I am attempting to modify the body’s background color using JavaScript event listeners. There are no error messages, but the color does not change when the button is clicked.
// Update body background color
const buttonChangeColor = document.querySelector('#change-color-button');
const colorPalette = ['red', 'yellow', 'purple', 'cyan', 'gray'];
buttonChangeColor.addEventListener('click', function() {
for(let j = 0; j < colorPalette.length; j++) {
document.body.style.backgroundColor = colorPalette[j];
}
});
I’ve run into similar situations in the past, and I suspect that your event listener might be cycling through all colors too quickly for you to notice any change. Each iteration of your loop is executing immediately, so the body color ends up being the last color in your array—‘gray’—once the loop completes. To cycle through colors visually, consider using a counter to keep track of the current color index and increment it upon each click, wrapping around using modulus. Something like:
let currentIndex = 0;
buttonChangeColor.addEventListener('click', function() {
document.body.style.backgroundColor = colorPalette[currentIndex];
currentIndex = (currentIndex + 1) % colorPalette.length;
});
With this approach, each click on the button will set the background to the next color, effectively cycling through your palette.