jQuery Wins (flawless victory) May 27th, 2008

This is really no secret to anyone who has worked with me, but I must publicly admit my love for the lightweight javascript library. For those of you who haven’t used jQuery yet, let me explain why its better than sliced bread. It’s simple, intuitive, simple, widely supported, simple, lightweight, simple, cross-browser etc. Forget anything you know about “traditional” javascript libraries like Prototype and Scriptaculous. This is in a league all on its own. I could rant for pages and pages to the advantages, but I’d rather share a simple few examples with you. Afterall, a line of code is worth 1,000 words.

Let’s say we have a div with the id of “content_container” dynamically filled with content and you want to know the height. Well traditionally, even with the help of old libraries, this is at least a 3-4 confusing lines of code. But with jQuery its this:

var oldHeight = $(’#content_container’).height();

Thats it! You might have even guessed that right? Now lets go for something a little trickier. Say we have a page with several tabs and one of them is selected. When you click on different tab you’d like the old selected tab to go unselected and make the one you clicked on selected. There are typically 2 ways to do this. First would be to loop through all of the tabs and look for the one with the class of selected and change it. Another way would be to blindly reset them all to unselected and then select the clicked one. Both of these methods take up precious time and the second one even might cause visual jumps on the page. Lets see how jQuery will do it.

$(’.tab_container .tab_selected’).removeClass().addClass(’tab_unselected’);
$(’#tab_’+type).removeClass().addClass(’tab_selected’);

Yup. 2 lines. Because jQuery is chainable, many things can be accomplished on one or two lines. The selector makes really easy work of this. It simply says find the div with a class of “tab_selected” within the “tab_container” div and remove its class and add unselected. The second line just says the id of the tab we clicked on and remove its class and add “tab_selected”. You can see how this can start to get very powerful. Also note the use of div id’s and div classes.

$(’.class_name’) - select an object by its class
$(’#id_name’) - select and object by its id

With jQuery, you can forget about all the tedious lines of javascript and replace it with sensible, simple, elegant lines of beautiful code. I will be writing more simple tutorials on jQuery as time goes on discussing animation, DOM manipulation, and Ajax. Until then check out http://jquery.com/