skip to Main Content

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


  1. you only call getRandomColor() once in your code here:

    const randomColor = getRandomColor();
    

    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:

    document.getElementById("mybutton").addEventListener("click", function() {
        document.getElementById("p1").style.backgroundColor = getRandomColor();
    });
    
    Login or Signup to reply.
  2. const randomColor = getRandomColor();
    

    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.

        document.getElementById("mybutton").addEventListener("click", function() {
        document.getElementById("p1").style.backgroundColor = getRandomColor();
    
    });
    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());
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search