What is Chaining in jQuery?

In jQuery, Chaining means to connect multiple functions, events on selectors. look at Sample Code 1 and 2.

$(document).ready(function(){
     $('#dvContent').addClass('dummy');
     $('#dvContent').css('color', 'red');
     $('#dvContent').fadeIn('slow');
 });​

$(document).ready(function(){

     $('#dvContent').addClass('dummy')
           .css('color', 'red')
           .fadeIn('slow');  
 });​

Both the sample codes above will perform the exact same thing but the only difference is that Sample code 2 is using Chaining. But Code 2 is faster and shorter then Code 1.

The problem with the Sample Code 1 is that for every statement, jQuery has to search the entire DOM and find the element and after that executes the attached function on it. But when chaining is used, then jQuery has to find the element only once and it will execute all the attached functions one by one. This is the advantage of Chaining.

No comments:

Post a Comment