To create a sequence of fade-ins using jQuery, you can utilize the jQuery queue feature. Here's an example:
View live demo on jsFiddle.
//--- Queue-up the fade-ins
var animationQ = $({});
$("#navtop a").each ( function () {
var jThis = $(this);
animationQ.queue ('FadeIns', function (nextQ_Item) {
jThis.fadeIn (5000, function() {
nextQ_Item ();
} );
} );
} );
//--- Start the fade-ins.
animationQ.dequeue ('FadeIns');
One advantage of this method is that you can queue up any set of nodes without limitations on their relationship to each other.
Update:
To introduce a staggered effect to the fade-in sequence, you can do the following:
var fadeTime = 5000; //-- Duration of each individual fade (in milliseconds)
var fadeStagger = 500; /*-- Delay between the start of one element's fade and
the next element's initiation of fading (in milliseconds)
*/
//--- Queue-up the fade-ins
var animationQ = $({});
$("#navtop a").each ( function (J) {
var jThis = $(this);
animationQ.queue ('FadeIns', function (nextQ_Item) {
jThis.fadeTo (fadeStagger, fadeStagger / fadeTime , function() {
nextQ_Item ();
jThis.fadeTo (fadeTime - fadeStagger, 1);
} );
} );
} );
//--- Start the fade-ins.
animationQ.dequeue ('FadeIns');
Check it out on jsFiddle.
Explanation:
We initialize a generic queue container by creating an empty jQuery object ( $({})
). This approach is cleaner than attaching the queue to a specific node.
We select our nodes using any valid jQuery selector, then iterate through them using the each() function.
For each node, we add an entry into our custom queue using the queue() function.
- We assign a unique name, "FadeIns," to the queue to prevent conflicts.
- Each queue entry receives a pointer to the next entry, provided when it's called. This pointer is captured with the variable
nextQ_Item
.
- The function within each queue item has two purposes: (1) execute the fade effect, and (2) call the next queue entry upon completion.
- We split the fade effect into two parts to achieve the desired staggered starting times.
- The first fade lasts only for the specified
fadeStagger
duration. We calculate the final opacity based on the ratio of the delay time to the total time.
- We then trigger the next element in the sequence.
- Subsequently, we resume and complete the fade, taking into account the remaining time left (total time minus the stagger delay).
- Once our custom queue is constructed, we initiate it using the dequeue() function.