Skip to content
Related Articles

Related Articles

Improve Article

jQuery | chaining()

  • Last Updated : 27 Apr, 2020

jQuery is a very powerful framework of JavaScript. With jQuery, we can use do chaining which means to chain together multiple methods in a single statement on a single element.
We have been using a single statement at once, but now using the chaining method we can bind multiple methods to make the code short. This way, browsers do not have to find the same element(s) more than once.

Advantage:
While using method chaining in jQuery, it ensures that there is no need to use the same selector more than once. Over-using a selector can seriously slow down your code, as every time you call on a selector you are forcing the browser to go looking for it. By combining or “chaining” multiple methods, you can seriously cut down on the number of times you make your browser look for the same elements without having to set any variables.

Implementation of chaining() using JavaScript and jQuery for better understanding:
Code #1: Using Slide up and slide down method functions for chaining-




<!DOCTYPE html>
<html>
  
<head>
    <script src="
    </script>
</head>
  
<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>
  
</html>

Output:

Code #2: Using animate function in jQuery for chaining effect-




<!DOCTYPE html>
<html>
  
<head>
    <script src="
    </script>
  
</head>
  
<body>
  
    <p id="para">Chaining method in jQuery</p>
  
    <button>Click me</button>
  
    <script type="text/javascript">
       $(document).ready(function() {
        $("button").click(function() { 
         $("#para").css("color", "blue").animate({
               width: "100%"
            })
            //it adds animation to the program by styling it
            .animate({
               fontSize: "46px"
             })
            .animate({
                borderWidth: 30
             });
            });
        });
    </script>
</body>
  
</html>

Output:




My Personal Notes arrow_drop_up
Recommended Articles
Page :