jQuery - Chaining


With jQuery, you can combine actions / modes.

Chaining allows us to use multiple jQuery methods (in the same component) within a single statement.


jQuery Method Chaining

So far we have been writing jQuery statements one at a time (one after another).

However, there is a process called chaining, which allows us to apply multiple jQuery commands, in sequence, to the same element (s).

Tip: In this way, browsers do not have to get the same element (s) more than once.

To combine an action, simply add the action to the previous action.

The following example combines css(), slideUp(), and slideDown() methods. The "p1" element first turns red, then slides up, then slides down:


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

We may also add calls for additional options if needed.

Tip: When tying, the line of code may be too long. However, jQuery is not very strong in syntax; you can format it the way you like, including cutting lines and undoing.

This also works well:


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

JQuery dumps extra white space and uses the above lines as one long line of code.