So on my new website in google chrome, I am trying to make the images switch every 5 seconds using a setInterval function. This seems to work, however I have the problem cannot set property src of null.
var images = new Array();
images[0] = "/images/grilled-chicken-large.png";
images[1] = "/images/sizzly-steak.png";
var img = document.getElementById("img");
function changeImage() {
for (var i = 0; i < 3; i++) {
img.src = images[i];
if (i == 2){i = i - 2;};
}
}
window.onload=setInterval("changeImage()", 5000);
I know the problem is that I am trying to get the element with an id of img before the page is done loading, but I've already got a window.onload, so i don't know what to do. Also, if i make an init() function containing the setInterval and the img variable, the page freezes.
Any ideas?
images[0]
andimages[1]
, but you're trying to accessimages[2]
. – bfavarettosetInterval
, it useseval
. Pass functions:setInterval(changeImage, 5000);
. Also,window.onload = setInterval(changeImage, 5000);
doesn't do what you think it does. – Rocket HazmatsetInterval
, immediately then assigns the result of that method (it's an integer used as ID) towindow.onload
, which does not make sense. See my anwer, I've added theonload
stuff. – Yogu