htmlfunctiononmouseoveronkeydown

How can I reset background color on keypress?


I'm trying to have divs that, when moused over, change their background color, and being able to reset those colors. I've managed the former, but the latter is giving me issues.

As written, the divs do, in fact, change color, but attempting to press a key does not result in anything. I've also tried to put the resetColor function in the same block of Script, but doing so makes it so I can't even hover over and change the colors of those divs. As such, I'm wondering what I should do to be able to reset the divs' color?

function randomColor(element) {
  var x = Math.floor(Math.random() * 256);
  var y = Math.floor(Math.random() * 256);
  var z = Math.floor(Math.random() * 256);
  var bgColor = "rgb(" + x + "," + y + "," + z + ")";
  console.log(bgColor);
  element.backgroundColor = bgColor;
}

function resetColor(element) {
  element.backgroundColor = '#ffff99';
}
body {
  background-color: lightblue;
}

.colorCell {
  border: 1px solid black;
  width: 10px;
  padding: 5px;
  background-color: #ffff99;
  border-radius: 0px;
}
<div class="colorCell" onmouseover="randomColor(this.style)" onkeydown="resetColor(this.style)">
  <!--Successfullly changed color-->
  <!--<a onmouseover="colorCell.body.style.backgroundColor = '#f39352'">-->
</div>
<div class="colorCell" onmouseover="randomColor(this.style)" onkeydown="resetColor(this.style)">
</div>
<div class="colorCell" onmouseover="randomColor(this.style)" onkeydown="resetColor(this.style)">
</div>


Solution

  • an idea can be to :

    let elementHovered = null;
    
    function getRandomColor() {
      return Math.floor(Math.random() * 256);
    }
    
    function randomColor(element) {
      const bgColor = `rgb(${getRandomColor()}, ${getRandomColor()}, ${getRandomColor()})`;
      console.log(bgColor);
      element.backgroundColor = bgColor;
    }
    
    function resetColor(element) {
      element.backgroundColor = '#ffff99';
    }
    
    [...document.querySelectorAll('.colorCell')].forEach(cell => {
      cell.addEventListener('mouseover', () => {
        elementHovered = event.target.style;
        randomColor(elementHovered);
      });
    });
    
    document.addEventListener('keydown', () => {
      if (elementHovered) {
        resetColor(elementHovered)
      }
    });
    body {
      background-color: lightblue;
    }
    
    .colorCell {
      border: 1px solid black;
      width: 10px;
      padding: 5px;
      background-color: #ffff99;
      border-radius: 0px;
    }
    <div class="colorCell"></div>
    <div class="colorCell"></div>
    <div class="colorCell"></div>