content top
Google Buzz

7 Really Useful Tips For Better jQuery Code

 

I’ve been using jQuery in my web apps for over three years now and a lot of the time – I use it in projects for my clients too. It’s an incredibly versatile way of using JavaScript and today I thought I’d share some tips that helped me do things a little better.

 

1: Use $(document).ready() or define your scripts before the closing </body> tag.

 

Although you might be used to defining your JavaScript functions without $(document).ready, I would recommend using it – everything inside it loads up as soon as the DOM does and even before the rest of your page’s contents have. It’ll also allow you to attach events to any of the elements on your page and it won’t interfere with their mark-up.

 

An example: I’ve come across lots of cases where you might want jQuery to hide some of the content in your page. If you’re running your function before the document is ready, you increase your chances of it not being executed at all if the server’s taking a while to load up the whole page. So..play it safe and use this method instead.

 

Experienced jQuery users can also define their scripts before the last body tag to make sure they’re executed as soon as they are loaded by the DOM.

 

2: Client side storage is getting more and more popular – do you use the data method instead of storing your data in the DOM?

 

I keep seeing people doing this in their plugins to store data

 

 

jQuery:
$('selector').attr('alt', ‘I am a string of data’);
// and then they access this data back through
$('selector').attr('alt');
 

So…why’s this such a bad thing? Well..it’s because ‘alt’ wasn’t created for this purpose and HTML isn’t supposed to be used for storing your data.  Instead… why not go for the data() method in jQuery. It was made to offer a way to store associated data with an element on the page.

 

Here’s an example of what I’m talking about.

 

 

jQuery:

$('selector').data('albumName1', ‘The Best of Phil Collins’);

// then you can access this data back through

$('selector').data('albumName1'); 

 

The overall effect of this is that you can store your data with meaningful names *and* you’re able to store as much information you want on any element on the page.  It’s an awesome little tool and one which you might just end up relying on some day.

 

 

3: Use jQuery’s built-in custom selectors

 

I won’t go into the reasons why using something like Sizzle.js is a good idea, but jQuery has lots of selectors that are beyond your run of the mill CSS selectors, so use them. Some that I find handy are:

 

:input  

Example: This’ll get you all the “input” elements on your page whether they’re text areas, text boxes, select lists or anything else.

 

[attribute=value]  

Example: If I want to find an input element with the name “eMail” I would use input[name='eMail']

 

:eq(index) 

Example: Btw..this is very very useful. To get the fifth div on a page use div:eq(5)

 

4: If you manipulate the DOM a lot use live().

 

When frequently adding elements to your page, attaching events or even running functions try to use the live() method. That way, you can easily do things like:

 

 

 

jQuery:
  $("div.fork").live("click", function(){
      $(this).after("<p>Another paragraph!</p>");
    });
 

This way, anytime you add a new div to your page with the class “fork”, it’ll attach that click event to it.

 

 

5: Use the jQuery Form plugin to submit files using Ajax

 

Try out this jQuery form plugin – it allows you to easily submit files to your server  via Ajax. The plugin uses a neat trick to do with an iframe to submit the data, but it’s really easy to use. Simply add an input type file and  use $(form).ajaxSubmit();

Thats it and you should be good to go.

 

6: Please..don’t call the same selector again and again

 

There’s no need to have jQuery find the element you’re interested in more than once so why don’t we do it more efficiently.

 

jQuery:

//rather than this

