Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery each add class with delay inbetween

I need to loop through each div .row to add or remove a flip class that has a CSS3 3D transform effect.

When I apply this add/remove class to each ".row" with jquery each(), all the divs get the class ".flip" added or removed at the exact same time. I need this to be delayed so it looks like a domino effect.

Any idea how I can get this working? Or how to add / remove the flip class one by one??

This is what I've found but it is not working:

  $('.row').each(function(i){
    if($(this).hasClass('flip')){
      $(this).delay(i*500).removeClass('flip');
    }else{
      $(this).delay(i*500).addClass('flip');
    }
  });
like image 601
Brandon Waring Avatar asked Oct 01 '12 20:10

Brandon Waring


People also ask

How do I delay the animation in jQuery?

The jQuery delay () method only delays the next pieces in the queue of strung together methods using $ (obj).delay (500).addClass ('flip'); It doesn't delay all subsequent lines of code. (check out the first example and how the code runs its animations side-by-side) Try using setTimeout () instead.

What does addClass() method do in jQuery?

It simply adds the class, appending it to any which may already be assigned to the elements. Before jQuery version 1.12/2.2, the .addClass () method manipulated the className property of the selected elements, not the class attribute. Once the property was changed, it was the browser that updated the attribute accordingly.

Why doesn't the addClass() function wait for animation to finish?

The addClass function isn't an animation function, so it doesn't get queued, and so runs immediately without waiting for the .delay () to finish.

How do I remove a class from an element using jQuery?

If you have it applied to an element but want to remove it from an element after a designated amount of time has passed, you can do so by using jQuery's .setTimeout () method. var header = $ ('#header'); header.addClass ('blue'); setTimeout (function () { header.removeClass ('blue'); }, 4000);


2 Answers

The jQuery delay() method only delays the next pieces in the queue of strung together methods using $(obj).delay(500).addClass('flip'); It doesn't delay all subsequent lines of code. (check out the first example and how the code runs its animations side-by-side)

Try using setTimeout() instead.

$('.row').each(function(i){
  var row = $(this);
  setTimeout(function() {
    row.toggleClass('flip');
  }, 500*i);
});​

Fiddle

like image 183
Scrimothy Avatar answered Sep 16 '22 22:09

Scrimothy


You have to use setTimeout to do a delay effect.

Here is jsFiddle: http://jsfiddle.net/xQkmB/1/

var i = 0;
var rows = $(".row");
show();

function show() {
    if (i < rows.length) {
        $(rows[i]).show();
        i++;
        setTimeout(show, 1000);
    }       
}
like image 24
Michele Bertoli Avatar answered Sep 16 '22 22:09

Michele Bertoli