I am trying to make a color changer, I want the program to loop through the array, change the color one by one with every click, then update the color-code class to the name of the array, I haven’t implemented this yet because I want to tackle this initial problem first. So far, It only changes the color to the last index.
const colorArray = ["blue", "green", "red", "orange", "violet", "indigo", "yellow", "white", "pink", "black"];
function changeColor() {
const body = document.querySelector('body');
const bodyColor = body.style.backgroundColor;
const colorCode = document.querySelector('color-code');
const button = document.querySelector('button');
button.addEventListener('click', function () {
for(let i = 0; i < colorArray.length; i++) {
body.style.backgroundColor = colorArray[i];
}
})
}
changeColor();
I tried using a for loop, I’m not quite sure it’s the right way to go.
2
Answers
It is looping through the array. The result is that the last value remains set.
It sounds like you don’t want to loop through the array, but rather want to keep track of the current index of the array and use the "next" one on each click. Something like this:
As understood you need to change new color on every click that means initially first color of the array is visible then on click second color and so on, assuming the same here is the code that can be used to achieve this
Above code will use first value of array as initial color and then on every button click a counter increament will happen and color will be change to next value of the array, also if whole array is iterated the counter will reset and again first color will set