Why I cannot refer to the images array?

Viewed 62

i try to swap the images continuously from the array, but the code does not get the image source, why this happened?

function nextPic(){
    var picCollection =["pic_bulbon.gif","pic_bulboff.gif"];
    for(i=0; i<picCollection.length; i++){
        document.getElementById("myImage").src = picCollection[i].src;
    }
}

function triggers(){
    setInterval(nextPic,500);
}
4 Answers

You need create a global variable for picture number. Then use that inside callback passed to setInterval. The above code will only show the last image of array.

let pic = 0;
const picCollection =["pic_bulbon.gif","pic_bulboff.gif"];

function nextPic(){
  document.getElementById("myImage").src = picCollection[pic];
  console.log("The pic shown is ", picCollection[pic])
  pic++;
  if(pic === picCollection.length){
    pic = 0;
  }
}

function triggers(){
    setInterval(nextPic,500);
}

triggers()
<img id="myImage"/>

Might be Your code should be

var picCollection =["pic_bulbon.gif","pic_bulboff.gif"];
var i=0;
var interval;
function nextPic(){
    document.getElementById("myImage").src = picCollection[i];
    // if you want to repeat for show image again and again tehn use below line
    i= (i+1) % picCollection.length;

    // if you want not to repeat again then use below line
    // if(i+1>=picCollection.length) clearInterval(interval);
   
}

function triggers(){
    interval=setInterval(nextPic,500);
}

Here you have to define the image name array in global which should be accessible in all desire functions. It is good if you store setInterval reference in variable and clear it by clearInterval.

There is no src key in your arrat. You can just use

document.getElementById("myImage").src = picCollection[i];

Your code should look something similar to below

function nextPic(){
  var picCollection = ["./pic_bulbon.gif","./pic_bulboff.gif"];

  for(i = 0; i < picCollection.length; i++){
    document.getElementById("myImage").src = picCollection[i];
  }
}

"./pic_bulbon.gif" may need to change based off of your file structure and where you are storing the gif you are trying to access.

If you could supply a screenshot of your file structure I could tell you exactly what you need

The other issue you are having is your trying to access picCollection[i].src

but picCollection[i] is only an array of string not objects.

Related