Jquery Tutorial : Advanced Concepts
Cache the
lengthproperty in loops:var arrayLength = myArray.length; for (var i = 0; i < arrayLength; i++) { //DO SOMETHING }Append content outside of loops
//BAD $.each(myArray, function(index, item) { var newTweet = '<li>' + item + '</li>'; $('#statuses').append(newTweet); }); //GOOD var newTweet = ''; $.each(myArray, function(index, item) { newTweet += '<li>' + item + '</li>'; }); $('#statuses').html(newTweet);
- Anonymous functions are often used when binding event handlers.
- However, anonymous functions are difficult to debug, maintain, test, or reuse.
It’s better to use object literals:
//BAD $(document).ready(function() { $('.status .delete').click(function(e) { //Do something }); $('.status').dblclick(function(e) { //Do the same thing }); }); //GOOD var bindingObject = { onReady : function() { $('.status .delete').click(bindingObject.deleteTweet); $('.status').dblclick(bindingObject.deleteTweet); }, deleteTweet : function(e) { //Do something } }; $(document).ready(bindingObject.onReady);
Here are some tips to keep in mind when using selectors:
Id selections are really fast. They are handled by
document.getElementById()// This is fast $('#statuses .status'); //This is faster $('#statuses').find('.status');Sizzle, the jQuery selector engine works bottom-up (right to left). Be more specific on the right side of your selector rather than on the left
//GOOD $('li.status .delete'); //BETTER $('.status img.delete');
Most of the jQuery methods act on selections. Those methods are in the
$.fnnamespace (also called the jQuery prototype).- Receive and return the selection as this.
The other jQuery methods do not act on selections and are in the
$namespace.![[Note]](../images/note.png)
Note You need to be aware that in some cases, while these two namespaces might have the same method name, they are in fact different methods (for instance,
$.fn.eachto iterate over each selected element in a selection and$.eachto iterate over an array or an object).- The utility methods that jQuery provides are very useful for doing routine programming tasks.
Here are some common jQuery utility methods. For more information, visit http://api.jquery.com/category/utilities/
$.trim(): This method removes leading and trailing whitespaces$.trim(' lots of extra whitespace '); //
$.each(): This method iterates over objects and arrays$.each(['apple','banana','peach'], function(index, value) { console.log('index: ' + index + ' value: ' + value); }); $.each({ firstname : 'laurent', lastname : 'tonon' }, function(key, value) { console.log(key + ' : ' + value); });$.inArray(): This method checks if a value is contained in an array. If found it returns the value’s index of the array. Returns -1 if the value is not foundvar myArray = [ 23, 46, 31, 12 ]; if ($.inArray(31, myArray) !== -1) { //
console.log('found it!');
}$.extend(): This method merges the properties of the first passed object using the properties of the other passed objects as arguments. The first object is modified and returned by the methodvar myFirstObject = { fruit : 'apple', vegetable: 'carrot' }; var mySecondObject = { fruit : 'banana' }; var resultingObject = $.extend(myFirstObject, mySecondObject); //
console.log(myFirstObject.fruit); //
console.log(resultingObject.fruit); // 
-
jQuery also provides methods to determine the type of a variable (
$.isFunction(),$.isPlainObject(),$.isArray())
-
As we have seen, jQuery makes extensive use of the
$variable. -
However, other JavaScript libraries like prototype make use of the
$variable sign as well, and might create conflicts. -
Of course, you could use the
jQueryvariable instead (the$variable is an alias to the jQuery variable) but it is obviously less convenient to type this in every instance. The following examples are the same:
//Using the $ variable $('.status').show(); //Using the jQuery variable jQuery('.status').show();To avoid conflicts, you can put jQuery in no-conflict mode as soon as it is loaded in the page using the
.noConflict()method:<script src="prototype.js"></script> <script src="jquery.js"></script> <script>var $j = jQuery.noConflict();</script>

- Animations performed on an element are asynchronous.
Consider this example where we would have a
<div>to animate:$('button').click(function () { $('div').animate({left:'+=200px'}, 2000); $('div').animate({top:'0px'}, 600); $('div').css('backgroundColor','red'); //
$('div').animate({left:'10px', top:'30px'}, 700);
});-
Each element has its own animation queue,
fx(default queue), which is an array of functions. - Those queues are FIFO (First In First Out).
Using the following animation queue function, you are in total control of your animations:
-
You can add a function to the queue using
.queue()(putting the function at the end of the stack) -
Calling
.dequeue()removes the top function from the stack and executes it
-
You can add a function to the queue using
You could place your background changing operation on the
fxstack like this:$('button').click(function () { $('div').animate({left:'+=200px'}, 2000); $('div').animate({top:'0px'}, 600); $('div').queue(function(){ //
$(this).css('backgroundColor','red');
$(this).dequeue(); //
});
$('div').animate({left:'10px', top:'30px'}, 700);
});-
You can get the animation queue of an element by calling
.queue()on the matched selection. It would return an array of functions. You could watch the state of the stack like this:
setInterval(function(){ $('span').html('Current Animation Queue Length for the div is ' + $('div').queue('fx').length); }, 100);