In this tutorial you will learn how to use jQuery chaining of multiple methods.
jQuery Chaining Method
The jQuery provides another robust feature called method chaining that allows us to perform multiple action on the same set of elements, all within a single line of code.
This is possible because most of the jQuery methods return a jQuery object that can be further used to call another method. Here’s an example for jQuery Chaining.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Example of jQuery Method Chaining</title> <script src="https://code.jquery.com/jquery-1.11.3.min.js"></script> <style type="text/css"> /* Some custom styles to beautify this example */ p { width: 200px; padding: 40px 0; font: bold 24px sans-serif; text-align: center; background: #aaccaa; border: 1px solid #63a063; box-sizing: border-box; } </style> <script type="text/javascript"> $(document).ready(function(){ $(".start").click(function(){ $("p").animate({width: "100%"}).animate({fontSize: "46px"}).animate({borderWidth: 30}); }); $(".reset").click(function(){ $("p").removeAttr("style"); }); }); </script> </head> <body> <p>Hello World!</p> <button type="button" class="start">Start Chaining</button> <button type="button" class="reset">Reset</button> </body> </html>
The above example demonstrate the chaining of three animate()
method. When a user click the trigger button, it expands the <p>
to 100% width. Once the width
change is complete the font-size
is start animating and after its completion, the border
animation will begin.
Tip:The method jQuery chaining not only helps you to keep your jQuery code concise, but it also can improve your script’s performance since browser doesn’t have to find the same elements multiple times to do something with them.
break a single line of code into multiple lines
.You can also break a single line of code into multiple lines for greater readability. For example, the sequence of methods in the above example could also be written as:
<script type="text/javascript"> $(document).ready(function(){ $("button").click(function(){ $("p") .animate({width: "100%"}) .animate({fontSize: "46px"}) .animate({borderWidth: 30}); }); }); </script>
Some jQuery methods doesn’t return the jQuery object. In general, setters i.e. methods that assign some value on a selection return a jQuery object, that allows you to continue calling jQuery methods on your selection. Whereas, getters return the requested value, so you can’t continue to call jQuery methods on the value returned by the getter.
A typical example of this scenario is the html()
method. If no parameters are passed to it, the HTML contents of the selected element is returned instead of a jQuery object.
<script type="text/javascript"> $(document).ready(function(){ $("button").click(function(){ // This will work $("h1").html("Hello World!").addClass("test"); // This will NOT work $("p").html().addClass("test"); }); }); </script>