Question

I am trying to create a simple slideshow consisting of 3 rotating images that will start over as soon as the last has displayed, timed 5000ms apart.

<div id="slideshow">&nbsp;</div>

<script type="text/javascript">
var imageArray = ['Image1','Image2','Image3'];
var currentIndex = 0;

nextPic = function(currentIndex,slideshow) {

  var theHTML = '<img src="http://www.domain.com/Pics/Test-' + imageArray[currentIndex] + '.jpg">';
  document.getElementById("slideshow").innerHTML = theHTML;

  if (currentIndex < imageArray.length) {
      currentIndex = currentIndex + 1;
  }
    else {
      currentIndex = 0;
    }

  setTimeout("nextPic(" + currentIndex + ")", 5000);
}

nextPic(currentIndex, "slideshow");

</script>

Every variation of Javascript code I have found has produced the same result: after the last image (Test-Image3.jpg), the JS attempts to display an undefined image ("Test-undefined.jpg") before resetting back to the first one. It works perfectly fine other than that and it's quite maddening.

Was it helpful?

Solution

You need to take into account the fact that you're adding one after checking against the length of the array:

if (currentIndex < imageArray.length - 1) {
  currentIndex = currentIndex + 1;
}
else {
  currentIndex = 0;
}

or

currentIndex += 1;
if (currentIndex >= imageArray.length)
  currentIndex = 0;

You really don't need to pass the parameter at all, however, because the function can just use the global variable. (It'd be better not to have one, but since you do, well, you might as well use it.)

OTHER TIPS

Change to:

  if (currentIndex < imageArray.length - 1) {
      currentIndex = currentIndex + 1;
  }

That is because otherwise, it will try to display imageArray[imageArray.length].

Also, instead of:

currentIndex = currentIndex + 1;

You could just use:

currentIndex ++;

A cleaner implementation using setInterval():

var slide = function(){
   //check if we are at the end of the array, either stop or replay.                               
   if (currentIndex == imageArray.length){
        currentIndex = 0; //replay slideshow

   /*to stop slideshow add this:
   *     window.clearInterval(slideInt)     
   *     return false;
   */

   }
     var theHTML = '<img src="http://www.domain.com/Pics/Test-' +    
                    imageArray[currentIndex] + '.jpg">';
     document.getElementById("slideshow").innerHTML = theHTML;
     currentIndex +=1;
}

  var imageArray = ['Image1','Image2','Image3'];
  var currentIndex = 0;
  var speed = 5000;
  var slideInt = window.setInterval(slide,speed); //skip a photo every 5000 milis
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top