Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

jQuery Chaining


May 07, 2021 jQuery


Table of contents


jQuery - Chaining


With jQuery, actions/methods can be linked together.

Chaining allows us to run multiple jQuery methods (on the same element) in one statement.


jQuery method link

Until now, we've all written one jQuery statement at a time (one after another).

However, there is a technique called chaining that allows us to run multiple jQuery commands on the same element, one after the other.

Tip: That way, the browser doesn't have to look for the same element multiple times.

To link an action, simply append it to the previous action.

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

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

Try it out . . .

We can also add multiple method calls if needed.

Tip: When you link, the lines of code become poor. However, the jQuery syntax is not very strict;

Writing as follows also works well:

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

Try it out . . .

jQuery throws away the extra spaces and executes the lines of code above as a long line of code.