Search code examples
javascriptjquerycssdelayjquery-animate

jquery - how to queue up a series of css property changes


I want to set a series of animation properties - a list of names that are currently invisible but will be marked visible, one right after another, with a set delay of about 100ms between each other. How do I accomplish this with jquery? Essentially, it would be something like this (pseudo-code):

for each $(.item) {
$(this).delay(index*100ms).css({'visibility': 'visible'}
}

The only thing that might compound this, while most of the elements would have the same class, not all of them would, so an animation queue of some sort would work best.


Solution

  • You can use .delay() to do this.

    $('#foo').slideUp(300).delay(800).fadeIn(400);
    

    When this statement is executed, the element slides up for 300 milliseconds and then pauses for 800 milliseconds before fading in for 400 milliseconds.

    You actually want to do one thing to multiple items, so this is how I'd do that:

    $.each($(".a"), function(index, value) {
        $(this).delay(index*400).fadeOut(400);
    });
    

    You were on the right track with your pseudocode, you need to offset each animation by index * someTime.

    Turns out, .delay() actually doesn't work with css() so here's an updated solution:

    $.each($(".a"), function(index, value) {
        $(this).delay(index*400).queue( function(next){ 
            $(this).css('visibility','visible'); 
            next(); 
          });
    });
    

    demo