jQuery is easy to learn, but if you want to write prettier, cleaner and more efficient code, you always need a few tricks. This article summarizes 14 tips for improving your jQuery code for you.
1. Test and level up your jQuery selectors
This jQuery Selector Lab is really cool, it’s free to use online, and of course you can also download it to use offline locally. The test page contains complex combined HTML fields, and then you can try out various predefined jQuery selectors. If that’s not enough you can also define your own selectors.
2. Test whether a jQuery wrapper set contains certain elements
If you want to test whether a certain jQuery wrapper set contains some elements, you can first try verifying whether the first element exists:
if($(selector)[0]){...}
// or like this
if($(selector).length){...}
Let’s look at this example:
//Example. If your page has the following html code
<ul id="shopping_cart_items">
<li><input class="in_stock" name="item" type="radio" value="Item-X" />Item X</li>
<li><input class="unknown" name="item" type="radio" value="Item-Y" />Item Y</li>
<li><input class="in_stock" name="item" type="radio" value="Item-Z" />Item Z</li>
</ul>
<pre escaped="true" lang="javascript">...
//this if condition will return true, because we have two
// input fields matched by the selector, so the <statement> code will run
if($('#shopping_cart_items input.in_stock')[0]){<statement>}
3. Read the latest jQuery version from jquery.org
You can use this line of code to load the latest version of the jQuery source file.
<script src="http://code.jquery.com/jquery-latest.js"></script>
You can use this approach to call the most recent version of the jQuery framework. Of course, you can also use the following code to call the same latest jQuery version from ajax.useso.com:
<script src="http://ajax.useso.com/ajax/libs/jquery/1.3.2/jquery.min.js"
type="text/javascript"></script>
4. Storing data
Using the data method can save you from storing data in the DOM. Some front-end developers like to use HTML attributes to store data:
$('selector').attr('alt', 'data being stored');
//later you can read the data like this:
$('selector').attr('alt');
Using the “alt” attribute as a parameter name to store data is actually not semantically correct for HTML. We can use jQuery’s data method to store data for an element on the page:
$('selector').data('参数名', '要存储的数据');
//later get the data like this:
$('selector').data('参数');
This data method lets you name the data parameters yourself, making it more semantic and more flexible. You can store data information on any element on the page. If you want to learn more about the data() and removeData() methods, take a look at this official jQuery explanation. A classic use of this method is giving an input field a default value and then clearing it when it gets focused: HTML part:
<form id="testform">
<input type="text" class="clear" value="Always cleared" />
<input type="text" class="clear once" value="Cleared only once" />
<input type="text" value="Normal text" />
</form>
JavaScript part:
$(function() {
//grab the input fields with the clear class
//(note: "clear once" is two classes, clear and once)
$('#testform input.clear').each(function(){
//use the data method to store data
$(this).data( "txt", $.trim($(this).val()) );
}).focus(function(){
// when focused, check whether the value in the field equals the default value, and clear it if so
if ( $.trim($(this).val()) === $(this).data("txt") ) {
$(this).val("");
}
}).blur(function(){
// add a blur event to fields with the clear class to restore the default value
// but ignore it if the class is once
if ( $.trim($(this).val()) === "" && !$(this).hasClass("once") ) {
//Restore saved data
$(this).val( $(this).data("txt") );
}
});
});
5. Keep the jQuery manual close by
Most people find it hard to remember all the programming details. Even the best programmers can be careless about some corner of a language, so printing out the relevant manual or keeping it on your desktop for quick reference is absolutely something that can improve your programming efficiency. oscarotero jquery 1.3 (wallpaper version)

