Having used jQuery on a number of projects I’ve picked up a few handy shortcuts that are definitely worth sharing. There are no secrets here, just basic jQuery techniques discovered with the aid of the jQuery documentation. If you have any which you think are worth mentioning then please feel free to leave a comment.
Checking if the DOM is ready
Running code when the DOM is loaded and ready for manipulation is a popular requirement. The ideal solution is to place all initiating code at the bottom of your document (as per Yahoo’s "Best Practices for Speeding Up Your Web Site") but sometimes this is not possible. The next best alternative is to use a solid ‘DOM ready’ function such as the one jQuery offers. You normally access it like this:
$(document).ready(function(){...}); |
There’s a quicker way of accessing the same functionality:
$(function(){...}); |
Creating elements
There are a few different ways of creating elements, this is my favorite:
$('<div/>').appendTo('body'); |
Alternatively you could take this route:
$('body').append('<div/>'); |
Notice that you don’t have to write out the entire element. Even though DIV elements cannot have self-closing tags it’s still fine to specify it like above – JQuery will know what you mean.
Adding or changing attributes in bulk
Not so good:
$('a').attr('id','mydiv'); $('a').attr('class','important'); $('a').attr('href','http://www.google.com'); |
Better:
// i.e. Chaining $('a') .attr('id','mydiv') .attr('class','important') .attr('href','http://www.google.com'); |
Best:
$('a').attr({ id: 'mydiv', class: 'important', href: 'http://www.google.com' }); |
Have full control over your animations
jQuery’s stock animation functions such as fadeOut()
and slideDown()
can be useful but may sometimes do more than you intended (like setting the element to display:none;
instead of JUST reducing the opacity). So if you want to have full control over your animations then use animate()
.
$('#elem').animate({ // Reduce opacity by 0.2: opacity: '-=.2' }); |
Three ways to test wheter an element exists
// 1: if ($('#elem').size()) { alert('It exists!'); } // 2: if ($('#elem').length) { alert('It exists!'); } // 3: if ($('#elem').get(0)) { alert('It exists!'); } |
Chain Everything!
jQuery gives you the power of chainability, this means you can perform multiple actions on a single element or set of elements without having to ‘re-select’:
$('<div/>') .css({ cursor: pointer, height: '200px', width: '200px' }) .attr({ id: 'mydiv', class: 'box' }) .append('<a href="#">link</a>') .appendTo('body'); |
Thanks for reading! Please share your thoughts with me on Twitter. Have a great day!
This is a very good one, taking the fact that this function is the most-used, your shortcut is very useful..
One other thing I’d like to add :
Using
directly instead of clearing and re-appending, especially for recurring Ajax-updated messages ..
Of course this is similar to old-school element.innerHTML approach.
🙂
Good shortcuts.
animate does give you fantastic control over things, and chaining is essential! Cheers.
Nice tip Ali! 🙂 … Using the
html()
is pretty much the same as:Thanks Shane, yeh,
Animate
is great, I never bother using the built infadeIn
/fadeOut
/slideDown
etc. anymore, I like having more control.Strictly speaking, self-closing elements don’t always work, primarily because jQuery uses the browser’s built in html parsing to save itself the work. So some browsers, ok basically just IE, will screw up certain elements if you use an empty or self-closing tag. I ran into that subtle bug a little while ago while debugging a bizarre error in IE (is there any other?).
Excellent article. Been looking for some info on reducing the size of my code and “Adding or changing attributes in bulk” works a treat.