Mike Vierwind
Mike Vierwind

Reputation: 1520

Set a different timeout to each selected element

I am currently adding a class name "animate" to <li> items with this script:

$('.list-blocks li').addClass('animate');

But this script immediately sets the class to the selected elements.

How can I add the class to the next selected element with one second buffer?

For example: After the page is loaded, the script give the first li the class "animate". After 1 second, the second li get the class "animate". And after 2 seconds the third li gets the class "animate".

How can I achieve this effect?

Upvotes: 1

Views: 1160

Answers (2)

Anujith
Anujith

Reputation: 9370

Try:

$('.list-blocks li').each(function (index) {
  var item = $(this);
  setTimeout(function () {
    item.addClass('animate');
  }, index * 1000);
});

Demo

Upvotes: 3

Willem Mulder
Willem Mulder

Reputation: 13994

Loop over all elements and set a timeout.

$('.list-blocks li').each(function(index, elm) {
    setTimeout(function () {
        $(elm).addClass('animate');
    }, index*1000);
});

should work. See http://api.jquery.com/each/ and https://developer.mozilla.org/en-US/docs/DOM/window.setTimeout

Upvotes: 4

Related Questions