$(‘div.hi’).css(‘color’, ‘#ffffff’);

$(‘div.hi’).text(‘hello world’);

$('div.hi’).addClass(‘amazingclass’);

//lets do this

var $q = $(‘div.hi’);

$q.css(‘color’, ‘#ffffff’);

$q.text(‘hello world’);

$q.addClass(‘amazingclass’);

 

7: How to effectively use “classes” as a sort of flag

 

So, you might not be trying to store data, but do want to set a flag on a particular type of element that uses a class – for example, if you wanted to lock down a form after a user has switched from the “edit” mode on your page, jQuery provides you with the addClass method which can later be checked using the very useful hasClass method

Bookmark and Share
Share

Related posts:

  1. jQuery Colour Selector plug-in with support for graceful degradation Hey guys. Here’s another entry on jQuery that someone...
  2. Offline Cross-Browser Client-Side Storage for the Web using JavaScript and a little Flash   Hi guys. Today I’m going to show you how...
  3. How To Add Form Validation using jQuery in 2 Easy Steps     Hi everybody. Sometimes you may find yourself...
  4. How to enlarge images with jQuery Guest writer,  Jeffrey Jordan Way. I’ve created many tutorials...
  5. 10 Incredibly Professional Tips for Web Designers and Web Developers   Professional development is one of the key elements to...

Related posts brought to you by Yet Another Related Posts Plugin.

20 Comments »

  1. avatar comment-top

    Great Tutorial. A similar tutorial that list about 20 useful jQuery Tips and Tricks – 20 jQuery Tips & Tricks

    comment-bottom
  2. avatar comment-top

    Nice Tutorial.

    In point (6:), your can use

    $(‘div.hi’).css(‘color’, ‘#ffffff’).text(‘hello world’).addClass(‘amazingclass’);

    with same result

    comment-bottom
  3. avatar comment-top

    Completely unaware of live(), thanks!
    Nice layout, btw.

    comment-bottom
  4. avatar comment-top

    Thanks for sharing the article jQuery Guy – anything that helps other developers on here is always welcome.

    comment-bottom
  5. avatar comment-top

    Thanks for that. I'd considered adding chaining to the list but it's got it's advantages and disadvantages. On one hand it really does make for better looking code but it also has a small hit on performance. All in all a good addition :)

    comment-bottom
  6. avatar comment-top

    It's really useful (thanks btw)

    comment-bottom
  7. avatar comment-top

    Chaining doesn't hurt performance, it's does the exact same thing as the 3 separate calls. I think you make a valid point about storing the selector, but there are better examples of when to use it (such as modifying one element inside of an .each() on a group of different elements)

    comment-bottom
  8. avatar comment-top

    I agree with you on the usage case, Gabriel. Thanks for contributing!. I also forgot to point out to readers that another advantage of chaining is that you're using a little less code so overall if you apply chaining to your codebase effectively it has the potential to make your apps more lightweight.

    With regards to performance, I should have explained that chaining is only a risk is if it's used incorrectly. There are instances I've seen where excessive chaining can lead to memory leaks (could have been app specific) but as with everything if used sensibly it's an excellent asset to any javascript coder.

    comment-bottom
  9. avatar comment-top

    NICE?

    comment-bottom
  10. avatar
    Michael Del Tito Says:
    September 24th, 2009 at 2:44 am
    comment-top

    3: Use jQuery’s built-in custom selectors

    jQuery in fact uses Sizzle as its default selection engine.

    comment-bottom
  11. avatar comment-top

    Had no idea the data() method existed. This changes everything!
    Literally, I've been up to my eyeballs in jQuery development recently and find myself constantly needing to store data in rel tags. This will truly be a life-saver. Thanks!

    comment-bottom
  12. avatar comment-top

    No problem at all, Jason. The data() method has come in handy for me lots of times in the past and I'm glad to see this post is helping other coders out.

    comment-bottom
  13. avatar comment-top

    [...] 7 Really Useful Tips For Better jQuery Code [...]

    comment-bottom
  14. avatar comment-top

    Good ones 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:

    comment-bottom
  15. avatar comment-top

    Here's the link:

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

    http://technosiastic.wordpress.com/2009/09/24/col...

    comment-bottom
  16. avatar comment-top

    7 Really Useful Tips For Better jQuery Code…

    I thought I’d share some tips that helped me to things a little better….

    comment-bottom
  17. avatar comment-top

    Thanks for the great tips, still learning jQuery.

    comment-bottom
  18. avatar comment-top

    [...] 20 jQuery Tips and trics, 8 awesome jQuery tips ir 7 tips for better jQuery code – išrenku pa?ius ?domiausius ir naudingiausius [...]

    comment-bottom
  19. avatar comment-top

    [...] 7 Really Useful Tips For Better jQuery Code [...]

    comment-bottom
  20. avatar comment-top

    [...] This post was Twitted by marcocz [...]

    comment-bottom

RSS feed for comments on this post. TrackBack URL

Leave a comment