Reputation: 1717
Any idea why this code is broken or not working? It is not my code but it does appear to be correct, of course I could be missing the obvious. I simply need the background image of a div to cycle to a new one in the/a array ever 5 seconds.
var imageIndex = 0;
var imagesArray = new Array();
//Set Images
imagesArray[0] = "images/self-whitewater.png";
imagesArray[1] = "images/fishing.png";
imagesArray[2] = "images/solo-kayaking.png";
function changeBackground(){
$("main-blocki").css("background","url('"+ imagesArray[imageIndex] +"')");
imageIndex++;
if (imageIndex > imageArray.length)
imageIndex = 0;
}
$(document).ready(function() {
setInterval("changeBackground()",5000);
});
Upvotes: 1
Views: 3304
Reputation: 6205
Your problem is in your if
statement, as specified by @thatidiotguy.
But you could also do this in a oneliner, without the if
statement.
var imageIndex = 0;
var imagesArray = [
"images/self-whitewater.png",
"images/fishing.png",
"images/solo-kayaking.png"
];
function changeBackground(){
var index = imageIndex++ % imagesArray.length;
$("main-blocki").css("background","url('"+ imagesArray[index] +"')");
}
$(document).ready(function() {
setInterval(changeBackground, 5000);
});
Notice the imageIndex++ % imagesArray.length
. This increments the global imageIndex
while making sure that the value is not greater than the imagesArray.length
.
Upvotes: 3
Reputation: 1207
if (imageIndex > imageArray.length)
The above line is wrong : you shall want to test imagesArray.length instead
... and you shall test with >= operator also since indexes are 0 based
Upvotes: 1
Reputation: 8971
You have a syntax error here:
if (imageIndex > imageArray.length)
imageIndex = 0;
There is no variable called imageArray
You should use a web debugger to show you when you have syntax errors. One syntax error and Javascript has the grace to kill every other script you are running or trying to run.
Upvotes: 3