Reputation: 11
I am trying to build a website with a background that switches images every five seconds. I use javascript to achieve this. After some fiddling around i stumbled upon what seems to be a scope issue, as it keeps telling me that the var imageCount is undefined. i am a bit of a newbie regarding javascript and stackoverflow and i appreciate any help i could get.
html
<body>
<div id="overlay">
</div>
<script>
window.setInterval(execute, 5000);
var imageCount;
function execute() {
console.log("bla");
if(imageCount == 0){
document.body.style.backgroundImage = "url('huis1.jpg')";
console.log("huis1");
}
else if(imageCount == 1){
document.body.style.backgroundImage = "url('huis2.jpg')";
console.log("huis2");
}
else if(imageCount == 2){
document.body.style.backgroundImage = "url('huis3.jpg')";
console.log("huis3");
imageCount = 0;
}
console.log(imageCount);
}
</script>
</body>
i would like to also post the CSS to this file but i wouldn't know how to do it if my life depended on it.
Upvotes: 1
Views: 2012
Reputation:
You don't need the global variable imageCount for this implementation.
It can easily be done using a closure
See code below:
window.setInterval(execute(), 5000);
function execute() {
var imageCount = 0;
return function() {
console.log("bla");
if(imageCount == 0){
document.body.style.backgroundImage = "url('huis1.jpg')";
console.log("huis1");
imageCount = 1;
} else if(imageCount == 1){
document.body.style.backgroundImage = "url('huis2.jpg')";
console.log("huis2");
imageCount = 2;
} else if(imageCount == 2){
document.body.style.backgroundImage = "url('huis3.jpg')";
console.log("huis3");
imageCount = 0;
}
console.log(imageCount);
}
}
Upvotes: 2
Reputation: 2113
As mention in the comment you have to initialise your variable.
You also have to increment your index each iteration, and if you only change the background you maybe not need the if
.
var imageCount = 0; // initialise your index variable
function execute() {
// increment your index if value is less than 2 otherwise set it to 0
imageCount = (imageCount >= 2) ? 0 : ++imageCount;
// concate your image name with the index value
document.body.style.backgroundImage = "url('huis" + (imageCount + 1)+ ".jpg')";
}
window.setInterval(execute, 5000);
Upvotes: 1