Format Your jQuery Correctly

Posted under jQuery on December 12, 2009.

I've seen this done too many times, even by myself. It's about time people learn how to format their jQuery the correct way. In this article I'm going to give you a couple bad examples and a couple good examples of jQuery code.

Note: This article is meant to show you a couple possible ways to better format your jQuery code. You should take the examples and modify them to work with your own coding style, as long as that doesn't mean placing everything on one line. :P

Chaining

One of the great features of the jQuery library is that it allows you to chain a group of functions in a row. This feature is great, but it often times leads people to produce ugly unreadable code. Here's some "bad" jQuery code:

jQuery('#element').data('hidden',true).addClass('valid').text('Edit').slideOut(fast).val('Type Here');

Just attempting to read all that code on one line is nauseating. Let's place each function on a separate line and make it much more readable:

jQuery('#element')
	.data('hidden',true)
	.addClass('valid')
	.text('Edit')
	.slideOut(fast)
	.val('Type Here');

If you really wanted to, you could also organize the chain alphabetically. As Jeffrey Jose pointed out in the comments, just make sure changing the order of your functions does not affect how your chain works.

jQuery('#element')
	.addClass('valid')
	.data('hidden',true)
	.slideOut(fast)
	.text('Edit')
	.val('Type Here');

Objects

When placing an object in a function, like when using the css jQuery function, you should place each item of the object on a separate line just like with the functions. Here's another "bad" example:

jQuery('#element').css({color:'#000000',display:'block',height:75,opacity:0.5,width:100});

Again, this is just hard to read. Here is what you should do:

jQuery('#element').css({
	color:'#000000',
	display:'block',
	height:75,
	opacity:0.5,
	width:100
});

If you were to chain the above with a couple other functions, don't do it this way:

jQuery('#element')
	.css({
		color:'#000000',
		display:'block',
		height:75,
		opacity:0.5,
		width:100
	})
	.addClass('hidden')
	.data('hidden',true)
	.text('Edit');

If at all possible try to put the functions that don't contain big objects before the ones that do:

jQuery('#element')
	.addClass('hidden')
	.data('hidden',true)
	.text('Edit')
	.css({
		color:'#000000',
		display:'block',
		height:75,
		opacity:0.5,
		width:100
	});

That's it for today, I hope you learned how to format your jQuery better! :)

Comment

See what others have to say on this topic, or add your own two cents.