Some jQuery Shortcuts

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!