When I start the diashow this is what I get: Uncaught TypeError: Cannot read property 'src' of undefined Pointing to function: runPicGal (see below). Hope you can help. Note: The strange thing is that I see the picture changing ONE time then I get the error.
Full JS File:
var picForDiashow;
var diashowPicArray = [];
var diashowPicArrayIndex = 0;
diashowPicArray [0] = new Image(); diashowPicArray [0].src = "./pics/1.jpg";
diashowPicArray [1] = new Image(); diashowPicArray [0].src = "./pics/2.jpg";
diashowPicArray [2] = new Image(); diashowPicArray [0].src = "./pics/3.jpg";
diashowPicArray [3] = new Image(); diashowPicArray [0].src = "./pics/4.jpg";
diashowPicArray [4] = new Image(); diashowPicArray [0].src = "./pics/5.jpg";
function initForDiashow () {
picForDiashow = document.getElementById("diashowPic");
}
window.onload = initForDiashow;
function startDiashow () {
picInterval = window.setInterval(runPicGal, 1000);
}
function stopDiashow () {
window.clearInterval(picInterval);
}
function runPicGal () {
diashowPicArrayIndex++;
if (diashowPicArrayIndex > diashowPicArray.length) {
diashowPicArrayIndex = 0;
}
picForDiashow.src = diashowPicArray[diashowPicArrayIndex].src;
}
You are always adding the elements to the first position of the array. Thus, only the first element,
diashowPicArray[0], will be accessible. Change the initialization to the following:Also, in your comparison, you should not use
diashowPicArrayIndex > diashowPicArray.length. Otherwise, you’ll try to accessdiashowPicArray[5], which is out of bounds. Use==instead:Or, simplifying the above lines, using modular arithmetic: