jQuery Minute™

…a jQuery Minute™ later and you're done!

Archive for the ‘Uncommon Features’ Category

jQuery Iteration and each()

without comments

There was a recent thread on the jQuery discussion group in that there was a need for looping through a series of elements and dynamically binding an event. An issue was brought up with closures and the arguments for dynamic binding of functions. Brandon Aaron provided an elegant solution that makes use of jQuery’s internal each() function. Let’s jump in!

So here’s a paraphrase of Brandon’s code:

Example 1:
jQuery.each( [0,1,2,3,4], function(index, item){
// Your code

At first glance this may look the same as your standard iteration code using each but it differs slightly and that is where the benefit is. Let’s look at using the standard each method on a jQuery object:

Example 2:
// Your code

In this example jQuery internally manages the collection (array) of matched elements by the selector.

But, by using jQuery’s internal .each() method (Example 1) we’re able to pass in an arbitrary array in which each item will have the callback executed. An elegant solution to your typical for ( i ) loop. Your callback can accept two arguments: index, item where index is the numerical zero based index in the array of the current item and item is the value of the current array. Also worth noting is that by returning false from you callback you can stop iteration over the array (this is the same as using a break; statement in a for loop).

Happy coding!

Written by jdsharp

February 7th, 2008 at 8:00 am

jQuery Event Namespacing

without comments

A feature often over looked is namespacing your events in jQuery.

jQuery added in support for $(...).bind('event.namespace', fn). This is primarily useful for plugin authors who may bind numerous events to elements and want to remove only their events without needing to keep a pointer to the function they bound. So for example, you can do: $(...).bind('click.myNS', function(){...}); $(...).unbind('click.myNS'); which will unbind the click event with the ‘myNS’ name space.

For more on this read an entry over at Learning jQuery:

Happy eventing!

Written by jdsharp

January 15th, 2008 at 10:49 am

addClass() removeClass()

without comments

If you have to add or remove multiple classes with jQuery, the most efficient way is to separate the classes with a space and make one call.

Such as:

$('body').addClass('abc def');

As opposed to:


Written by jdsharp

December 11th, 2007 at 12:22 pm