Home > OS >  Button not doing anything if clicked
Button not doing anything if clicked

Time:08-05

I'm making an Etch-a-Sketch project and when I click the black button, it works. The background color of the squares turns black when hovered. But when I click the rainbow button it doesn't work. It should change the background color of the squares to a random color when hovered.

Here's the HTML:

<button id="black"  onclick="changeColor('black')"> <span> Black</span> </button>
<button id="rainbow"  onclick="changeColor('random')"> <span> Rainbow</span></button>

Here's the JS:

 let color = "black";

      function getColor(){
        if(true){
          if(color === "random"){
            let value = "0123456789ABCDEF";
        var random = "#";
        for (let i = 0; i < 6; i  ){
          color  = value[Math.floor(Math.random() * 16)];
        }
        this.style.backgroundColor = random;
          } else{
            this.style.backgroundColor = color;
          }
        }
      }
    
      function changeColor(select){
        color = select;
      }

The getColor() function is called in getGrid(size) function. Like this: square.addEventListener("mouseover", getColor);

Here's the fiddle: https://jsfiddle.net/JaredDev/w2kgubLq/6/

What should I do to make the rainbow button generate a random background color to a square/pixel when hovered?

CodePudding user response:

after you generate a random color, you store it in color which will become color = "random{some random string}" and then you assign random = "#" to this.style.backgroundColor. you need to assign the random color to random.

...
for (let i = 0; i < 6; i  ){
    random  = value[Math.floor(Math.random() * 16)];
}
...
  • Related