Jordan Brown
Jordan Brown

Reputation: 439

Change Div Color Dynamically using for loop

let colors = ["red","green","cyan"];
let start = colors[0];
let div = document.getElementById("color");


setInterval(function(){
  document.getElementById("color").style.backgroundColor=colors[0];
  for(var x = 0; x < colors.length; x++){
      document.getElementById("color").style.backgroundColor=colors[x];
      if(colors[x] == colors[colors.length-1]){
          div.style.backgroundColor=start;
          colors[x]++;
      }
    }
},500);

Basically, it loops through the colors but it doesn't reset. What am I actually doing wrong here?

Update:

Thanks to the answer below, I was able to understand what I was doing incorrectly. I've re-written it based on the way I was trying to do it with For Loops.

let colors = ["red","green","cyan","purple","grey"];
let div = document.getElementById("color");

document.getElementById("color").style.backgroundColor=colors[0];

for(let x = 0; x < (colors.length / colors.length); x++){
    var i = x;
    div.style.backgroundColor=colors[i];
}

setInterval(function(){
    div.style.backgroundColor=colors[i];
    i++;
    if(i==colors.length){
        i=0;
    }
},300);

Although inefficient, this is the way I wanted to do it solely for the purpose of testing purposes.

Upvotes: 0

Views: 1396

Answers (1)

Bravo
Bravo

Reputation: 6264

You are running the for loop every 500ms ... but each color change is done within the loop immediately

There's no time for the browser to show anything else but the last background

If what you want to do is simply cycle through those colors, the code is very simple

let colors = ["red","green","cyan"];
let index = 0;
let div = document.getElementById("color");

setInterval(function(){
    div.style.backgroundColor=colors[index];
    index = (index + 1) % colors.length;
},500);
<div id="color">
DIV!
</div>

Upvotes: 4

Related Questions