Chaining Different Effects
Explore the concept of chaining in jQuery and its advantages, along with an example.
We'll cover the following
What is the chaining of effects?
jQuery allows us to chain together different effects for a single selector. The chained effects are placed in a queue and executed in that sequence. The syntax for chaining different effects is straightforward and given below:
$("selector").effectA().effectB().effectC()....effectN()
The effectA()
takes place first. When effectA()
concludes, effectB()
begins its execution, and so on until all the N effects complete their execution.
đź“ť Note:
- Chaining allows us to use a single selector to perform a series of effects instead of continually using the same selector. This significantly reduces the overhead time overhead as the browser does not need to repeatedly look for the same element.
- We can also use the
animate()
method within a jQuery chain.
Example of chaining
In the web page below, we have a div
element and a button
element with the text “Chained effects.” In the click event handler function of the “Chained effects,” we use chaining to perform a series of effects on the div
element. The effects slideUp()
, slideDown()
, fadeOut()
and fadeIn()
execute one after the other when we click on the “Chained effects” button.
Pausing the chain
If we want to briefly pause in the middle of a jQuery chain, we can use the jQuery delay()
method. The delay()
method takes the time in milliseconds as an argument and pauses the chain for the specified period.
For example, in the web page discussed above, we add two breaks of 3 seconds each using the delay()
method shown below in line 5 and line 7.