/ Gists / jQuery

Gists - jQuery

On gists

Deferrers examples

jQuery

short-chaining.js #

var deferred = $.Deferred();

deferred.then(function(value) {
    alert(value);
    return 42;
}).then(function(id){
    alert('The answer : ' + id);
});

console.log(deferred)
deferred.resolve("hello world");




var deferred = $.Deferred();
deferred.done(function(value) {
    alert(value[0]);
}).done(function(value){
    alert(value[1]);
});

deferred.resolve(["hello world", "goodbye, cruel world"]);

On gists

Animation by queue (own logic or std queue) - DEFERRERS

jQuery

animation-queue.js #

$(function () {

    // 1 by QUEUE
    // $.each([$('#fade-el-1'), $('#fade-el-2'), $('#fade-el-3'), $('#fade-el-4')], function () {
    //     var $this = this;
    //     $(document).queue('text-animate', function (next) {
    //         animateText($this, next);
    //     });
    // });

    // $(document).dequeue('text-animate');


    // BY MY OWN QUEUE LOGIC
    var objectsToAnimate = [];
    $('.hidden-fade').each(function () {
        objectsToAnimate.push($(this));
        
    });

    animate(objectsToAnimate, finished);
    //animate([$('#fade-el-1'), $('#fade-el-2'), $('#fade-el-3'), $('#fade-el-4')], finished);

    function finished() {
        //console.log('Finished');
    }
    
    function animate(list, callback) {
        if (list.length === 0) {
            callback();
            return;
        }
        $el = list.shift();

        animateText($el, function () {
            animate(list, callback);
        });

    }


    function animateText($element, $callback) {

        var $this = $element;
        var $wordList = $this.text().split("");
        $this.text("");
        $this.css('opacity', 1);

        $.each($wordList, function (idx, elem) {
            var newEL = $("<span/>").text(elem).css({
                opacity: 0
            });
            newEL.appendTo($this);
            newEL.delay(idx * 125);
            newEL.animate({
                opacity: 1
            }, 500, 'swing', function () {
                if ($wordList.length === idx + 1) {
                    $callback();
                }
            });
        });

        
    };
    

    
  });

On gists

Souřadnice / procenta na obrázku

jQuery

script.js #

$("#test").mousemove(function(e){
    var percx = e.offsetX/ $(this).width() * 100;
    var percy = e.offsetY/ $(this).height() * 100;
    $('#vystup').html(percx + " | " + percy + " perc");
});

On gists

Rescue modal

jQuery jQuery-plugins

rescue-modal.js #

var rescueModal = (function(){


    $(document).ready(function() {

        var modalShow = sessionStorage.getItem('rescue-modal') || 0;

        console.log(document.location);
        
        

        if (modalShow)
            return;

        $('head').append('<link rel="stylesheet" href="http://vhgastro-modal.r.dev.andweb.cz/rescue-modal.css" type="text/css" />');

        var recenter = function() {
            var modalWrapper = $('.modal-wrapper');
            var h = modalWrapper.outerHeight(true) / 2;
            modalWrapper.css('margin-top',  '-' + h + 'px');
        };

        var modalClose = function() {
            modalOverlay.hide();
            modalWrapper.hide()
        };
        
        
        var modalOverlay = $('<div class="modal-overlay"></div>');
        var modalWrapper = $('<div class="modal-wrapper"></div>');
        var htmlTpl = "<h1>Důležité upozornění</h1> \
            <p>Náš e-shop právě prochází rozsáhlou rekonstrukcí. Uvedené ceny a dostupnosti u produktů jsou proto pouze orientační.</p> \
            <p>Pro ověření Vaší objednávky nás kontaktujte na e-mailu: <a href=''mailto:info@vhgastro.cz'>info@vhgastro.cz</a>, nebo na telefonním čísle: +<b>420 603 256 194</b>.</p> \
            <p>Děkujeme za pochopení.</p> \
            <p>Tým HOFMANN Strakonice s.r.o.</p> \
            <a class='btn-navigation active'>&times; Zavřít</a> \
            ";

        modalWrapper.html(htmlTpl);
        modalOverlay.hide().prependTo(document.body);
        modalWrapper.hide().prependTo(document.body);
        
        modalWrapper.find('a.btn-navigation').on('click', function(e){
            modalClose();
        });

    
        setTimeout(function(){
            recenter();
            modalOverlay.show();
            modalWrapper.show();
        }, 500);


        sessionStorage.setItem('rescue-modal', 1);
     

    });  

})();

On gists

Jsonp, json, js to html from another domain

JavaScript jQuery JSON

