Search code examples
javascriptjquerydelayfadein

FadeIn stops working when delayed in loop


I want to add .delay() to this, so each item will animate one after the other. The problem is that if I add delay() to the element the fadeIn stops working.

Working code (but without delay...)

time = 500;

for (var i=1;i<=5;i++){

    delay2 = (i * time);
    $('<tr><td><h3>Hello</h3></td><td>'+i+'</td</tr>').hide().appendTo('#table').fadeIn("slow").css('display', 'table-row');

    // do more stuff here

};

jsfiddle example

FadeIn not working (as it has delay...)

time = 500;

for (var i=1;i<=5;i++){

    delay2 = (i * time);
    $('<tr><td><h3>Hello</h3></td><td>'+i+'</td</tr>').hide().appendTo('#table').delay(delay2).fadeIn("slow").css('display', 'table-row');

    // do more stuff here

};

jsfiddle example

Does anyone know what is the problem? In the second example it should animate the items one after te other, but that does not happen, they're not even animated.


Solution

  • Try this:

    $('<tr><td><h3>Hello</h3></td><td>'+i+'</td</tr>')
    .appendTo('#table')
    .hide()
    .delay(delay2)
    .show('slow');
    

    The problem here is that the css change occurs instantly, whereas you want it to occur after the fade in is complete. You do not need fadeIn at all here, especially since show will remember the display attribute value and restore it automatically.

    Here is a fiddle: http://jsfiddle.net/u5dEp/7/