During the last year I’ve tried using jQuery as much as possible when it comes to adding JavaScript functionality to web interfaces.
For those who still don’t know, jQuery is a cross browser open source JavaScript library which makes it extremely easy to manipulate HTML, perform Ajax requests, apply visual or interactive effects to your site, etc. If you know how to write CSS, you should be able to use jQuery. And if you work with web applications / -programming, you ought to know how to use jQuery or similar frameworks.
The dual licensing model of jQuery (GPL/MIT) makes it a perfect tool for both open source as well as commercial projects and products.
Here’s an example of what you might had to do in the pre-jQuery era (whose first release was in 2006):
function getElementsByClassName(className, tag, elm){
var testClass = new RegExp("(^|\\\\s)" + className + "(\\\\s|$)");
var tag = tag || "*";
var elm = elm || document;
var elements = (tag == "*" && elm.all) ? elm.all : elm.getElementsByTagName(tag);
var elementList = [];
var current;
var length = elements.length;
for(var i=0; i
current = elements[i];
if(testClass.test(current.className)){
elementList.push(current);
}
}
return elementList;
}
var myElmList = getElmentsByClassName('myClass');
var numElms = myElmList.length;
for( var i = 0; i < numElms; ++i) {
// ...
}
Thanks to jQuery, the above code can be stripped down to:
$('.myClass').each( function(i) {
// ...
});
Nice?
(For those unfamiliar with jQuery: $ is simply an alias for jQuery, so calling $('.myClass'); would be the same as jQuery('.myClass'); as long as we’re not operating under jQuery.noConlfict()).
Selectors
jQuery works by binding JavaScript functions or snippets to DOM elements. The elements that we bind our JavaScript to are selected from the DOM based on CSS (pseudo) selectors.
A selector might be as simple as an element name, such as for example p for all paragraphs in the DOM.
In addition, jQuery adds basic filters such as :first, :last, :even, for selecting only the first, the last, the "even" (index based) and the "odd" matched elements respectively.
dd
In other words: to select the last paragraph in the DOM, you could write
$('p:last');
Alerting the text contained in this element would be as simple as:
alert( $('p:last').text() );
You can also select elements based on the element ID or class name, just as in CSS: p#some-id, p.some-class.
Or you can select all spans that are the next sibling of a p.some-class:
$('p.some-class + span');
Further, jQuery supports content filters (such as :not(), :contains()), visibility filters (:hidden, :visible), attribute filters (such as [attribute='value']), child filters (:first-child, :last-child,
nly-child) and form filters (:input, :text, :password, :button, :disabled, :selected, etc.).
The filters makes it very easy to bind JavaScript functions to DOM elements, and you can of course build quite complex filters by combining the various filter types.
See jQuery.com for documentation and examples.
Chaining jQuery calls
Calling jQuery() on a DOM nodeset returns a jQuery object. Therefore, you can chain jQuery calls — like so:
$('p').addClass('foo').removeClass('bar');
The above code would do two things:
- Add the CSS class
foo - Remove the CSS class
bar
…from all <p>s in the HTML DOM.
In fact, most jQuery calls returns a jQuery object on which we can call all methods defined on the jQuery class, and the ones that don’t are the obvious ones — for example text() which returns a string, and get() which returns the HTMLElement.
$(document).ready()
When adding JavaScript functionality to web sites, we often rely on the window.onload or body.onload functions to make sure that our code runs when the document is loaded.
However, these functions run after all content items, including images, javascript, etc., have been fully loaded into the browser.
Therefore, jQuery includes a method (cross-browser, of course) for executing code once the DOM has been built. This means that you can be sure that your code is run before all ads, etc. are loaded. Using this functionality is as easy as wrapping your calls inside $(document).ready():
$(document).ready( function() {
doMyStuff();
});
Example: Collapsable Sections
Ok. Enough of the foo-bar stuff. In order for this not to turn into a Hello World tutorial, lets have a look at how you might create collapsable blocks of HTML code.
Given the HTML:
<h2 class="collapsable">Section1</h2> <div> <p>para</p> <p>para</p> </div> <h2 class="collapsable">Section1</h2> <div> <p>para</p> <p>para</p> </div> <h2 class="not-collapsable">Section3</h2> <div> <p>this will not be a collapsable field</p> </div>
the following JavaScript is (thanks to jQuery) all it takes to turn the "sections" into collapsable blocks (like the ones in this blog’s sidebar).
$(document).ready( function() {
$("h2.collapsable").click( function() { // applies the anonymous function to all h2s of class collapsable
if($(this).hasClass("expanded")) {
$(this).removeClass("expanded").addClass("collapsed");
} else {
$(this).removeClass("collapsed").addClass("expanded");
}
$(this).next().toggle();
});
});
The magic is really in the short piece of code being:
$("h2.collapsable").click(function() {
$(this).next().toggle();
});
$(this) gives us a jQuery object wrapped around the current HTMLElement, next() selects the next sibling of the current HTMLElement and toggle() makes this sibling either appear or disappear (really sets the CSS display to either block or none), based on the current status.
The other stuff is just for adding CSS classes in which we could e.g. define which background image (+/- sign, for example) is to be used.
jQuery UI
jQuery UI is a library which extends jQuery, adding visual effects and widgets.
The widgets include datepicker, draggable, droppable, etc, whereas the visual effects include stuff like highlighting, fading in / fading out text, sliding blocks, etc. All by writing a simple one liner.
You really ought to check it out.
Separation of HTML/CSS/JavaScript
Even though jQuery makes it extremely easy to do stuff in JavaScript, it is very important that JS-code is separated from HTML and CSS. I also believe it is very important to keep defining all CSS in separate CSS-files — for example by adding/removing classes on elements, rather than using the jQuery.css() method to apply CSS directly on the elements.
$(document).ready(
function() {}
);
should, as all other JS, be placed in a separate .js file which is loaded into the DOM as part of the HTML head.
Try jQuery!
If you’re like me, you’ll start loving jQuery as soon as you start using it.
Go to http://www.jquery.com/ to get the latest version of jQuery.
jQuery UI is located at http://ui.jquery.com/, while http://docs.jquery.com/ is a good source of documentation and examples on applying jQuery. There’s also tons of awesome jQuery plug-ins, such as jquery.cycle, out there.
I’ll try to write some follow ups on this post, showing how to apply jQuery in the real world.