Floris
Floris

Reputation: 3127

How to animate blocks one after the other?

With this bit of JavaScript I hoped to animate some block element one after the other by adding CSS animation classes with a time out of 500 milliseconds.

Unfortunately it waits one time and all the boxes slide up at once after the one wait.

Here is the script so far:

var blocks = $('.block');

blocks.each(function(index, obj) {
    var block = $(obj);
    setTimeout(function() {
        block.addClass('animated slideInUp');
    }, 500);
});

So, how do I add these classes asynchronically so the boxes on the page will slide up one after the other?

Upvotes: 2

Views: 310

Answers (1)

Ankit Agarwal
Ankit Agarwal

Reputation: 30739

You can consider the index of the each() loop so that in setTimeout() the time will be multiple of 500. With this the boxes will appear in each 500 milliseconds as the setTimeout() will have timeout time as 500, 1000, 1500, ... and so on.

var blocks = $('.block');
blocks.each(function(index, obj) {
    var block = $(obj);
    setTimeout(function() {
        block.addClass('animated slideInUp');
    }, 500*index);
});

Upvotes: 2

Related Questions