Search code examples
jquerycssdelaycss-animations

Css3 animation delay with jquery


I am using scroll animations. I'm using animate.css library and viewport.js. It's clearly working. But I want to dynamically add animation delays. For example: I have social media icon list and I want to delay the animation for each item.

This is my JS code:

$(".animateda:in-viewport(-10)").find(".animated").each(function(queue) {
    $(this).addClass($(this).attr("data-animation"));
});

I can do it by writing a CSS class for each delay:

.animate-delay-1{animation-duration:.6s;animation-delay:.3s}
.animate-delay-2{animation-duration:.6s;animation-delay:.6s}.....

And use this JS code:

$(this).find(".animated-item").each(function(queue) {
    $(this).addClass("animate-delay-"+(queue+1)).addClass($(this).attr("data-animation"));
});

It's working good. But I must write a CSS delay class for all of the objects that have a animation. Can I make the delays with jQuery without using different CSS classes for each object?


Solution

  • You could try using the setTimeout function.

    setTimeout takes two arguments, a callback function and a delay in ms. If you wanted to delay the adding of a class by 6 seconds, you could do something like this:

    var delay = 6000;
    $(".animateda:in-viewport(-10)").find(".animated").each(function(queue) {
        setTimeout(function() {
            // do some animation here
        }, delay);
    });
    

    This would do the animation (roughly) six seconds after it was called.

    EDIT: If you wanted to change the length of the animation each time, you could do something like this: The setTimeout must be wrapped in a closure, to stop the value of i changing within the method.

    var i = 0;
    $(".animateda:in-viewport(-10)").find(".animated").each(function(queue) {
        (function(i) {
            setTimeout(function() {
                // do some animation here
            }, i * 350);
        })(i);
        i++; // increment i for each item
    });