Javascript – Auto fade/show between multiple divs

javascriptjquery

What's a simple jQuery script I can load on my webpage that will auto fade between each of the three "box" divs, and repeat? I'd like it to show a div for 5 seconds while hiding the other two, then run a 1 second fade transition into the next.

The three div's are currently stacked on top of each other.

<div class="boxes">

<div class="box1">text1</div>
<div class="box2">text2</div>
<div class="box3">text3</div>

</div>

Best Answer

You could try this:

$(document).ready(function () {
    var allBoxes = $("div.boxes").children("div");
    transitionBox(null, allBoxes.first());
});

function transitionBox(from, to) {
    function next() {
        var nextTo;
        if (to.is(":last-child")) {
            nextTo = to.closest(".boxes").children("div").first();
        } else {
            nextTo = to.next();
        }
        to.fadeIn(500, function () {
            setTimeout(function () {
                transitionBox(to, nextTo);
            }, 5000);
        });
    }

    if (from) {
        from.fadeOut(500, next);
    } else {
        next();
    }
}

DEMO: http://jsfiddle.net/CYJLA/

I'm sure it could be cleaned up and/or be more efficient, but I just put it together to get it working.

Related Topic