index.html #

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src='//cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js'></script>
</head>
<body>

    <!-- https://www.sitepoint.com/jsonp-examples/ -->

    <div style="background: goldenrod; padding: 1rem;">
        <script src="http://lab.rjwebdesign.cz/jsonp/js.php"></script>
    </div>

    <div style="background: burlywood; padding: 1rem;" id="jsonp">
    
    </div>
    <script>
   
        // 1 zpusob
        $.getJSON('http://lab.rjwebdesign.cz/jsonp/jsonp.php?callback=?', function(json){
            console.log(json);
        });

        // 2 zpusob
        function logResults(json) {
            console.log(json);
        }

        $.ajax({
        url: "http://lab.rjwebdesign.cz/jsonp/jsonp.php",
        dataType: "jsonp",
        jsonpCallback: "logResults"
        });
    </script>

</body>
</html>

On gists

Document, element, outside click, propagation

JavaScript jQuery

example.js #

// 1
$(document).click(function(e){

   if($(e.target).closest('#dropdownID').length != 0) return false;
   $('#dropdownID').hide();
});


// 2
$('body').click(function(e) {
    if ($(e.target).closest('.notification-container').length === 0) {
        // close/animate your div
    }
});


//3, https://www.tutorialrepublic.com/faq/hide-dropdown-menu-on-click-outside-of-the-element-in-jquery.php
$(document).ready(function(){
        // Show hide popover
        $(".dropdown").click(function(){
            $(this).find(".dropdown-menu").slideToggle("fast");
        });
    });
    $(document).on("click", function(event){
        var $trigger = $(".dropdown");
        if($trigger !== event.target && !$trigger.has(event.target).length){
            $(".dropdown-menu").slideUp("fast");
        }            
    });

// 4, http://benalman.com/projects/jquery-outside-events-plugin/
$(document).ready(function(){
    $(".notification-button").click(function(){
        $('.notification-container').toggle().animate({"margin-top":"0px"}, 75); 
    }); 

    $('.notification-wrapper').bind('clickoutside', function (event) {
        $('.notification-container').animate({"margin-top":"-15px"}, 75, function(){$(this).fadeOut(75)});
    });
});

On gists

Promises

jQuery

promises.html #

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
    <script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.js'></script>
</head>
<body>
    
<table border=1>
    <tr>
        <td>Num</td>
        <td>State</td>
    </tr>
    <tr>
        <td><a href="">1</a></td><td></td>
    </tr>
    <tr>
        <td><a href="">2</a></td><td></td>
    </tr>
    <tr>
        <td><a href="">3</a></td><td></td>
    </tr>
</table>

<script>
var promises = [];
var $a = $('a');
$.each($a, function() {
    var $this = $(this);

    var promise = $.get('/rq.php?num=' + $this.text());
    promise.done(function() {
        $this.parent().next().text('done!');
    });
    promises.push(promise);
});



if (jQuery.when.all===undefined) {
    jQuery.when.all = function(deferreds) {
        var deferred = new jQuery.Deferred();
        $.when.apply(jQuery, deferreds).then(
            function() {
                deferred.resolve(Array.prototype.slice.call(arguments));
            },
            function() {
                deferred.fail(Array.prototype.slice.call(arguments));
            });

        return deferred;
    }
}


$.when.all(promises).then(function(schemas) {
     console.log("DONE", this, schemas); // 'schemas' is now an array
}, function(e) {
     console.log("My ajax failed");
});


// $.when.apply($, promises).then(function() {
//    console.log(arguments);
//    console.log('DONE');
   
   
// });
</script>

</body>
</html>

On gists

Plugin - Slideshow (image/div) - tiny

jQuery jQuery-plugins

slideshow.js #

