Question

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!

Was it helpful?

Solution

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 ...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top