Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
97
rated 0 times [  103] [ 6]  / answers: 1 / hits: 38160  / 9 Years ago, thu, september 17, 2015, 12:00:00
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.


More From » javascript

 Answers
41

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>&nbsp</div>




[#65019] Wednesday, September 16, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
denver

Total Points: 232
Total Questions: 111
Total Answers: 103

Location: South Korea
Member since Sat, Oct 2, 2021
3 Years ago
;