Actually, we have been using jQuery statements one at a time. But with jQuery chaining method, we can bind multiple methods in a single statement on a single element.

What is meant by Chaining in jQuery?

jQuery Chaining is another robust feature, which allows to perform multiple action in a single line of code. It is possible because most of the methods return a jQuery object, which can be further used to call another method.

When we use chaining method, then there is no need to use the same selector more than once. Using chaining method, we can chain multiple methods and make the code short.

Why to use jQuery Chaining?

While using chaining in your code, it makes your code very short and easy to manage also. This will leads to provide a better performance. Normally, the chain starts from left to right and the left most will be called first.

For Example

<script type=”text/javascript”>

$(document).ready(function(){

    $(“button”).click(function(){

        $(“p”).animate({width: “100%”}).animate({fontSize: “46px”}).animate({borderWidth: 30});

    });

}); 

</script>

In the above example, when the user triggers the button, it expands p to 100% width. Once the process is complete, the font-size will be start animating and finally the border animation will begin.

Implementing chaining in slide up and slide down method functions. Let’s see how to write the code for chaining.

<body> 
    <p id="para">Chaining method in jQuery</p> 
      <button>Click me</button> 
      <script type="text/javascript"> 
        $(document).ready(function() { 
            $("button").click(function() { 
                //assigning the color blue 
                $("#para").css("color", "blue") 
                //using slide up method 
                    .slideUp(2000)   
                 //using slide down method 
                    .slideDown(2000). 
                slideUp(2000). 
                slideDown(4000); 
            }); 
        }); 
    </script> 
</body>

Leave a Reply

Your email address will not be published. Required fields are marked *