/ Gists / JavaScript

Gists - JavaScript

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

JS / jQuery: Caching selectors

JavaScript

caching.js #

function Selector_Cache() {
    var collection = {};
    function get_from_cache( selector ) {
        if ( undefined === collection[ selector ] ) {
            collection[ selector ] = $( selector );
        }
        return collection[ selector ];
    }
    return { get: get_from_cache };
}

var selectors = new Selector_Cache();

// Usage $( '#element' ) becomes
selectors.get( '#element' );

On gists

JS - round, floor, ceil obj - Decimal precision

JavaScript-OOP JavaScript

decimalperecision.js #

var DecimalPrecision = (function(){
	if (Number.EPSILON === undefined) {
		Number.EPSILON = Math.pow(2, -52);
	}
	this.round = function(n, p=2){
		let r = 0.5 * Number.EPSILON * n;
		let o = 1; while(p-- > 0) o *= 10;
		if(n < 0)
			o *= -1;
		return Math.round((n + r) * o) / o;
	}
	this.ceil = function(n, p=2){
		let r = 0.5 * Number.EPSILON * n;
		let o = 1; while(p-- > 0) o *= 10;
		if(n < 0)
			o *= -1;
		return Math.ceil((n + r) * o) / o;
	}
	this.floor = function(n, p=2){
		let r = 0.5 * Number.EPSILON * n;
		let o = 1; while(p-- > 0) o *= 10;
		if(n < 0)
			o *= -1;
		return Math.floor((n + r) * o) / o;
	}
	return this;
})();

On gists

Change URL - pushstate

JavaScript

example.html #

<html>
<head>
<link rel="stylesheet" type="text/css" href="url_style.css">
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
function changeurl(url)
{
 var new_url="/Your URL/"+url;
 window.history.pushState("data","Title",new_url);
 document.title=url;
}
</script>
</head>
<body>
<div id="wrapper">

<div id="url_link">
 <p id="url_label">Click On Languages To Change URL</p>
 <li onclick="changeurl('PHP');">PHP</li>
 <li onclick="changeurl('HTML');">HTML</li>
 <li onclick="changeurl('CSS');">CSS</li>
 <li onclick="changeurl('JavaScript');">JavaScript</li>
 <li onclick="changeurl('jQuery');">jQuery</li>
</div>

</div>
</body>
</html>

On gists

pubsub - cache obj

JavaScript

pubsub.js #


;(function(d){

	// the topic/subscription hash
	var cache = {};

	d.publish = function(/* String */topic, /* Array? */args){
		// summary: 
		//		Publish some data on a named topic.
		// topic: String
		//		The channel to publish on
		// args: Array?
		//		The data to publish. Each array item is converted into an ordered
		//		arguments on the subscribed functions. 
		//
		// example:
		//		Publish stuff on '/some/topic'. Anything subscribed will be called
		//		with a function signature like: function(a,b,c){ ... }
		//
		//	|		$.publish("/some/topic", ["a","b","c"]);
		cache[topic] && d.each(cache[topic], function(){
			this.apply(d, args || []);
		});
	};

	d.subscribe = function(/* String */topic, /* Function */callback){
		// summary:
		//		Register a callback on a named topic.
		// topic: String
		//		The channel to subscribe to
		// callback: Function
		//		The handler event. Anytime something is $.publish'ed on a 
		//		subscribed channel, the callback will be called with the
		//		published array as ordered arguments.
		//
		// returns: Array
		//		A handle which can be used to unsubscribe this particular subscription.
		//	
		// example:
		//	|	$.subscribe("/some/topic", function(a, b, c){ /* handle data */ });
		//
		if(!cache[topic]){
			cache[topic] = [];
		}
		cache[topic].push(callback);
		return [topic, callback]; // Array
	};

	d.unsubscribe = function(/* Array */handle){
		// summary:
		//		Disconnect a subscribed function for a topic.
		// handle: Array
		//		The return value from a $.subscribe call.
		// example:
		//	|	var handle = $.subscribe("/something", function(){});
		//	|	$.unsubscribe(handle);
		
		var t = handle[0];
		cache[t] && d.each(cache[t], function(idx){
			if(this == handle[1]){
				cache[t].splice(idx, 1);
			}
		});
	};

})(jQuery);




