how to use jquery easing

I have been use jQuery for a long time, but quite know about the multiple effect of the easing plugin, today i find some thing useful, and summary it here.

You must introduce the plugin after your jquery invoke.

1.Change the default animate effect of jQuery

jQuery.easing.def = "effect-string";

With this code in the top of your js code, then the default animate effect will change to the string you defined.

2.Make a difference of your multiple action, for example:

$(ele).animate({
   top: "+200",
   right: "-=100"
},{
   specialEasing:{
     top: 'swing',
     right: 'easeOutBounce'
   }
});

or

$(ele).animate({
   top: [500, 'swing'],
   right: [200, 'easeOutBounce']
},{
   specialEasing:{
     top: 'swing',
     right: 'easeOutBounce'
   }
});

You can use it after the version 1.4.

simulate placeholder with jQuery

I just want to use the html5′s form api, but it is not available for ie. This is just a polyfill, you can use it with the Modernizr library.

jQuery.extend( jQuery.expr[':'], {
  'placeholder': function( elem ){
    var attr = elem.getAttribute( "placeholder" ), val = elem.placeholder, n = elem.nodeName.toLowerCase();
    return n === 'input' && attr !== 'undefined' && '' !== val;
    }
});

$(':placeholder').each(function(){
  $(this).css('color', '#a9a9a9').val($(this).attr('placeholder'));
}).bind('focus', function(){
  if ($(this).val() == $(this).attr('placeholder')) {
    $(this).val('');
  }
}).bind('blur', function(){
  if ($(this).val() == '') {
    $(this).val($(this).attr('placeholder'));
  };
});

quick tips:jquery background color animation

There is one jquery color animations plugin in the official website of jquery, which is the weakness of jquery and i have not used it before. I happened to find the snippet about how to use it.

With this plugin you can do many things that the animate function can’t do, something like border color animation, background color animation and font color animation and more of (color, backgroundColor, borderColor, borderBottomColor, borderLeftColor, borderRightColor, borderTopColor, outlineColor), that will make your site amazing and more attractive to your visitors.

You can find the plugin by visiting jquery background color animation of the jquery offical website.

Awesome plugin! The usage of it is very simple, just pass the name and color that you want to make a animation as one json object to the animate function of jquery, something like this:

	element.animate({borderColor: '#F2E2CE', backgroundColor: '#400101', borderColor: '#F2E2CE'});

Jquery color plugin official website: http://www.bitstorm.org/jquery/color-animation/

There are perfect demos here, have your funs.

jQuery Deferred tutorial

I have been reading about the jquery Deferred object for one whole day, i don’t think i can use with it very well , but now i will summary what i learned, if you are knowing it better and more usage, please tell me.

In my option, the deferred object can do one thing and do it very well: provides flexible ways to provide multiple callbacks, and these callbacks can be invoked regardless of whether the original callback dispatch has already occurred.

Three status of it: unresolved, resolved, rejected of the actions.

I shall not show you many examples, only show you about my mind of the Deferred class.

There are 11 methods of the Deferred Object, excatly of the Deferred’s promise object.Because if you use the asynchronous function like ajax, in jQuery 1.6 it will return you one instance of the Deferred’s promise object, or if you excute your function with $.when(), both the cases should return the promise object( For the function or jquery object, you should use the promise method to make the promise object before using the multiple callback functions ).

You can find online example in the jQuery’s offical website jQuery promise and deferred.promise().

Maybe you don’t get what you want learn from it, but what i want to tell you is that , read the official website of this chapter one or more times, you will find much power from it.

Here is some sites of jQuery Deferred tutorial for you:
1. Official website of jQuery of the Deferred: http://api.jquery.com/category/deferred-object/.
2. Some example i found for help: http://www.erichynds.com/jquery/using-deferreds-in-jquery/

Use jQuery expressions to custom jQuery selectors

I mean this is an old topic, and i think it simple as mostly it just one line’s code to accomplish the function, may be you use a function to do it before, i will show you how to make it a selector of jQuery and use it just like as simple as :text, :checked ect do.

First, let us see samples in jQuery sourse:

		enabled: function( elem ) {
			return elem.disabled === false && elem.type !== "hidden";
		},

		disabled: function( elem ) {
			return elem.disabled === true;
		},

		checked: function( elem ) {
			return elem.checked === true;
		},

		selected: function( elem ) {
			// Accessing this property makes selected-by-default
			// options in Safari work properly
			if ( elem.parentNode ) {
				elem.parentNode.selectedIndex;
			}

			return elem.selected === true;
		},

		parent: function( elem ) {
			return !!elem.firstChild;
		},

		empty: function( elem ) {
			return !elem.firstChild;
		},

		has: function( elem, i, match ) {
			return !!Sizzle( match[3], elem ).length;
		},

		header: function( elem ) {
			return (/h\d/i).test( elem.nodeName );
		},

		text: function( elem ) {
			var attr = elem.getAttribute( "type" ), type = elem.type;
			// IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc)
			// use getAttribute instead to test this case
			return "text" === type && ( attr === type || attr === null );
		},

		radio: function( elem ) {
			return "radio" === elem.type;
		},

		checkbox: function( elem ) {
			return "checkbox" === elem.type;
		},

		file: function( elem ) {
			return "file" === elem.type;
		},
		password: function( elem ) {
			return "password" === elem.type;
		},

		submit: function( elem ) {
			return "submit" === elem.type;
		},

		image: function( elem ) {
			return "image" === elem.type;
		},

		reset: function( elem ) {
			return "reset" === elem.type;
		},

		button: function( elem ) {
			return "button" === elem.type || elem.nodeName.toLowerCase() === "button";
		},

		input: function( elem ) {
			return (/input|select|textarea|button/i).test( elem.nodeName );
		}

