Technology usage has a tendency to ebb and flow. Popular technology considered ubiquitous at one point in time may fall from lofty heights, to be replaced by younger, fitter rivals. Time will tell how jQuery fares in the years ahead, but it’s currently enjoying massive success, having emerged as the clear winner in the battle for favour among JavaScript libraries.
Following are few very useful jQuery Tips and Tricks for all jQuery developers.
1. Optimize performance of complex selectors
Query a subset of the DOM when using complex selectors drastically improves performance:
var subset = $(“”);
$(“input[value^=”]”, subset);
2. Set Context and improve the performance
On the core jQuery function, specify the context parameter when. Specifying the context parameter allows jQuery to start from a deeper branch in the DOM, rather than from the DOM root. Given a large enough DOM, specifying the context parameter should translate to performance gains.
$(“input:radio”, document.forms[0]);
3. Live Event Handlers
Set an event handler for any element that matches a selector, even if it gets added to the DOM after the initial page load:
$(‘button.someClass’).live(‘click’, someFunction);
This allows you to load content via ajax, or add them via javascript and have the event handlers get set up properly for those elements automatically.
Likewise, to stop the live event handling:
$(‘button.someClass’).die(‘click’, someFunction);
These live event handlers have a few limitations compared to regular events, but they work great for the majority of cases. Live event will work starting from jQuery 1.3
4. Checking the Index
jQuery has .index but it is a pain to use as you need the list of elements and pass in the element you want the index of
var index = e.g $(‘#ul>li’).index( liDomObject );
The following is easier:
if you want to know the index of an element within a set, e.g. list items within a unordered list:
$(“ul > li”).click(function ()
{
var index = $(this).prevAll().length;
});
5. Use jQuery data method
jQuery’s data() method is useful and not well known. It allows you to bind data to DOM elements without modifying the DOM.