jQuery - Chaining
With jQuery, you can chain actions/methods together.
Chaining allows us to run multiple jQuery methods (on the same element) within a single statement.
jQuery Method Chaining
Until now, we have been writing one jQuery statement at a time (one after the other).
However, there is a technique called chaining that allows us to run multiple jQuery commands, one after the other, on the same element.
Tip: This way, the browser does not have to find the same element multiple times.
To chain an action, you simply append the action to the previous action.
The following example chains css(), slideUp(), and slideDown() together. The "p1" element will first turn red, then slide up, and then slide down:
Example
$("#p1").css("color","red").slideUp(2000).slideDown(2000);
If needed, we can also add multiple method calls.
Tip: When chaining, the code lines can get quite long. However, jQuery syntax is not very strict; you can write it in the format you prefer, including line breaks and indentation.
The following also works well:
Example
$("#p1").css("color","red")
.slideUp(2000)
.slideDown(2000);
jQuery will strip out the extra spaces and treat the above as a single long line of code.