All of these filters are one line code, So it will be very easy to custom your own expresssion.
To custom your own filter, here is the syntax:

	jQuery.extend(jQuery.expr[':'], {
		EXPRESSION_NAME: "EXPRESSION_RULE"
	});

One example:

jQuery.extend(jQuery.expr[':'], {
    submitable: function(a) {
        return !a.disabled&&(a.selected||a.checked||(a.nodeName.toUpperCase()=='TEXTAREA')||(a.nodeName.toUpperCase()=='INPUT'&&(a.type=='text'||a.type=='hidden'||a.type=='password')));
    },
    nothidden: function(a) {
        return a.type&&a.type!='hidden';
    }
})

You can custom your own selectors with jQuery expressions whatever you can , that’s up to your site.

Quick Tips:event.preventDefault() and event.stopPropagation and event.stopImmediatePropagation

I belive many of you have used return false for an click event to prevent from visiting link address of ‘#’, do you know what have been happened when you code return false?
Look at this demo:

$('a').click(function(){
	# some code
	return false;
});

It seems to have done the right job, but it is misused this time,do you know what happened behind the screen when you click the link?First, you got your goal, you have prevent to visiting the link,here it is the event.preventDefault() make the sense, other more, you have also prevent event.stopPropagation and the callback function below the return false.

So , it has greatly increase the brittleness of your code to use return false at this time.
If you just want to prevent the default behavior of your click event, you only need to preventDefault, the right usage:

$('a').click(function(event){
	# some code
	event.preventDefault();
});

That is the event.preventDefault(), but what is stopPropagation?

$('a').click(function(event){
	event.preventDefault();
	event.stopPropagation();
	console.log('You have clicked the link.');
});

$('#demo').click(function(){
	$(this).toggleClass('yellow');
	console.log('You have clicked the demo div.');
});

The html is a div and inside it is a link address, with a yellow background class.You may find there is one line of event.stopPropagation(), the case you do not write this, when you click on the div or the link address, the div will be attach the yellow class, but with this line, when you click on the link address, the div will not change backgroud to yellow.It stops bubbling to the parent click event.

Another event here is event.stopImmediatePropagation:

$('a').click(function(event){
	event.preventDefault();
	console.log('Click on the link one time.');
});
$('a').click(function(event){
	event.preventDefault();
	event.stopImmediatePropagation();
	console.log('Click on the link two time.');
});
$('a').click(function(event){
	event.preventDefault();
	console.log('Click on the link three time.');
});
$('a').click(function(event){
	event.preventDefault();
	console.log('Click on the link four time.');
});

Above example will print ‘Click on the link one time.’ and ‘Click on the link two time.’,the third and forth print will not occur.Your page may have many plugin or event for one element, you can use stopImmediatePropagation to not fire the next operation.

Here you know what is the difference in event.preventDefault() and event.stopPropagation and event.stopImmediatePropagation.But where should i put them in my code?

Acctually, the last two events can be put in any place in your callback function, but positon of event.preventDefault can be different.

$('a').click(function( event ){
	event.preventDefault();
	func(); // undefined function
});
// use both these two snippets
$('a').click(function( event ){
	func(); // undefined function
	event.preventDefault();
});

After exam it, you will find that the first snippet will not visit the ‘#’ address, and then appear the error,but the next snippet will visit the address with the error notice comes first.
Summary:Use the Right Method of event.preventDefault() and event.stopPropagation and event.stopImmediatePropagation for the Job!

Tricks:call and apply methods in javascript

You may had seen .call or .apply in javascript code, do you wonder about them?That what you will know from this article.
As we know, each function as an object has many methods themselves, a toString() method will not be strange with you.
That’s it, you can invoke it without defining it, and so are .call and .apply methods in javascript.

One example of .toString():

	function bar(){
		# some code
	}

	console.log(bar.toString());

In my option, the call and apply methods is used to told what object to reference at the script runtime! That’s just it!

	var x = 'test',
		obj = { x: 'value' };
	function bar(){
		console.log(this.x);
	}

	bar(); // log 'test'
	bar.call(obj);  // log 'value'
	bar.apply(obj); // log 'value'

