views:

82

answers:

4

Possible Duplicate:
jquery finish one animation then start the other one

I've got a set of divs loading via ajax (we're talking about 6 divs, representing 6 products).

What I'm trying to accomplish is a progressive animation, like a jquery.fadeIn() per div, after the animation of the previous div has finished. What would be the optimal way to do this ?

I'm thinking like this:

  1. i get the new html elements via ajax - done
  2. i iterate over them - i can insert them as hidden then iterate over them
  3. for each one, i show it with a fadeIn() and when the animimation finishes, i show the next one - for each one I execute fadeIn with a callback to the next one somehow...
A: 

Most of the jQuery effects support a callback function. So what you've outlined should work.

http://api.jquery.com/fadeIn/

bryanbcook
+1  A: 

The animate function has a callback in it, designed to run after the code has completed.

F.Aquino
+2  A: 

You can build your own little plugin to do a recursive calling on the elements to fade them in sequentially. Something like this should work:

$.fn.queuedFadeIn = function(speed) {
    var elem = $(this);
    if(elem.length > 0) {
        elem.eq(0).fadeIn(speed, function() {
            elem.slice(1).queuedFadeIn(speed);
        });
    }
}

$('.div_selector').queuedFadeIn(1000);

This should fade them in one after the another. Here's the same in pseudo-code to make things clearer:

# If there are elements in the selection:
    # Find the first element in selection, fade it in
       # After fade in, call itself, discarding the first element
Tatu Ulmanen
works great, added one more line so that i will show my pagination after the animation finishes so it won't look weird. thank you
dakull
A: 

Here's another way of doing it. Sort of weird, but it works.

var callbacks = [];

$.each(["f", "e", "d", "c", "b", "a"], function(index, id) {
    callbacks[index] = function() {
        $("#" + id).fadeIn(callbacks[index - 1]);
    };
});

callbacks[5]();
Emmett
Novel way of thinking there. You'd better just `each()` through an set of elements and use the object directly, instead of string values as ID's. That way it could be a bit more readable and doesn't require naming elements `#a`, `#b`, `#c`...
Tatu Ulmanen