I’m trying to write a segment that will change that background color of my
each time I click the button. So far, it only works after the first click and then I need to refresh, and then it works again but only once. I need it to work on repeated clicks.
My code so far:
document.getElementById("mybutton").addEventListener("click", function() {
document.getElementById("p1").style.backgroundColor = randomColor;
});
function getRandomColor(){
const letters = '0123456789ABCDEF';
let color = '#';
for(let i=0; i<6; i++) {
color += letters[Math.floor(Math.random()*16)];
}
return color;
}
console.log(getRandomColor());
const randomColor = getRandomColor();
2
Answers
you only call
getRandomColor()
once in your code here:and so it will only change the color once. Instead of doing this, call it in your method at the top so that it is called each time the button is pressed:
In this code, randomColor is selected as one value.
If you want to change color when you click the button, change the code as follow.