10 Tips for Writing Better jQuery Code

jQuery is totally cool. I’ve been using it for a year now and I find myself constantly learning new tricks and running into great improvements.
 The amount of plug-ins and resources out there is great, too, making this powerful javascript library either a must-use (for many developers) or a very-cool-thing-I-like for the others. However, many people want to know how to write better code. 

Here, my friend, are some tips.




1. $(document).ready () All The Way

Everything inside it will load as soon as the DOM is loaded and before the page contents are loaded. It lets you attach events to any alements in the page without directly interfering with the mark-up; all those annoying onload, onclick and onwhatever stuff isn’t needed anymore; just write it in here. An example with created-on-the-spot functions, which keeps everything very compact and quite understandable, could be

$(document).ready (function () {
$(".dummy").click (function () {
$(this).css ('color', '#000000');

2. Use $(window).load ()

Even though the vast majority of examples come with the wide-spread $(document).ready () pseudo event, you better avoid putting everything in it.

The latter is incredibly useful, but occurs during page render, while objects are still downloading. Superfluous functionality such as scrolling, drag and drop, etc, could be put inside the $(window).load () function, which executes after all of the objects have downloaded and avoids stalling during page loading.

Syntax is the same as the well-known $(document).ready () event

$(window).load (function () {
// my scrolling methods

3. Load Only What You Really Need

Everyone is tempted to write all of the JS code for the website in one place and then copy it over. jQuery takes time to look elements up, even if they don’t exist, and this slow things down.

There are two ways I would suggest you can get around this awful situation. The simplest one would be to just tag the body with a name (the page name, for example) and run the code needed by the page only.

$(document).ready (function () {
if ('body').hasClass ('home') {
// home page code
else if ('body').hasClass ('blog') {
// blog code
}   // and so on

The other method, a bit trickier to me, is to build a library and call the code you need on every page.

// global JS library
var jslib =
init: function () {
// home page code
},   blog:
init: function () {
// blog code
}   // and so on
<!-- html page -->
<script type="text/javascript"><!--mce:0--></script>

4. 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 alows you to associate and store data to any element on the page and having a meaningful name to refer to.

5. Built-In Custom Selectors

Being familiar with CSS selectors is a huge help when dealing with jQuery, but being knowledgable about jQuery built-in selectors is a boost for real! Have a look at http://docs.jquery.com/Selectors to find out all of them.

For example, you could use

$("div:contains('hello')").css ('background-color', '#cc0000');

to paint red all the divs containing the word “hello”, or


to match all the password fields.

6. Flag With Classes

You can use flags to monitor what the user is doing, or even to check whether a particular thing has been done or not. The addClass method comes in handy this time, providing a easy way to add a new class to an element. You can later check the existence of the class (thus the flag) with the hasClass function.

A very common use of flags is whenever the application has two or more working modes; upon entering the second mode, the flag is set to a predetermined element and, when needed, the hasClass method is used to check the current working mode. That easy!

function editModeOn ()
// turns on edit mode and sets a flag
$('#flags').addClass ("editModeOn");
// do other cool things
}   function saveData ()
// to save data, first exit edit mode (if editing)
if ($('#flags').hasClass ('editModeOn')) {
exitEditMode ();
$('#flags').removeClass ('editModeOn');
}   save ();

7. Don’t Call the Same Selector Hundreds of Times

Yeah, don’t do it, really. Instead of

$('p.hello').css ('color', '#000000');
$('p.hello').text ('hello');
$('p.hello').addClass ('paragraph');
$('p.hello').fadeTo (1000, 1);

go with

var $p = $('p.hello');
$p.css ('color', '#000000');
$p.text ('hello');
$p.addClass ('paragraph');
$p.fadeTo (1000, 1);

This will cache the variable and keep it ready for quick reuse.

8. Chain (Almost) Everything

Chaining is extremely useful. The above code could be re-written as

$('p.hello').css ('color', '#000000').text ('hello').addClass ('paragraph').fadeTo (1000, 1);

Beware chaining could slow things down a bit though.

9. toggleClass Utility

You can toggle an element’s class on and off to switch its behaviour without much effort. If your .hidden class won’t display any item, you can show ‘em with

$('p.hidden').toggleClass ();

because the paragraph will now look as if it had the following mark-up

text here

Another point of the toggleClass is that, with the next release of jQuery 1.3.3 the .toggleClass() method will have a couple more modes of operation: [it] will be able to toggle multiple class names and will also be able to toggle all the classes on or off. Here are the different ways you’ll be able to use .toggleClass().- Brandon Aaron

// With the following element
//   // Toggle all classes
$('div').toggleClass(); //
$('div').toggleClass(); //
<div class="a b c">
$('div').toggleClass( false ); //
$('div').toggleClass( true ); //
<div class="a b c">   // Toggle multiple classes
$('div').toggleClass( "a b" ); //
<div class="c">
$('div').toggleClass( "a c" ); //
<div class="a">
$('div').toggleClass( "a b c", false ); //
$('div').toggleClass( "a b c", true ); //</div>

10. Store jQuery Results

When dealing with functions, you might want to have some results available elsewhere; a possible solution is to store results into objects with a global scope, storing them for later usage.

// use the window object for instance
window.$results = {
one : 0,
two : 0
};   // this is the function, perhaps ran more than once
function getResults (first, second)
$results.one = first;
$results.two = second;
}   // run function
getResults ($('li.blue'), $('a.red));
$results.one.hasClass ('blue'); // true
$results.two.hasClass ('blue'); // false   // run again
getResults ($('li.red'), $('a.blue));
$results.one.hasClass ('blue'); // false
$results.two.hasClass ('blue'); // true



Leave a comment