Chaining in jQuery

By | October 1, 2022

Before we discuss about jQuery Chaining of Methods, Consider a situation when you want to perform the following actions on an HTML element:

  • 1 – Select a paragraph element.
  • 2 – Change the color of the paragraph.
  • 3 – Apply FadeOut efect on the paragraph.
  • 4 – Apply FadeIn effect on the paragraph.

Following is the jQuery program to perform the above mentioned actions:

<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"></script>
<script>
   $(document).ready(function() {
      $("button").click(function(){
         $("p").css("color", "#fb7c7c");
         $("p").fadeOut(1000);
         $("p").fadeIn(1000);
      });
   });
</script>
<style>
   button{width:100px;cursor:pointer;}
</style>
</head>
<body>
   <p>Click the below button to see the result:</p>

   <button>Click Me</button>
</body>
</html>

jQuery Method Chaining

jQuery method chaining allows us to call multiple jQuery methods using a single statement on the same element(s). This gives a better performance because while using chaining, we do not need to parse the whole page every time to find the element.

To chain different methods, we simply need to append the method to the previous method. For example our above program can be written as below:

<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"></script>
<script>
   $(document).ready(function() {
      $("button").click(function(){
         $("p").css("color", "#fb7c7c").fadeOut(1000).fadeIn(1000);
      });
   });
</script>
<style>
   button{width:100px;cursor:pointer;}
</style>
</head>
<body>
   <p>Click the below button to see the result:</p>

   <button>Click Me</button>
</body>
</html>

Animation with Chaining

We can take advantage of jQuery Method Chaining while writing jQuery animation programs. Following is a simple animation program written with the help of chaining:

<html>
<head>
<title>The jQuery Example</title>
<script src="https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"></script>
<script>
   $(document).ready(function() {
      $("button").click(function(){
         $("div").animate({left: '250px'})
         .animate({top: '100px'})
         .animate({left: '0px'})
         .animate({top: '0px'});
      });
   });
</script>
<style>
   button {width:125px;cursor:pointer}
   #box{position:relative;margin:3px;padding:10px;height:20px; width:100px;background-color:#9c9cff;}
</style>
</head>
<body>
<p>Click on Start Animation button to see the result:</p>

<div id="box">This is Box</div>
<button>Start Animation</button>
</body>
</html>

Leave a Reply

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