# Applying Sequential Effects - J Query

Problem
You want an effect to occur on one set of elements after another effect occurs on a different set of elements. This is simple to solve if you just have one other effect to execute, but if you want to apply the effect one-by-one to any number of elements, the code could become difficult to maintain.

Solution

This solution uses the standard template outlined at the beginning of this chapter,except that we have multiple copies of the div.box element on the page. This solution is designed as such that we can be dealing with any number of div.box elements, from just one single element to many, because the automatic sequence solution can handle them all.

Manual callback

The basic approach to applying sequential effects would be to use the callback. This would also be used if the next effect is different from the first:

Automatic sequence

This alternative method, based on Dave Methvin’s solution, will repeat in sequence the effect on any number of elements:

Discussion

The simple solution uses the callback feature to then step in to the next animation in the sequence. The selector we use targets the first div.box; however, this doesn’t scale because it is expecting there to be two and only two animated elements. Any less and the code breaks. Any more, and some elements will be missed.
If we have many more, or even an unknown number of elements we need to animate in sequence, then Dave Methvin’s solution is perfect.
There are two tricks to the code. The first is the fail over to an empty array:

This code increments the index counter, and if the element doesn’t exist, it passes an empty array to jQuery.
When the jQuery result set is empty, running an animation doesn’t do anything. Since the result is empty, jQuery doesn’t pass any DOM elements to the chained call, and therefore any callbacks given to the chained method won’t be called either.
For example, if we ran the following code, the alert box would never appear—which is a key ingredient to making this recipe work:

The second trick to this recipe is the callback argument:

arguments is a keyword in JavaScript referring to a local variable that all functions haveaccess to. The arguments object is similar to any array but does not have any of the arraymethods (such as slice) or properties except length.
arguments also contains a reference to the currently executing function in the arguments.callee property. This is useful for recursive function calls, which is exactly how we are using the property in this solution.
This solution says to keep incrementing through the $boxes jQuery collection and, on completion of the animation, recursively execute the function. This continues until the <div>index goes beyond the length of the$boxes jQuery collection (\$boxes.length), at which point an empty array is used as the jQuery collection, and thus the callback is not executed, causing the code to finish running.