Search code examples
jqueryloopsdelayeachsetinterval

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');
    }
  });

Solution

  • 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