Thursday, 31 January 2013

jQuery: chaining!

   


jQueryWe should all bless jQuery. It gives JavaScript a completely new face in terms of usability and easiness.
Considering the latest news about version 2.0, jQuery is quite alive and kicking...

I don't know how many of you know about chaining, but I think we should all try to understand how and why we should use it while writing jQuery code.



As a simple example, you know that we can manipulate DOM elements with specific jQuery methods. As beginners, if we want to manipulate an element more than once, we separate each method as follows:
$("#element").fadeIn('fast');
$("#element").fadeOut('slow');
$("#element").css('marginRight', '10px');
However, we can actually chain all those actions together:
$("#element").fadeIn('fast').fadeOut('slow').css('marginRight', '10px');
As you can see there's an immediate benefit: we write less code which means that our document will be smaller in size.
But that's not all (and definitely not the most important thing!)

First of all, let me say something important. You may think that using chaining we could end up with unreadable code. That's not true because jQuery doesn't care about spaces in code and the above code could be like the following without generating any problem at all:
$("#element").fadeIn('fast')
                     .fadeOut('slow')
                     .css('marginRight', '10px');
The above is surely more readable, but aren't we missing the "size" advantage?
Yes, we are, however we are taking another great advantage none the less.

Every time we use jQuery to manipulate an element, we search for the element itself (using the selector) and then we apply the chosen method. That operation takes time.
Look at the very first example: jQuery searches for the element in each line.
With chaining the element is searched just once: the code will run faster... no doubt about it!

Ok, ladies and gentlemen, that's all for today. See you next time.

2 comments:

Comments are moderated. I apologize if I don't publish comments immediately.

However, I do answer to all the comments.