What is Chaining in jQuery?

You may have come across a term "Chaining" in jQuery. But do you know what is Chaining in jQuery? There is no specific definition available for this term in jQuery but it is also not different from the general meaning of Chain. In general term Chain is, "A connected flexible series of metal links used for fastening or securing objects and pulling or supporting loads." Below images dictates what is chaining.

Okay..As far as jQuery is concerned then undoubtedly Chaining is one of the most powerful feature of jQuery. Even in jQuery, Chaining means to connect multiple functions, events on selectors. To understand it better take a look at Sample Code 1 and 2.

Sample Code 1

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

Sample Code 2

?$(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. But you must be thinking that why do I say so?

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.

Important points about Chaining

  • It makes your code short and easy to manage.
  • It gives better performance.
  • The chain starts from left to right. So left most will be called first and so on.

Not only functions or methods, chaining also works with events in jQuery. For example, below piece of code have click, mouseover and mouseout event for a button.

?$(document).ready(function() {
    $("#btnDummy").click(function(e) {
        alert("click!");
    }).mouseover(function(e) {
        alert("mouse over!")
    }).mouseout(function(e) {
        alert("mouse out!")
    });
});?

See result below.

See Complete Code

Feel free to contact me for any help related to jQuery, I will gladly help you.



Responsive Menu
Add more content here...