0

This is my code and when I am clicking on the button (btnColor) it is only showing last color in an array and not working

var color = ["#222F3E","#F368E0","#EE5253","#ABDE3","#10AC84","#222F3E","#5F27CD","pink"];
var btnColor = document.getElementById("color_change");


btnColor.addEventListener("click", function() {

    for(var i = 0; i < color.length; i++) {
        document.querySelector("body").style.background = color[i];
    }
})
Dharman
  • 30,962
  • 25
  • 85
  • 135
  • Duplicate of https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example – Ray Toal Aug 24 '19 at 19:04
  • The listener function goes through the entire loop. You need to put a counter outside the closure and use that for the color index. Also, you can add 1 to the counter on each click inside the closure to move it along the colors. – Ryan Morton Aug 24 '19 at 22:01
  • Possible duplicate of [addEventListener using for loop and passing values](https://stackoverflow.com/questions/19586137/addeventlistener-using-for-loop-and-passing-values) – Ryan Morton Aug 24 '19 at 22:02
  • Possible duplicate of [JavaScript closure inside loops – simple practical example](https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – nbk Aug 24 '19 at 23:35

2 Answers2

1

It is cycling through all the colors, but it's happening immediately when you press the button.

To clarify: It cycles through everything, but it happens too fast for you to see.

If you want to make the background cycle once when you press the button, use the following code.

var color = ["#222F3E","#F368E0","#EE5253","#ABDE3","#10AC84","#222F3E","#5F27CD","pink"];
var btnColor = document.getElementById("color_change");
var colorI = 0;

btnColor.addEventListener("click", function() {

    document.querySelector("body").style.background = color[colorI];
    colorI++;
    colorI = colorI % color.length;
})
Aggs123
  • 171
  • 8
0

instead of a loop, add a variable colorIndex and increment it after each time the button is clicked, and check if you reach the end, reset it to 0 :

var color = ["#222F3E", "#F368E0", "#EE5253", "#ABDE3", "#10AC84", "#222F3E", "#5F27CD", "pink"];
var btnColor = document.getElementById("color_change");

var colorIndex = 0;

btnColor.addEventListener("click", function() {
  if (colorIndex === color.length) colorIndex = 0;
  document.querySelector("body").style.background = color[colorIndex++];

})
<button id="color_change">Click me</button>
Taki
  • 17,320
  • 4
  • 26
  • 47