10 Tips for Writing Better jQuery Code

By   |  Stashed in Webdesign

jquery-tips

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 =
{
home:
{
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

$('input:password')

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>
$('div').toggleClass(); //
<div class="a b c">
$('div').toggleClass( false ); //
<div>
$('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>
$('div').toggleClass( "a b c", true ); //</div>
</div>
</div>
</div>
</div>
</div>
</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

About the Author

Keen on geeky stuff, I tried everything from rocketry to weird game development adventures more than once. I love orange-colored things. I'd be a web developer with a passion for design but I find myself writing for some websites every now and then.

More posts by

Website

  • Robin

    #7 and #8 should be combined, although that would make it 9 tips :P

  • http://www.blog.exxcorpio.com Luis Lopez

    Thanks for this post I’m really bad at jquery and this tips look awesome, I try them, because is something i have to get better at.
    Thanks
    .-= Luis Lopez´s last blog ..Video Of The Week #08 – Red Rabbit By Egtmon Mayer =-.

  • john Hoysa

    Great article!

    With Tip 7 how would one work converting the following code?

    $(“#myID > ul:last”).addClass(“newClass_A”);

    $(“#myID > ul:first”).removeClass(“newClass_1″);

    $(“#myID > ul:not(:last)”).addClass(“newSomething”);

    $(“#myID > ul:last”).addClass(“newClass”);

    of course I made up the class names for this example.

    Thanx for the help!

    John

  • http://aaronkuzemchak.com/ Aaron

    #1 and #2 aren’t even needed if you follow the recommendation to move scripts to right before the closing body tag. Not only will it appear that things load faster, but the scripts will execute as soon as they’re loaded by the DOM, eliminating the need for either document.ready or window.load :)
    .-= Aaron´s last blog ..My New Favorite Way to Train Clients =-.

  • http://twitter.com/hardbap Mike Breen (hardbap)

    For #1 – what about putting your scripts before the closing body tag? That way you don’t have to check if the DOM is loaded.

  • Roger Sarrasin

    Great tips!!!

    Would you be able to elaborate more about #3?
    Newbie, I must be missing something simple.
    I can’t seem to find out how mce:0 works or how to call / run the code needed by the page only.

    Thanks!

  • http://www.ithoughts.de http://twitter.com/ithoughts_de

    Does chaining really slow things down? I thought it would speed things up?
    .-= http://twitter.com/ithoughts_de´s last blog ..Which JavaScript-Framework? =-.

  • http://pietschsoft.com Chris Pietschmann

    Instead of using “$(document).ready(function(){});”, why not just use “$(function(){});”. It’s shorter and does the same thing.
    .-= Chris Pietschmann´s last blog ..Bing Maps Silverlight: Plot/Edit Pushpin data via a ChildWindow =-.

  • http://www.jeroenvanwarmerdam.nl jerone

    1 should be:
    1. $(function(){/**code**/}) All The Way

    http://docs.jquery.com/Core/jQuery#callback

  • http://www.thespider.com thespider

    quick morning coffee read. thanks!
    .-= thespider´s last blog ..Site Launch – Redesign of TheSpider.com =-.

  • http://vipullimbachiya.com Vipul Limbachiya

    Good tips..

    Thanks for sharing

    Vipul Limbachiya

  • danny

    Nice. But, sorry, I have to say that “Tip” #8 was terrible, and you would have been better off leaving it out and sticking with 9 Tips. Writing “code like this most of the time, but sometimes it may make your code suck” does not a tip make. :)

  • http://EricMiller.name Eric Miller

    The perfect list for someone still new to jQuery. Thanks.

  • http://cpcdisseny.net/webmundi Javier

    Great post Giulio! There are some tips that I didn’t know.
    .-= Javier´s last blog ..Changes in delicious.com =-.

  • http://www.subprint.com Joe McCann

    For #10, instead of creating a global variable,why not use jQuery’s data method?


    $.data(window, "cache", { foo: false, bar: true });

    To access the values do this:

    $.data(window, "cache").foo; // returns false
    $.data(window, "cache").bar; // returns true

    To change values do this:

    $.data(window, "cache").foo = true;
    $.data(window, "cache").bar = false;

  • http://www.juliobitencourt.com Julio Cesar Bitencourt

    Dude, #4 is really awesome. Can I translate this post to brazilian portuguese? Thanks a lot.
    .-= Julio Cesar Bitencourt´s last blog ..Estilizando links com seletores CSS =-.

  • danny

    @john Hoysa

    Tip 7 hasn’t been described too well, as it doesn’t say why this is a tip, but it’s the most important jQuery tip there is. Simply put, always store a jQuery selector if you are going to use it more than once. Everytime you write something like:

    $(”#myID”);

    you are traversing the DOM, looking for that element. But if you store a reference to that element, like:

    var $myId = $(”#myID”);

    you can now access $myId whenever you want, without searching the DOM again. So you might change your code to something like this (this isn’t a great example):

    var $myId = $(“#myID”);
    var $ulLast = $(“#myID”).children(“ul:last”);

    $ulLast.addClass(”newClass_A”).addClass(”newClass”);
    $myId.children(“ul:first”).removeClass(”newClass_1″);
    $myId.children(“ul:not(:last)”).addClass(”newSomething”);

    (you only accessed ul:first and ul:not(:last) once each, so I didn’t store them)

  • http://www.twitter.com/joshuantaylor JoshuaNTaylor

    Still learning, but this will help. I look forward to using the toggleClass utility. I can think of a lot of great options for that.
    .-= JoshuaNTaylor´s last blog ..joshuantaylor: This is a really great animated video by @cribble http://twurl.nl/k53ct0 =-.

  • Darron

    Could you please elaborate on the second part of #3.

  • http://buup.mephir.com Giulio

    @Aaron: true, but I’d check anyway — for no reason probably — using wither document.ready or window.load

    Yeah, it looks like chaining actually slows things down in the long run — i.e. when you deal with lots of stuff

    @Joe McCann: That’s another possibility. Thanks for having pointed that out!

    @Julio Cesar Bitencourt: If Andrew is ok with that, I don’t see any reason you could not

    @danny: Yep that’s it — I should’ve written some more about that point, sorry

    And for #3, the last bit of code basically loads the desired part of code depending on the page.
    Though, the script in the HTML page is

    jslib.home.init (); // replace ‘home’ with ‘blog’ or whatever you need

    and I don’t know why mce:0 is displayed instead… :/

    Thanks for the feedback guys!

  • http://www.myinkblog.com Andrew Houle

    @Julio – As long as you give credit to the original article and link back then you are welcome to translate it to your blog. Thanks!

  • Will

    #3 is a good one. I myself have a method that checks to see if a div exists:
    function checkForDiv(id) {
    var div = document.getElementById(id);
    if (div) { return true } else { return false }
    }

    Then you can call it like this:

    $(document).ready(function() {
    if (checkForDiv(“home”)) { homePageMethod(); }
    }

    Great post!

  • http://diffract.me Pedro Assuncao

    Cool article. Thanks for sharing the tips.
    .-= Pedro Assuncao´s last blog ..Road trip to citybox at Amsterdam Noord =-.

  • http://amrelgarhy.com Amr ElGarhy

    Very nice post, and useful tips, thanks

  • Ricardo

    number 10 is a bit weird. You’d usually do

    var elements = $(‘a.blue, a.red’);

    $( elements[0] ).addClass(‘one’);
    $( elements[1] ).addClass(‘two’);

    Or simply save each object in a variable, or in the jQuery object itself – jQuery.$results – to avoid polluting the global namespace.

  • muppet

    to complain about chaining is to not understand jQuery.

  • Jeremy

    Data method just blew my mind.
    I knew I was doing it wrong storing values in the rel, title and other element attributes.

  • http://www.rodrigofante.com Rodrigo Fante

    Nice article, I’ve been working with jQuery for a few months now and didn’t know the data method.. really cool indeed…

    Thanks

  • danny

    @Will

    Hey mate, cool but that seems a little over the top. Firstly, I don’t really see the point of the function. Doing this would be the same thing:

    $(document).ready(function() {
    if (document.getElementById(”home”)) { homePageMethod(); }
    }

    Secondly, you could certainly optimise your function:

    function checkForDiv(id){
    return (document.getElementById(id))? true : false;
    }

    Lastly and most importantly, you’re mixing native DOM functions and jQuery. One off the points of using jQuery is that it improves and extends DOM selectors. So you should be doing:

    $(document).ready(function() {
    if ($(”#home”).length>0) { homePageMethod(); }
    }

    Or using your function principle, you could check for IDs and classes:

    function checkForDiv(id){
    return ($(id).length>0)? true : false;
    }

    Both of these would then work:

    console.log(checkForDiv(‘#home’));
    console.log(checkForDiv(‘.home’));

  • http://www.snilesh.com/ Neel

    Great tutorial as I started to learn jquery. now after trying this tutorial i learn alot.

  • http://www.kaplang.com Kaplang

    great article, thanks for all of the useful tips, this is something that I have been struggling with myself, so you have really helped me out :)

  • http://twitter.com/jjenzz Jenna

    @John Hoysa I’d convert it as follows:

    $context = $('#myID');
    $('> ul:last', $context).addClass('newClass_A').addClass('newClass');
    $('> ul:first', $context).removeClass('newClass_1');
    $('> ul:not(:last)', $context).addClass('newSomething');

    .-= Jenna´s last blog ..JJenZz: Just found BaseKit (CMS) and it looks awesome. Has drag and drop content widgets – http://basekit.com/ =-.

  • http://twitter.com/jjenzz Jenna

    oops, even better:

    
    $context = $('#myID');
    $('> ul:last', $context).addClass('newClass_A').addClass('newClass');
    $('> ul:first', $context).removeClass('newClass_1');
    $('> ul:not(:last)', $context).addClass('newSomething');	
    
    

    .-= Jenna´s last blog ..JJenZz: Just found BaseKit (CMS) and it looks awesome. Has drag and drop content widgets – http://basekit.com/ =-.

  • http://twitter.com/jjenzz Jenna

    Man I suck at this… where’s delete comment when you need it! haha.

    That should be $(‘> ul:last’, $context).addClass(‘newClass_A newClass’); instead, on the 2nd line.
    .-= Jenna´s last blog ..JJenZz: Just found BaseKit (CMS) and it looks awesome. Has drag and drop content widgets – http://basekit.com/ =-.

  • http://www.refinelighting.com ben

    thanks i am always finding it

  • http://phiredesign.net/blog AJ Troxell

    I don’t know much of jQuery, so these all look like great pointers to me. Time to learn something new!
    .-= AJ Troxell´s last blog ..8 Ways to Protect Your Home Office Computer =-.

  • http://buup.mephir.com Giulio

    @Ricardo: you’re right, yours looks like a cleaner version of what I meant. Thanks

    @Will and danny: From my point of view, perhaps a bit odd and not so right :/, I personally happen to prefer native JS to jQuery when possible, due to performance issues. Thus I like Will’s function better, though it’s not jQuery stuff and you could’ve optimized it as danny suggested

    @Jenna and John: sorry John I missed your comment, but Jenna got my point and answered your question in her message… oh wait was it the second one? or better, her last attempt ;)

  • http://365icon.com Jonathan

    Thanks for the tips! great article!

  • http://www.designstudio16.com saurabh shah

    wow nice cool tips … and agreed with the comments here … thnx for sharing …

  • http://www.discountwebdesign.co.uk imroz

    great post. thanks a lot

  • http://www.codelobster.com Stas

    I suggest everyone to use new free PHP IDE – Codelobster PHP Edition with special JQuery plug-in for working with JQuery library.

  • http://maddon.net/blog Madeline Ong

    The more I use JQuery, the more I love it. Thank you for this useful and informative post. :)
    .-= Madeline Ong´s last blog ..Book reviews =-.

  • http://technosiastic.wordpress.com Shahriar Hyder

    Nice collection of jQuery Tips and Tricks mate. I have also linked to yours from my blog post below where I am trying to collect the most useful and common jQuery code snippets for JavaScript over the web. Here is the title and the link to the jQuery link compilation endeavor:

    Ultimate collection of top jQuery tutorials, tips-tricks and techniques to improve performance

    http://technosiastic.wordpress.com/2009/09/24/collection-of-top-jquery-tutorials-tips-tricks-techniques-to-improve-performance/
    .-= Shahriar Hyder´s last blog ..Ultimate collection of top jQuery tutorials, tips-tricks and techniques to improve performance =-.

  • http://www.bigforge.com Eileen B

    For those app developers that don’t know Objective-C and Cocoa Touch and don’t want to outsource development, check out localbeacon at http://www.bigforge.com. Great for those who want to build just one app or developers interested in white label.

  • http://www.vertinix.com Vertinix

    Very good tips of jQuery. Great sharing.

  • http://www.noonoob.com/dara/ noonoob

    very nice , thank you very much .

  • http://www.webcreationuk.com/ Web Design

    This is just awesome mate, already bookmarked this post for further reading.

    Cheers!

  • http://www.mehmetkabatas.com Chris

    wow nice cool tips

  • http://motorai.ro Casti Moto

    I want to write my own JQ plugin now and this will definitely help me. Thanks for the great tips.

  • http://www.desiredtech.co.uk Scott

    Brilliant post, thank you for sharing. I’ve said it a few times today how much I enjoy working with JQuery. I’ve only been using it for a few weeks but it seems limitless.