function change(i) {
var doc = document.getElementById("background");
var color =[ "black", "blue", "brown", "green"];
for(i=0; i<color.length; i++){
doc.style.backgroundColor = color[i];
alert("my color is "+ color[i]);
/*if (i>=color.length){i=0;}*/
}
}
setInterval(function changebackground(){change(0)},1000);
HI Folks, I am trying to change the background color of a div using the code above. The function works as long as the alert is part of it (I introduced the alert to see if the loop was working ). How do I get the function working without the alert. I need to use vanilla js not jquery. Thanks for helping a beginner.
The function works fine (without the alert), you're just not seeing it since you're changing the color within a synchronous loop.
Try like this:
var i = 0;
function change() {
var doc = document.getElementById("background");
var color = ["black", "blue", "brown", "green"];
doc.style.backgroundColor = color[i];
i = (i + 1) % color.length;
}
setInterval(change, 1000);
<div id="background"> </div>
Since you're using setInterval, there's no need to use a for loop. Try this instead:
var doc = document.getElementById("background");
var color = ["black", "blue", "brown", "green"];
var i = 0;
function change() {
doc.style.backgroundColor = color[i];
i++;
if(i > color.length - 1) {
i = 0;
}
}
setInterval(change, 1000);
<div id="background" style="height: 200px;"></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With