Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change background color every second

Tags:

javascript

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.

like image 496
kofi Avatar asked Sep 17 '15 21:09

kofi


2 Answers

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>
like image 180
Amit Avatar answered Oct 16 '22 13:10

Amit


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>
like image 29
Mario Pabon Avatar answered Oct 16 '22 14:10

Mario Pabon