reitermarkus
reitermarkus

Reputation: 708

How to fade in divs in sequence with Javascript (jQuery)?

What i want is to fade in my sidebar boxes after each other on page load by adding a class.

I have tried the following:

var a = $(".sidebar-box"), delayTime = 2000;

for(var i = 0; i < a.length; i++) {
    setTimeout(function(
        var ai = $(a[i]);
        ai.addClass("fade in");
        console.log(ai);
    ), delayTime);

    console.log(delayTime);
    delayTime += 2000;
}

The problem is, by the time the class gets added the first time, i already is 4, so the class only gets added to the last box, when actually it should be added to the first one.

Upvotes: 1

Views: 826

Answers (2)

user1796666
user1796666

Reputation:

You need to create a separate function so that variable i is copied each time:

var a = $(".sidebar-box"), delayTime = 2000;

var func = function(i)
{
    setTimeout(function() {
        var ai = $(a[i]);
        ai.addClass("fade in");
    }, delayTime);
}

for(var i = 0; i < a.length; i++) {
    func(i);
    delayTime += 2000;
}

Upvotes: 1

techfoobar
techfoobar

Reputation: 66663

Instead of adding a class and animating via CSS, if you are okay with using jQuery's fadeIn() method, you can have it like:

var a = $(".sidebar-box"), delayTime = 2000, i = 0;

function animateSideBar() {
    if(i >= a.length) return;

    // call fadeIn, and pass this function itself as the completion callback
    $(a[i]).fadeIn(delayTime, animateSideBar);

    i++;
}

animateSideBar(); // start it

Upvotes: 1

Related Questions