Sixfoot Studio
Sixfoot Studio

Reputation: 3001

Rotating Divs using jQuery

Simple easy one.

I am trying to rotate image inside divs and cycle back to the first one when the end of my array has been reached. Can someone please help point me out where I am going wrong in my code here? It seems that when it gets to the second image, the index never returns back to zero to start with the first image in my array again.

var images = new Array ('.advert1', '.advert2');
var index = 0;

function rotateImage()
{

$(images[index]).fadeOut('fast', function()
{
    index++;        

    $(images[index]).fadeIn('fast', function()
    {

        if (index == images.length-1)
        {
            index = 0;
        }

    });
});
}

This is being called with a setInterval every 5 seconds.

 setInterval (rotateImage, 5000);

Many thanks!

Upvotes: 0

Views: 397

Answers (1)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195982

You need to check if the index has broken out of bounds before using it ..

function rotateImage()
{

  $(images[index]).fadeOut('fast', function()
   {
       index++;
       if (index == images.length)
           {
               index = 0;
           }
       $(images[index]).fadeIn('fast');
   });
}

that is because when your function got called and index was 1 it would be come 2 and then try to fade in the images[2] which would fail ...

Upvotes: 1

Related Questions