(function ($) {
    $.fn.slideShow = function (options) {

//           Supplying default options

        options = $.extend({
            timeOut: 3000,
            showNavigation: true,
            pauseOnHover: true,
            swipeNavigation: true
        }, options);


//        Variables
        var intervals = [],
            slideshowImgs = [],
            originalSrc,
            img,
            cont,
            width,
            height,

//        Creates an object with all the elements with a 'data-slideshow' attribute

            container = this.filter(function () {
                return $(this).data('slideshow');
            });

//        Cycle through all the elements from the container object
//        Later on we'll use the "i" variable to distinguish the separate slideshows from one another

        for (var i = 0; i < container.length; i++) {

            cont = $(container[i]);

            width = container.eq(i).outerWidth(true);
            height = container.eq(i).outerHeight(true);

//            For every separate slideshow, create a helper <div>, each with its own ID.
//            In those we'll store the images for our slides.

            var helpdiv = $('<div id="slideshow-container-' + i + '" class="slideshow" >');

            helpdiv.height(height);
            helpdiv.width(width);

//            If this option is enabled, call a function that appends buttons

            if (options.showNavigation) {
                createNavigation();
            }

//            Append the original image to the helper <div>

            originalSrc = cont.attr('src');
            img = $('<div class="slide" style="background-image: url(' + originalSrc + ')">');
            img.appendTo(helpdiv);

//            Append the images from the data-slideshow attribute

            slideshowImgs[i] = cont.attr('data-slideshow').split("|");

            for (var j = 0; j < slideshowImgs[i].length; j++) {

                img = $('<div class="slide" style="background-image: url(' + slideshowImgs[i][j] + ')">');
                img.appendTo(helpdiv);

            }

//            Replace the original element with the helper <div>

            cont.replaceWith(helpdiv);

//            Activate the slideshow

            automaticSlide(i)

        }


        // Functions

//          Slideshow auto switch

        function automaticSlide(index) {

            // Hide all the images except the first one
            $('#slideshow-container-' + index + ' .slide:gt(0)').hide();

            // Every few seconds fade out the first image, fade in the next one,
            // then take the first and append it to the container again, where it becomes last

            intervals[index] = setInterval(function () {
                    $('#slideshow-container-' + index + ' .slide:first').fadeOut("slow")
                        .next('.slide').fadeIn("slow")
                        .end().appendTo('#slideshow-container-' + index + '');
                },
                options.timeOut);
        }


//           Pause on hover and resume on mouse leave

        if (options.pauseOnHover) {
            (function hoverPause() {
                $('.slideshow').on({
                    'mouseenter.hover': function () {
                        clearInterval(intervals[($(this).attr('id').split('-')[2])])
                    },
                    'mouseleave.hover': function () {
                        automaticSlide($(this).attr('id').split('-')[2])
                    }
                });
            })()
        }


//          We use this to prevent the slideshow from resuming once we've stopped it

        function hoverStop(id) {
            $('#' + id + '').off('mouseenter.hover mouseleave.hover');
        }


//          Create the navigation buttons

        function createNavigation() {

//            The buttons themselves
            var leftArrow = $('<div class="leftBtn slideBtn hide">');
            var rightArrow = $('<div class="rightBtn slideBtn hide">');
//            Arrows for the buttons
            var nextPointer = $('<span class="pointer next"></span>');
            var prevPointer = $('<span class="pointer previous"></span>');

            prevPointer.appendTo(leftArrow);
            nextPointer.appendTo(rightArrow);

            leftArrow.appendTo(helpdiv);
            rightArrow.appendTo(helpdiv);
        }

//          Slideshow manual switch

        if (options.showNavigation) {

//            This shows the navigation when the mouse enters the slideshow
//            and hides it again when it leaves it

            $('.slideshow').on({
                'mouseenter': function () {
                    $(this).find('.leftBtn, .rightBtn').removeClass('hide')
                },
                'mouseleave': function () {
                    $(this).find('.leftBtn, .rightBtn').addClass('hide')
                }
            });

//            Upon click, stop the automatic slideshow and change the slide

            $('.leftBtn').on('click', function () {

                // Clear the corresponding interval to stop the slideshow
                // (intervals is an array, so we give it the number of the slideshow container)

                clearInterval(intervals[($(this).parent().attr('id').split('-')[2])]);

                // Make the last slide visible and set it as first in the slideshow container

                $(this).parent().find('.slide:last').fadeIn("slow")
                    .insertBefore($(this).parent().find('.slide:first').fadeOut("slow"));

                hoverStop($(this).parent().attr('id'));
            });

            $('.rightBtn').on('click', function () {

                // Clear the corresponding interval to stop the slideshow
                clearInterval(intervals[($(this).parent().attr('id').split('-')[2])]);

                // Fade out the current image and append it to the parent, making it last
                // Fade in the next one

                $(this).parent().find('.slide:first').fadeOut("slow")
                    .next('.slide').fadeIn("slow")
                    .end().appendTo($(this).parent());

                hoverStop($(this).parent().attr('id'));
            });
        }

//              Change slide on swipe

        // Same as the 'on click' functions, but we use hammer.js this time

        if (options.swipeNavigation) {
            $('.slideshow').hammer().on({
                "swiperight": function () {
                    clearInterval(intervals[($(this).attr('id').split('-')[2])]);

                    $(this).find('.slide:last').fadeIn("slow")
                        .insertBefore($(this).find('.slide:first').fadeOut("slow"))

                },
                "swipeleft": function () {
                    clearInterval(intervals[($(this).attr('id').split('-')[2])]);

                    $(this).find('.slide:first').fadeOut("slow")
                        .next('.slide').fadeIn("slow")
                        .end().appendTo($(this));
                }
            })
        }

    }
}(jQuery)
    )
;

