Alternate content of a div every 3 seconds with javascript

javascript, jquery

Solution

Try

jQuery(function () {
    var $els = $('div[id^=quote]'),
        i = 0,
        len = $els.length;

    $els.slice(1).hide();
    setInterval(function () {
        $els.eq(i).fadeOut(function () {
            i = (i + 1) % len
            $els.eq(i).fadeIn();
        })
    }, 2500)
})

Demo: Fiddle

Problem

I would like to alternate the contents of a div (or swap in a new div if better) every few seconds, with a fade in/out. Jquery prefered, or pure js fine too. Based on Arun's solution, I have added the Jquery below, and it works perfectly... but how do I make it repeat? HTML: ``` <div class="wrapper" style="height:100px"> <div id="quote1">I am a quote</div> <div id="quote2">I am another quote</div> <div id="quote3">I am yet another quote</div> </div> ``` Javascript: (as per Arun in the comments) ``` jQuery(function () { var $els = $('div[id^=quote]'), i = 0, len = $els.length; $els.slice(1).hide(); setInterval(function () { $els.eq(i).fadeOut(function () { $els.eq(++i % len).fadeIn(); }) }, 2500) }) ```

Original source