$.subscribe("test", function(a,b) {
	console.log(arguments);
	
});

$('button').on('click', function(e){
$.publish("test", [e, "a","b"]);	
});


/*
OUTPUT:

Arguments(3) [j…y.Event, "a", "b", callee: ƒ, Symbol(Symbol.iterator): ƒ]0: jQuery.Event {originalEvent: MouseEvent, type: "click", isDefaultPrevented: ƒ, timeStamp: 2187.000000005355, jQuery112409936550241987452: true, …}1: "a"2: "b"callee: ƒ (a,b)length: 3Symbol(Symbol.iterator): ƒ values()__proto__: Object

*/




On gists

Trolling literal object

JavaScript-OOP JavaScript

trolling.js #

$(function () {
			var Trolling = {
				displayRandom: 210,
				carouselDelay: 2000,
				Trolling: $('.face'),
				input: $('#searchQuery'),
				init: function () {
					this.Trolling.hide();
					this.input.on('keyup', $.proxy(this.search, this));
					this.input.focus();
					this.createIndex();
					this.carouselPlay();
				},
				index: {},
				createIndex: function () {
					var me = this;
					this.Trolling.each(function () {
						me.index[$.trim($(this).text()).toLowerCase()] = $(this);
					});
				},
				search: function () {
					var searching = $.trim(this.input.val()).toLowerCase();
					if (searching == "") {
						this.Trolling.hide();
						this.carouselPlay();

					} else {
						this.carouselStop();

						$.each(this.index, function (key, val) {
							if (key.indexOf(searching) != -1) {
								val.show();
							} else {
								val.hide();
							}
						});
					}
				},
				carouselTimer: null,
				carouselPlay: function () {
					if (this.carouselTimer) {
						this.carouselStop();
					}

					this.carouselTimer = setInterval($.proxy(this.carousel, this), this.carouselDelay);
					this.randomTrolling(this.displayRandom).show();
				},
				carouselStop: function () {
					clearInterval(this.carouselTimer);
					this.carouselTimer = false;
					this.Trolling.stop();
					this.Trolling.css({opacity:1});
					this.Trolling.hide();
				},
				carousel: function () {
					var hidden = this.randomHidden();
					var visible = this.randomVisible();

					visible.before(hidden);
					visible.fadeOut('slow', $.proxy(function () {
						hidden.fadeIn('slow');
					}, this));
				},
				randomVisible: function (){
					return this.randomTrolling(1, this.Trolling.find(':visible')).closest('.face');
				},
				randomHidden: function (){
					return this.randomTrolling(1, this.Trolling.find(':hidden')).closest('.face');
				},
				randomTrolling: function (num, Trolling) {
					if (typeof num === 'undefined') {
						num = 1;
					}
					if (typeof Trolling === 'undefined') {
						Trolling = this.Trolling;
					}

					var max = Trolling.length - num;
					var start = Math.floor(Math.random() * max);
					return Trolling.slice(start, num + start);
				}
			};

			Trolling.init();
		});

On gists

JS OOP ways - Zdrojak.cz

JavaScript-OOP JavaScript

1.js #

/// 1. Jediná globální proměnná /// 

var myApplication =  (function(){
        function(){
            /*...*/
        },
        return{
            /*...*/
        }
})();

On gists

Test rychlosti psaní

JavaScript jQuery-plugins

test.js #

$('[name=psani]').keyup(function(){
    
    var chars = $(this).val().split("");
    var vzor = $("#vzor").text().split("");
    var correctIndex = -1;
    for(var i in chars){
        if(chars[i] == vzor[i]){
            correctIndex = parseInt(i);
        }else{
            break;
        }
    }
    var correct = '';
    var wrong = '';
    
    if(correctIndex !== -1){
        var correct = $("#vzor").text().substring(0,correctIndex+1);
    }
    if(chars.length > correctIndex+1){
        var wrong = $("#vzor").text().substring(correctIndex+1, chars.length);
    }
    var rest = $("#vzor").text().substring(chars.length, vzor.length-1);
    
    $('#display')
    .html('<span id="correct">'+correct+'</span><span id="wrong">'+wrong+'</span>'+rest);
    
    $('#auticko').css('left', $('#draha').width() * ((correctIndex+1) / vzor.length));
    
}).keyup();

