Let's face it, if you are a .NET web developer then jQuery is quickly becoming a required skill. With that said, I am making it a point this year to learn as much as I can about jQuery. If this was some sort of support meeting then this would be the part where I would stand up and say "Hi, I am an MVC addict, and my New Year's resolution is to become a jQuery ninja." LOL
Anyways, over the last couple of days I have spent time digging through the various jQuery tips and tricks that are scattered on the web. Here are a few tips and tricks that I found particularly interesting that I wanted to share with you:
No conflict-mode
(No, this is not a tip about dating or parenting)
To avoid conflict when you are using multiple libraries in a website, you can use this jQuery Method, and assign a different variable name instead of the dollar sign. Using jQuery with other libraries
var $j = jQuery.noConflict();
$j('#myDiv').hide();
Using empty() vs html("")
If you write .html("") when you want to empty a div or a list, then there's no guarantee that the events assigned to the child DOM elements are unbound. The jQuery manual states:
"To avoid memory leaks, jQuery removes other constructs such as data and event handlers from the child elements before removing the elements themselves."
So, always use .empty() instead of .html("")
Custom selectors can help clean up your code
Do you have a selector that you use over and over again? Then perhaps you should create a custom selector instead...
$.extend($.expr[':'], {
over100pixels: function(a) {
return $(a).height() > 100;
}
});
$('.box:over100pixels').click(function() {
alert('The element you clicked is over 100 pixels high');
});
Learn What The "data" Method Is And Use It
I see this all the time; people don’t think about this and always write stuff like
$('.myselector').attr ('alt', 'orange');
to store (and associate) some miscellaneous data in DOM. This is technically incorrect, as well as rather confusing for someone alien to the original programmer’s thoughts.
jQuery actually provides a method to store data in DOM, which is data. The above example would then become:
$('.myselector').data ('myfavcolor', 'orange');
// then retrieved as simply as
$('myselector').data ('myfavcolor');
This method allows you to associate and store data to any element on the page and having a meaningful name to refer to.
Give your selectors a context
By default, when you use a selector such as $('.myDiv') the whole of the DOM will be traversed, which depending on the page could be expensive.
The jQuery function takes a second parameter when performing a selection.
jQuery( expression, context )
By providing a context to the selector, you give it an element to start searching within so that it doesn't have to traverse the whole of the DOM.
To demonstrate this, let's take the first block of code from the tip above. It creates an unordered list with 1000 items, each with an individual class. It then loops through and selects each item once. You'll remember that when selecting by class it took just over 5 seconds to select all 1000 of them using this selector.
var selectedItem = $('#listItem' + i);
I then added a context so that it was only running the selector inside the unordered list, like this...
var selectedItem = $('#listItem' + i, $('.myList'));
It still took 3818 milliseconds because it's still horribly inefficient, but that's more than a 25% speed increase by making a small modification to a selector.
You can use shorthand for the ready event
A small tip this one but you can save a few characters by using shorthand for the $(document).ready function. Instead of this...
$(document).ready(function (){
// your code
});
You can do this...
$(function (){
// your code
});
Bookmark JsFiddle
Need a place to quickly test your JavaScript code? If so, then head over to JSFiddle. JsFiddle presents an interface for editing HTML, CSS and JavaScript. In addition, jsFiddle allows you to choose all of the most popular JavaScript frameworks such as Mootools, jQuery, Dojo, Prototype, YUI, Glow and Vanilla. JsFiddle’s, greatest feature is the ability to store and share code via a unique URL. Very handy for troubleshooting some JavaScript with a friend at a remote location.
Related Links:
Improve your jQuery - 25 excellent tips
10 Tips for Writing Better jQuery Code
20 Top jQuery tips & tricks for jQuery programmers
10 tricks that will make your jQuery enabled site go faster