The above code show u how to use the methods, The apply() method is identical to call(), is it? NO, just different from the arguments!

	var x = 'test',
		y = 'name',
		obj = { x: 'value' };

	function bar(arg1, arg2){
		console.log(this.x, arg1, arg2);
	}

	bar.call(obj, x, y); // log 'value', 'test', 'name'
	bar.apply(obj, [x, y]); // log 'value', 'test', 'name'

You can see from the example that .call method’s argument are string and .apply method’s argument is an array, this is quit useful when there are many arguments to pass into the function.

To let you know more, here is another example:
Inside every function , you can use arguments as a collection of arguments, it feels like an array object, but arguments only has the length property, and no other methods , like pop, push methods.
So, what can we do with it?Look at the example blow:

	var o = { x: 15 };
	function f(message1, message2)
	{
	    alert(message1 + (this.x * this.x) + message2);
	}

	function g(object, func)
	{
	    var args = []; // empty array
	    // copy all other arguments we want to "pass through"
	    for(var i = 2; i < arguments.length; i++)
	    {
	        args.push(arguments[i]);
	    }

	    func.apply(object, args);
	}
	g(o, f, "The value of x squared = ", ". Wow!");

Awesome! I believe many of us had use arguments, and you can do more work with it! .call and .apply methods appear in many function and jQuery plugin.So learn it and use it!

Parse jQuery getScript

I am used to work with jQuery framwork, but when it come to javascript, many words and expressions i have never heard of or used.This time i find the getScript method of jQuery, and someone had made a function to be used. I think it be useful , when you need to use jQuery within a tiny work. At this time, you can only use this function, and do the same thing as you did with jQuery.

For short, it is used to import script dynamicly, so the browser will not cache your script, and you can have a callback function ,when the script is loaded successfully.

Here is the getScript function:

	function getScript(url, callback){
		var head = document.documentElement,
		script = document.createElement("script");
		script.src = url;

		var done = false;

		//Attach handlers for all browsers
		script.onload = script.onreadystatechange = function(){
			if (!done && (!this.readyState || this.readyState === "loaded" || this.readyState === "complete")){
				done = true;

				callback();

				//handle memory leak in IE
				script.onload = script.onreadystatechange = null;
				if (head && script.parentNode) {
					head.removeChild(script);
				}
			}
		};

		//use insertBefore instead of appendChild to circumvent an IE6 bug.
		//this arises when a base node is used
		head.insertBefore(script,head.firstChild);

		//we handle everything using the script element injection
		return 'scriptinjected!';
	}

Usage:

	getScript('scriptsrc', function(){
		// some code
	});

Enjoy this article? Please leave a word about your options about this getScript function.

jQuery delegate plugin

Actually i want to find solution for jQueyr.event for my problem, but i find one jQuery method i have not seen before, and i find the reason for why is it not very widely used is that the .live method. And i want you know .delegate method of jQuery.

About .delegate:

//Basic syntax:
.delegate( selector, eventType, handler )
.delegate( selector, eventType, eventData, handler )
.delegate( selector, events )

$("table").delegate("td", "hover", function(){
	$(this).toggleClass("hover");
});

 // Is equivalent to the following code

$("table").each(function(){
	$("td", this).live("hover", function(){
		$(this).toggleClass("hover");
	});
});

It is almost the same function with .live , to bind event to the selector now and the selector future.But what i want to show you is that let it support a delegate method that takes a map.Very simple jQuery delegate plugin.

	(function($) {
		$.fn.delegate = function(selector, types, data, fn) {
			if (typeof selector === "object") {
				for (var sel in selector) {
					for (var type in selector[sel]) {
						this.live(type, data, selector[sel][type], sel);
					}
				}
			return this;
			} else {
				return this.live(types, data, fn, selector);
			}
		};
	})(jQuery);

Simply Usage:

	$('#header').delegate({
		'img' : {
				'click dblclick':function(){
				console.log('clicked')
			}
		},
		'li' : {
			mouseover:function(){
				console.log('over')
			},
			mouseout:function(){
				console.log('out')
			}
		}
	}, {foo:123 , bar:456});

May be it is not very perfect, and can not meet your need, and you can modify it for yourself.

Throttle function in javascript

I happen to realize that when validating username in my site, i should control the request time of the ajax request, my validation was that when user click on the keyboard, this will trigger the javascript keyup event, then do the ajax validation within the event.
Assume the case , when user just trigger the keyup function and the script is doing validating, but he has not finished writing , one again he input another letter, so it will duplicate that step.It result in so much request unnecessary request to the server, as everyone knows that you don’t want the extra request to your server.
What you can do is to throttle the Ajax request after your input immediately, this step is very important, but how many of you have done so?
You can do like this:

function throttle(fn, delay) {
  var timer = null;
  return function () {
    var context = this, args = arguments;
    clearTimeout(timer);
    timer = setTimeout(function () {
      fn.apply(context, args);
    }, delay);
  };
}

// so when you do this with jQuery, here is what you should do
$('input.username').keypress(throttle(function (event) {
  // do the Ajax request
}, 250));

Above code is my solution, the validation will be fired in delay micro-seconds, and if there are a series of event , it will throttle the extra requests.