0

I have a CSS animation that I want to be applied in 200ms intervals. I've set up the CSS like this:

.discrete {
    position:relative;
    opacity:1;

    -webkit-transition: all .5s linear;
    -moz-transition: all .5s linear;
    -o-transition: all .5s linear;
    transition: all .5s linear;
}

.discrete.out {
    left:-40px;
    opacity:0;    
}

I then want to stagger the application of the .discrete.out class in 200ms intervals. I've tried the following:

$('.discrete').each(function() {
    $(this).delay(200).addClass('out');
});

And this:

$('.discrete').each(function() {
   var theNode = $(this); 
   setTimeout(function() {
       theNode.addClass('out');
    }, 200);
});

But in both cases, the animation just occurs all at once!

Any ideas?

daniel0mullins
  • 1,937
  • 5
  • 21
  • 45

3 Answers3

4

You could use

var els = $('.discrete'),
    i = 0,
    f = function () {
        $(els[i++]).addClass('out');
        if(i < els.length) setTimeout(f, 200);
    };
f();

Demo

Oriol
  • 274,082
  • 63
  • 437
  • 513
  • Marked this one as accepted because this method seems to be significantly faster than using the jQuery animation queue! Thanks to everyone! – daniel0mullins Sep 29 '13 at 03:16
3

Try using the jQuery animation queue: http://jsfiddle.net/gwwar/7zm6q/2/

function createWorkQueueFunction($element) {
    return function(next) {
        $element.addClass("out");
        next();
    };
}

$('button').click(function() {
    var queue = $({}); //use the default animation queue
    $(".discrete").each(function() {
        queue.queue(createWorkQueueFunction($(this)));
        queue.delay(200);
    });
});

But why don't your examples work?

The reason why the following doesn't work is because jQuery will immediately add the 'out' class after adding a 200 ms delay to the fx queue. In other words, delay() will not pause items that are not added to a queue. Please see: What are queues in jQuery? for more information about how jQuery queues work.

$('.discrete').each(function() { $(this).delay(200).addClass('out'); });

In the second example, you're adding the same timeout to each of the .discrete elements. So after roughly 200ms each one will have a class added to it at just about the same time. Instead you probably would have wanted to set a timeout of 200ms, then 400ms, then 600ms and so on for each element.

$('.discrete').each(function() { var theNode = $(this);
setTimeout(function() { theNode.addClass('out'); }, 200); });

Community
  • 1
  • 1
Kerry Liu
  • 2,072
  • 16
  • 16
0

I have created simple 2 line solution which works among all frameworks

let dl = 0.2; //time-delay // <animation class> <gap animation> document.querySelectorAll('.card.fade-in').forEach(o=>{dl+=0.2;o.style.animationDelay=dl+'s'});

Saptarshee Das
  • 339
  • 2
  • 6