Aleix
Aleix

Reputation: 497

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.

Upvotes: 0

Views: 110

Answers (3)

user1726343
user1726343

Reputation:

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/

Upvotes: 2

S&#233;bastien Renauld
S&#233;bastien Renauld

Reputation: 19672

Your answer:

$('<tr><td><h3>Hello</h3></td><td>'+i+'</td</tr>')
.hide()
.appendTo('#table')
.delay(delay2)
.fadeIn("slow")
.queue(function() { $(this).css('display', 'table-row'); });

The explanation is simple: when you chain events that go in the queue and events that do not go in the queue, the events that do not go in the queue will bypass it. $.css() does not go in the fx queue, so will be executed immediately.

The solution to this is to use the $.queue() function to queue your non-queueable calls into the fx queue.

Working fiddle: http://jsfiddle.net/u5dEp/6/

(That's a lot of queues in one answer)

Upvotes: 3

Jai
Jai

Reputation: 74738

even this can work: http://jsfiddle.net/pYYFM/8/

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").queue();
                                               ^-------missed this
};​

Upvotes: 1

Related Questions