Jez D
Jez D

Reputation: 1489

create simple rotation with pause

How can I cycle through a series of elements, adding a class, pausing then removing the class and moving on to the next element. I have tried setInterval and I have tried setTimeout, but cannot seem to get it to work.

My Javascript

var numpromos = $('.promoteBlock').length;
var promonum = 1;
while (numpromos > promonum){
    setInterval(function() { 
            $('#promoteCont .promoteBlock').fadeOut().removeClass('active');
            $('#promoteCont #promo'+promonum).addClass('active');   
        } 

    }, 3000);
    promonum++;
}

My HTML

<div id="promoteCont">
            <div id="promo1" class="promoteBlock">Promotion No.1</div>
            <div id="promo2" class="promoteBlock">Second Promo</div>
            <div id="promo3" class="promoteBlock">Another one</div>

         </div>

Upvotes: 0

Views: 80

Answers (2)

Parfait
Parfait

Reputation: 1750

function playNext(){
    console.log("playNext");
    var active = $('#promoteCont').find(".promoteBlock.active");
    if( active.length == 0 )
        active = $(".promoteBlock:eq(0)");

    var fout = active.next();
    if( fout.length == 0 )
        fout = $(".promoteBlock:eq(0)");

    active.fadeOut().removeClass('active');
    fout.fadeIn().addClass('active');

    setTimeout(function(){
        playNext();
    },3000);
}

setTimeout(function(){
    playNext();
},3000);

http://jsfiddle.net/p1c3kzj7/

Upvotes: 2

Paul Zaczkowski
Paul Zaczkowski

Reputation: 2888

Take things out of the while loop. You only need to set the interval once. Perform your state calculation (which item is selected) within the callback method itself. See below, which I believe is what your looking for.

// Global variables to maintain state... I'm sure I'll get some comments about these :p
var numpromos = $('.promoteBlock').length;
var promonum = 1;

$document.ready(function()
{
    setInterval(function() { 
        $('#promoteCont .promoteBlock').fadeOut().removeClass('active');
        $('#promoteCont #promo'+promonum).addClass('active');

        promonum++;

        if(promonums > numpromos)
          promonum = 1;           
    }, 3000);
});

Upvotes: 1

Related Questions