6. Log jQuery in the FireBug console
FireBug is one of my favorite browser extensions. It lets you quickly understand the current page’s HTML+CSS+JavaScript in a visual interface, and do live development right inside the tool. As a jQuery or JavaScript developer, FireFox also supports logging your JavaScript code. The simplest way to write to the FireBug console is as follows:
console.log("hello world")
fire-500X200
You can also write some parameters however you like:
console.log(2,4,6,8,"foo",bar)
You can also write a small extension to log jQuery objects to the console:
jQuery.fn.log = function (msg) {
console.log("%s: %o", msg, this);
return this;
};
With this extension, you can directly use the .log() method to log the current object to the console.
$('#some_div').find('li.source > input:checkbox')
.log("sources to uncheck")
.removeAttr("checked");
7. Use ID selectors whenever possible
After you start using jQuery, you’ll find that selecting DOM elements by their class attribute becomes quite easy. Even so, it’s still recommended to use class selectors as little as possible and instead use the faster ID selectors (in IE, using a class selector walks the entire DOM tree before returning the matching class wrapper set). ID selectors are faster because the DOM itself has a “natural” getElementById method, while class does not. So if you use class selectors, the browser will traverse the whole DOM, and if your page’s DOM structure is complex enough, these class selectors are more than enough to drag the page down and make it slower and slower. Let’s look at this simple piece of HTML code:
<div id="main">
<form method="post" action="/">
<h2>Selectors in jQuery</h2>
...
...
<input class="button" id="main_button" type="submit" value="Submit" />
</form>
</div>
//using a class to call the submit button is much slower than using the absolute ID selector
var main_button = $('#main .button');
var main_button = $('#main_button');
8. Make good use of jQuery chaining
jQuery chaining not only lets you write powerful operations in a concise way, but also improves development efficiency, because it can apply multiple commands to a wrapper set without having to recompute the wrapper set. So instead of writing:
<li>Description: <input type="text" name="description" value="" /></li>
$('#shopping_cart_items input.text').css('border', '3px dashed yellow');
$('#shopping_cart_items input.text').css('background-color', 'red');
$('#shopping_cart_items input.text').val("text updated");
Instead, you can use jQuery chaining to do it more simply:
var input_text = $('#shopping_cart_items input.text');
input_text.css('border', '3px dashed yellow');
input_text.css('background-color', 'red');
input_text.val("text updated");
//same with chaining:
var input_text = $('#shopping_cart_items input.text');
input_text
.css('border', '3px dashed yellow')
.css('background-color', 'red')
.val("text updated");
9. Bind jQuery functions to the $(window).load event
Most jQuery examples or tutorials tell us to bind our jQuery code to the $(document).ready event. Although the $(document).ready event is fine in most cases, it runs when the document is ready but images and other objects on the page are still downloading. So sometimes using the $(document).ready event doesn’t necessarily give us the result we expect — for example with some visual effects and animations, drag and drop, preloading hidden images, and so on… By using the $(window).load event you can safely start running the code you expect only after the entire document is ready.
$(window).load(function(){
// put the code you want to run after the page is fully ready here
});
10. Use jQuery chaining to scope selectors, making your code cleaner and more elegant
Because JavaScript supports chaining and line breaks, you can write your code like this. This example first removes a class from an element and then adds another class to the same element:
$('#shopping_cart_items input.in_stock')
.removeClass('in_stock')
.addClass('3-5_days');
If you want to make it even simpler and more practical, you can create a chainable jQuery function:
$.fn.makeNotInStock = function() {
return $(this).removeClass('in_stock').addClass('3-5_days');
}
$('#shopping_cart_items input.in_stock').makeNotInStock().log();
11. Use callback functions to synchronize effects
If you want to make sure an event or animation effect is called after another event runs, then you need to use a callback function. You can bind a callback function after these animation effects: slideDown( speed, [callback] ) ie. $(’#sliding’).slideDown(’slow’, function(){… Click here to preview this example.
<style>
div.button { background:#cfd; margin:3px; width:50px;
text-align:center; float:left; cursor:pointer;
border:2px outset black; font-weight:bolder; }
#sliding { display:none; }
</style>
$(document).ready(function(){
// use jQuery's click event to change the visual effect and start the sliding effect
$("div.button").click(function () {
//div.button now looks like it is pressed
$(this).css({ borderStyle:"inset", cursor:"wait" });
//#sliding will now fade out and start the fade-in effect once it completes
//slideup once it completes
$('#sliding').slideDown('slow', function(){
$('#sliding').slideUp('slow', function(){
//once the fade-in effect completes, the button's CSS properties will be changed
$('div.button').css({ borderStyle:"outset", cursor:"auto" });
});
});
});
});
12. Learn to use custom selectors
jQuery allows us to define custom selectors on top of CSS selectors to make our code cleaner:
$.expr[':'].mycustomselector= function(element, index, meta, stack){
// element - DOM element
// index - the index value of the current iteration in the stack
// meta - data element about your selector
// stack - the stack used to iterate over all elements
// return true if the current element is included
// return false if the current element is not included
};
// usage of the custom selector:
$('.someClasses:test').doSomething();
Below let’s look at a small example where we use a custom selector to target the set of elements that have a “rel” attribute:
$.expr[':'].withRel = function(element){
var $this = $(element);
//only return elements whose rel attribute is not empty
return ($this.attr('rel') != '');
};
$(document).ready(function(){
//using a custom selector is very simple, it works like any other selector and returns a wrapper set of elements
//you can use formatted methods on it, for example changing its css style like this
$('a:withRel').css('background-color', 'green');
});
<ul>
<li>
<a href="#">without rel</a>
</li>
<li>
<a rel="somerel" href="#">with rel</a>
</li>
<li>
<a rel="" href="#">without rel</a>
</li>
<li>
<a rel="nofollow" href="#">a link with rel</a>
</li>
</ul>
13. Preload images
Usually using JavaScript to preload images is a pretty good approach:
//define the function that preloads a list of images (takes parameters)
jQuery.preloadImages = function(){
//iterate over the images
for(var i = 0; i<arguments.length; i++){
jQuery("<img>").attr("src", arguments[i]);
}
}
// you can use the preload function like this
$.preloadImages("images/logo.png", "images/logo-face.png", "images/mission.png");
14. Test your code thoroughly
jQuery has a unit testing framework called QUnit. Writing tests is easy, and it lets you modify your code with confidence, making sure it still works as expected. Here is how it works:
//split the tests into several modules.
module("Module B");
test("some other test", function() {
//specify how many assertions need to be added to the test.
expect(2);
equals( true, false, "failing test" );
equals( true, true, "passing test" );
});

