jQuery Tutorial

jQuery Chaining Effect (Functions Explained With Example)

jQuery Chaining Method

You can chain actions/methods together with jQuery.

Chaining allows us to use a single statement to execute many jQuery methods (on the same element).

 

Example of jQuery Chaining

 

We've been writing jQuery statements (one after the other).

There is, however, a method known as chaining that allows us to run multiple jQuery commands. So, for example, you can run the order on the same element after the other (s).

Tip: Browsers will not have to look for the same element(s) twice this way.

Add it to the end of the preceding one to chain an action.

The CSS()slideUp(), and slideDown() methods are combined in the following example. The "p1" element turns red initially, then moves up and down:

Example 

$("#p1").css("color", "red").slideUp(2000).slideDown(2000);

If more method calls were required, we could have done so.

Tip: When chaining lines of code, the line of code can get rather long. On the other hand, jQuery is not particularly rigid about syntax; you can format it as you like, including line breaks and indentations.

Example

$("#p1").css("color", "red")
  .slideUp(2000)
  .slideDown(2000);

Extra whitespace is removed by jQuery, and the lines above are executed as a single long line of code.

Did you find this article helpful?