On gists

Checkbox plugin

jQuery jQuery-plugins

checkbox.js #

(function($){
	$.fn.tzCheckbox = function(options){
		
		// Default On / Off labels:
		
		options = $.extend({
			labels : ['ON','OFF']
		},options);
		
		return this.each(function(){
			var originalCheckBox = $(this),
				labels = [];

			// Checking for the data-on / data-off HTML5 data attributes:
			if(originalCheckBox.data('on')){
				labels[0] = originalCheckBox.data('on');
				labels[1] = originalCheckBox.data('off');
			}
			else labels = options.labels;

			// Creating the new checkbox markup:
			var checkBox = $('<span>',{
				className	: 'tzCheckBox '+(this.checked?'checked':''),
				html:	'<span class="tzCBContent">'+labels[this.checked?0:1]+
						'</span><span class="tzCBPart"></span>'
			});

			// Inserting the new checkbox, and hiding the original:
			checkBox.insertAfter(originalCheckBox.hide());

			checkBox.click(function(){
				checkBox.toggleClass('checked');
				
				var isChecked = checkBox.hasClass('checked');
				
				// Synchronizing the original checkbox:
				originalCheckBox.attr('checked',isChecked);
				checkBox.find('.tzCBContent').html(labels[isChecked?0:1]);
			});
			
			// Listening for changes on the original and affecting the new one:
			originalCheckBox.bind('change',function(){
				checkBox.click();
			});
		});
	};
})(jQuery);

On gists

Colortip

jQuery jQuery-plugins

colortip.js #

(function($){
	$.fn.colorTip = function(settings){

		var defaultSettings = {
			color		: 'yellow',
			timeout		: 500
		}
		
		var supportedColors = ['red','green','blue','white','yellow','black'];
		
		/* Combining the default settings object with the supplied one */
		settings = $.extend(defaultSettings,settings);

		/*
		*	Looping through all the elements and returning them afterwards.
		*	This will add chainability to the plugin.
		*/
		
		return this.each(function(){

			var elem = $(this);
			
			// If the title attribute is empty, continue with the next element
			if(!elem.attr('title')) return true;
			
			// Creating new eventScheduler and Tip objects for this element.
			// (See the class definition at the bottom).
			
			var scheduleEvent = new eventScheduler();
			var tip = new Tip(elem.attr('title'));

			// Adding the tooltip markup to the element and
			// applying a special class:
			
			elem.append(tip.generate()).addClass('colorTipContainer');

			// Checking to see whether a supported color has been
			// set as a classname on the element.
			
			var hasClass = false;
			for(var i=0;i<supportedColors.length;i++)
			{
				if(elem.hasClass(supportedColors[i])){
					hasClass = true;
					break;
				}
			}
			
			// If it has been set, it will override the default color
			
			if(!hasClass){
				elem.addClass(settings.color);
			}
			
			// On mouseenter, show the tip, on mouseleave set the
			// tip to be hidden in half a second.
			
			elem.hover(function(){

				tip.show();
				
				// If the user moves away and hovers over the tip again,
				// clear the previously set event:
				
				scheduleEvent.clear();

			},function(){

				// Schedule event actualy sets a timeout (as you can
				// see from the class definition below).
				
				scheduleEvent.set(function(){
					tip.hide();
				},settings.timeout);

			});
			
			// Removing the title attribute, so the regular OS titles are
			// not shown along with the tooltips.
			
			elem.removeAttr('title');
		});
		
	}


	/*
	/	Event Scheduler Class Definition
	*/

	function eventScheduler(){}
	
	eventScheduler.prototype = {
		set	: function (func,timeout){

			// The set method takes a function and a time period (ms) as
			// parameters, and sets a timeout

			this.timer = setTimeout(func,timeout);
		},
		clear: function(){
			
			// The clear method clears the timeout
			
			clearTimeout(this.timer);
		}
	}


	/*
	/	Tip Class Definition
	*/

	function Tip(txt){
		this.content = txt;
		this.shown = false;
	}
	
	Tip.prototype = {
		generate: function(){
			
			// The generate method returns either a previously generated element
			// stored in the tip variable, or generates it and saves it in tip for
			// later use, after which returns it.
			
			return this.tip || (this.tip = $('<span class="colorTip">'+this.content+
											 '<span class="pointyTipShadow"></span><span class="pointyTip"></span></span>'));
		},
		show: function(){
			if(this.shown) return;
			
			// Center the tip and start a fadeIn animation
			this.tip.css('margin-left',-this.tip.outerWidth()/2).fadeIn('fast');
			this.shown = true;
		},
		hide: function(){
			this.tip.fadeOut();
			this.shown = false;
		}
	}
	
})(jQuery);