
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.
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.
I keep seeing people doing this in their plugins to store data
$('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.
$('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.
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)
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:
$("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.
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.
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.
//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’);
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
ShareRelated posts:
Related posts brought to you by Yet Another Related Posts Plugin.
RSS feed for comments on this post. TrackBack URL
September 22nd, 2009 at 4:15 pm
Great Tutorial. A similar tutorial that list about 20 useful jQuery Tips and Tricks – 20 jQuery Tips & Tricks
September 23rd, 2009 at 5:42 pm
Nice Tutorial.
In point (6:), your can use
$(‘div.hi’).css(‘color’, ‘#ffffff’).text(‘hello world’).addClass(‘amazingclass’);
with same result
September 24th, 2009 at 12:28 am
Completely unaware of live(), thanks!
Nice layout, btw.
September 24th, 2009 at 12:42 am
Thanks for sharing the article jQuery Guy – anything that helps other developers on here is always welcome.
September 24th, 2009 at 12:44 am
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 :)
September 24th, 2009 at 12:44 am
It's really useful (thanks btw)
September 24th, 2009 at 1:09 am
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)
September 24th, 2009 at 1:29 am
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.
September 24th, 2009 at 1:56 am
NICE?
September 24th, 2009 at 2:44 am
3: Use jQuery’s built-in custom selectors
jQuery in fact uses Sizzle as its default selection engine.
September 24th, 2009 at 3:12 am
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!
September 24th, 2009 at 3:23 am
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.
September 24th, 2009 at 3:52 am
[...] 7 Really Useful Tips For Better jQuery Code [...]
September 24th, 2009 at 9:30 am
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:
September 24th, 2009 at 9:32 am
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...
September 24th, 2009 at 6:35 pm
7 Really Useful Tips For Better jQuery Code…
I thought I’d share some tips that helped me to things a little better….
September 24th, 2009 at 11:36 pm
Thanks for the great tips, still learning jQuery.
September 27th, 2009 at 8:11 am
[...] 20 jQuery Tips and trics, 8 awesome jQuery tips ir 7 tips for better jQuery code – išrenku pa?ius ?domiausius ir naudingiausius [...]
October 7th, 2009 at 6:37 am
[...] 7 Really Useful Tips For Better jQuery Code [...]
December 13th, 2009 at 3:16 pm
[...] This post was Twitted by marcocz [...]
March 13th, 2010 at 8:06 am
Correction in example 3:
:eq(index)
Example: Btw..this is very very useful. To get the fifth div on a page use div:eq(5)
This would actually get the sixth div because the :eq is 0 based like arrays.