If you’ve ever tried to write a simple "Fade In" effect that works in both Internet Explorer 6 and Firefox 1.5, you know the pain. You’re wading through hundreds of lines of document.getElementById, attachEvent vs addEventListener, and manual CSS property manipulation. It’s soul-crushing work.
Then comes jQuery.
John Resig’s new library uses a concept so simple it’s brilliant: CSS selectors for DOM manipulation. If you know how to style an element with CSS, you now know how to manipulate it with JavaScript.
// The old way (roughly)
var el = document.getElementById('my-div');
el.style.display = 'none';
// ... complex timing loop for fading ...
// The jQuery way
$('#my-div').fadeIn('slow');
The $ function is the entry point to everything. It returns a "jQuery object" that wraps the DOM elements and provides a suite of cross-browser methods. Want to add a class to every paragraph that has the class "note"? $('p.note').addClass('highlight');. One line. Done.
But it’s not just about shorthand. jQuery handles the "cross-browser" mess for you. It knows about the quirks of IE’s event model. It knows how to handle AJAX requests without you having to check for ActiveXObject vs XMLHttpRequest. It lets you focus on the behavior of your app instead of the bugs in the browser.
The library also encourages "Chaining." Since most jQuery methods return the jQuery object itself, you can string operations together: $('#menu').show().addClass('active').css('color', 'red');. It’s an incredibly expressive way to write code.
At just 19KB (minified), there’s almost no reason not to use it. Some "pure" JavaScript developers are worried it will make programmers lazy or that they won't understand the underlying DOM. And they might be right. But for those of us with deadlines and a requirement to support IE6, jQuery is a godsend.
The web is finally becoming a fun place to develop for again.
Aunimeda builds modern web frontends - from single-page applications to complex multi-locale sites.
Contact us to discuss your frontend project. See also: Web Development, Corporate Website Development