/ Gists / JavaScript

Gists - JavaScript

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';
        }
    }
})();

On gists

Jquery tiny slider - binding via events

JavaScript jQuery jQuery-plugins

slider.js #

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


  return this.each(function() {
    var $img = $(this),
      current = 0;

		  function show(index) {
		  var total = options.images.length;

		  while(index < 0)
      {
		    index += total;
        
      }
		  while(index >= total)
      {
		    index -= total;
        
      }
		  current = index;
		  $img.attr('src', options.images[index]);
		}

		function prev() {
		  show(current - 1);
		}

		function next() {
		  show(current + 1);
		}
    
      $img.bind('prev', prev)
      .bind('next', next)
      .bind('goto',function(e, index) {
  			show( index );
		});


    });



   
  };
})(jQuery);
    

On gists

Formulář jako objekt - můj výtvor

JavaScript-OOP JavaScript

formjs-object-my.js #


	(function() {
 
		var Form = {
			init: function(config) 
			{
				this.form            = config.form;
				this.mandatoryFields = this.form.find('input[name="name"], input[name="phone"], input[name="email"], input[name="date"], input[name="time"], input[name="persons"]');
				this.url             = this.form.attr('action');
				this.submitButton    = this.form.find('button');
				this.binds();
			},

			binds: function()
			{
				var self = this;
				this.submitButton.on('click', function(e){
					e.preventDefault();
					var formData = self.form.serialize();
					self.dispatch(formData);
				});
			},
			formFieldCleaner(formObject)
			{ 
				$(":input", formObject).not(":button, :submit, :reset, :hidden")
									   .val("")
									   .removeAttr("checked")
									   .removeAttr("selected"); 
			},
			showErrors: function(error)
			{
				var self = this;

				this.mandatoryFields.removeClass('-error');
				$('#form-message-success').html('')
										  .hide();
										  
				$('#form-message-error').show()
										.html(error.msg.join('<br />'));

				$.each(error.missingField, function(){

					self.form.find('input[name="'+this+'"]')
					              .addClass('-error');
				});
			

			},
			showSuccess: function(msg)
			{
				this.mandatoryFields.removeClass('-error');	
				this.formFieldCleaner(this.form);
				$('#form-message-error').html('')
										.hide();
										
				$('#form-message-success').show()
										  .html(msg)
										  .delay(5000)
										  .fadeOut(800);
			},
			dispatch: function(formData) 
			{
		
				
				var self = this;
				var xhr = $.post(this.url, formData);

				xhr.done(function(json){
					
					json = JSON.parse(json);

					// chyba
					if (json.error.state)
					{
						self.showErrors(json.error);
					}
					else
					{
						self.showSuccess(json.success.message);
					}


				});
			}
		};

		Form.init({
			form: $('#reservation-form')
		});

		})();

On gists

Is element in viewport?

JavaScript Helpers-Filters-Plugins

is-in-viewport.js #

/**
 * Check if DOM element is in browsers view port
 * @param el The element
 * @return boolean
 */
function isInViewport(el) {
    var rect = el.getBoundingClientRect();

    return (
        rect.bottom >= 0 &&
        rect.right >= 0 &&

        rect.top <= (
            window.innerHeight ||
            document.documentElement.clientHeight) &&

        rect.left <= (
            window.innerWidth ||
            document.documentElement.clientWidth)
    );
}