
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





Great Tutorial. A similar tutorial that list about 20 useful jQuery Tips and Tricks – 20 jQuery Tips & Tricks
Great Tutorial. A similar tutorial that list about 20 useful jQuery Tips and Tricks – 20 jQuery Tips & Tricks
Nice Tutorial.
In point (6:), your can use
$(‘div.hi’).css(‘color’, ‘#ffffff’).text(‘hello world’).addClass(‘amazingclass’);
with same result
Nice Tutorial.
In point (6:), your can use
$(‘div.hi’).css(‘color’, ‘#ffffff’).text(‘hello world’).addClass(‘amazingclass’);
with same result
Completely unaware of live(), thanks!
Nice layout, btw.
Completely unaware of live(), thanks!
Nice layout, btw.
Thanks for sharing the article jQuery Guy – anything that helps other developers on here is always welcome.
Thanks for sharing the article jQuery Guy – anything that helps other developers on here is always welcome.
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
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
It's really useful (thanks btw)
It's really useful (thanks btw)
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)
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)
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.
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.
NICE!
NICE!
3: Use jQuery’s built-in custom selectors
jQuery in fact uses Sizzle as its default selection engine.
3: Use jQuery’s built-in custom selectors
jQuery in fact uses Sizzle as its default selection engine.
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!
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!
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.
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.
[...] 7 Really Useful Tips For Better jQuery Code [...]
[...] 7 Really Useful Tips For Better jQuery Code [...]
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:
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:
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...
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...
7 Really Useful Tips For Better jQuery Code…
I thought I’d share some tips that helped me to things a little better….
7 Really Useful Tips For Better jQuery Code…
I thought I’d share some tips that helped me to things a little better….
Thanks for the great tips, still learning jQuery.
Thanks for the great tips, still learning jQuery.
[...] 20 jQuery Tips and trics, 8 awesome jQuery tips ir 7 tips for better jQuery code – išrenku pačius įdomiausius ir naudingiausius [...]
[...] 20 jQuery Tips and trics, 8 awesome jQuery tips ir 7 tips for better jQuery code – išrenku pačius įdomiausius ir naudingiausius [...]
[...] 7 Really Useful Tips For Better jQuery Code [...]
[...] 7 Really Useful Tips For Better jQuery Code [...]
7 Really Useful Tips For Better jQuery Code…
jQuery is an incredibly versatile way of using JavaScript and today I thought I'd share some tips that will help you do things better….
7 Really Useful Tips For Better jQuery Code…
jQuery is an incredibly versatile way of using JavaScript and today I thought I'd share some tips that will help you do things better….
Excellent article Addy. Since I started using jQuery back in '07, interface development has been fun. I am not always having to write a special set of functions to handle basic tasks. I like standardization.
BTW :eq() uses zero-based indexing, so :eq(5) would actually grab the 6th div.
Keep up the good work!
Excellent article Addy. Since I started using jQuery back in '07, interface development has been fun. I am not always having to write a special set of functions to handle basic tasks. I like standardization.
BTW :eq() uses zero-based indexing, so :eq(5) would actually grab the 6th div.
Keep up the good work!
Rather than doing this:
var $q = $(‘div.hi’);
$q.css(‘color’, ‘#ffffff’);
$q.text(‘hello world’);
$q.addClass(‘amazingclass’);
Do this:
$(‘div.hi’).css(‘color’, ‘#ffffff’).text(‘hello world’).addClass(‘amazingclass’);
Rather than doing this:
var $q = $(‘div.hi’);
$q.css(‘color’, ‘#ffffff’);
$q.text(‘hello world’);
$q.addClass(‘amazingclass’);
Do this:
$(‘div.hi’).css(‘color’, ‘#ffffff’).text(‘hello world’).addClass(‘amazingclass’);