On gists

Vanilla JS equivalents of jQuery methods

JavaScript jQuery

README.md #

Sans jQuery

Events

// jQuery
$(document).ready(function() {
  // code
})

// Vanilla
document.addEventListener('DOMContentLoaded', function() {
  // code
})
// jQuery
$('a').click(function() {
  // code…
})

// Vanilla
[].forEach.call(document.querySelectorAll('a'), function(el) {
  el.addEventListener('click', function() {
    // code…
  })
})

Selectors

// jQuery
var divs = $('div')

// Vanilla
var divs = document.querySelectorAll('div')
// jQuery
var newDiv = $('<div/>')

// Vanilla
var newDiv = document.createElement('div')

Attributes

// jQuery
$('img').filter(':first').attr('alt', 'My image')

// Vanilla
document.querySelector('img').setAttribute('alt', 'My image')

Classes

// jQuery
newDiv.addClass('foo')

// Vanilla
newDiv.classList.add('foo')
// jQuery
newDiv.toggleClass('foo')

// Vanilla
newDiv.classList.toggle('foo')

Manipulation

// jQuery
$('body').append($('<p/>'))

// Vanilla
document.body.appendChild(document.createElement('p'))
// jQuery
var clonedElement = $('#about').clone()

// Vanilla
var clonedElement = document.getElementById('about').cloneNode(true)
// jQuery
$('#wrap').empty()

// Vanilla
var wrap = document.getElementById('wrap')
while(wrap.firstChild) wrap.removeChild(wrap.firstChild)

Transversing

// jQuery
var parent = $('#about').parent()

// Vanilla
var parent = document.getElementById('about').parentNode
// jQuery
if($('#wrap').is(':empty'))

// Vanilla
if(!document.getElementById('wrap').hasChildNodes())
// jQuery
var nextElement = $('#wrap').next()

// Vanilla
var nextElement = document.getElementById('wrap').nextSibling

AJAX

GET

// jQuery
$.get('//example.com', function (data) {
  // code
})

// Vanilla
var httpRequest = new XMLHttpRequest()
httpRequest.onreadystatechange = function (data) {
  // code
}
httpRequest.open('GET', url)
httpRequest.send()

POST

// jQuery
$.post('//example.com', { username: username }, function (data) {
  // code
})

// Vanilla
var httpRequest = new XMLHttpRequest()
httpRequest.onreadystatechange = function (data) {
  // code
}
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
httpRequest.open('POST', url)
httpRequest.send('username=' + encodeURIComponent(username))

JSONP

// jQuery
$.getJSON('//openexchangerates.org/latest.json?callback=?', function (data) {
  // code
})

// Vanilla
function success(data) {
  // code
}
var scr = document.createElement('script')
scr.src = '//openexchangerates.org/latest.json?callback=formatCurrency'
document.body.appendChild(scr)

More

Here are a few additional references demonstrating vanilla javascript equivalents of jquery methods:

Also, see the two part series showing equivalents for ...


On gists

Private members and prototypes

JavaScript-OOP JavaScript

example.js #

function Dog(name, color) {
    //private members
    var name = name,
        color = color;

    //public method
    this.getColor = function () {
        return color;
    }
    //public method
    this.getName = function () {
        return name;
    }
}
Dog.prototype = (function () {
    //private member
    var breed = 'French Bulldog',
    
    //private method
    getBreed = function () {
        return breed;
    };
    
    //public interface
    return {
        getBreed: function () {
            return breed;
        },
        getMessage: function () {
            return this.getColor() + ' dog, ' + 
                getBreed() + ' breed, named ' + 
                this.getName() + ' is missing';
        }
    }
})();