I was trying to solve this : Whenever i will enter the mouse cursor in a parent div,the background color of that div will change randomly

First I thought I solved the problem as everytime i entered the cursor inside the div, the background color changed randomly. But the issue was as long as i was keeping the cursor inside the div and moving over child elements, background color kept changing randomly. How will I fix it?

<div class="card-border" id="triangleColorChange">
  <img src="images/triangle.png" alt="...">
  <div>
    <h5>Triangle</h5>
    <h6>Area(A)= .5 x b x h </h6>
    <input type="text" placeholder="b" id="triangleB"><span> cm</span>
    <input type="text" placeholder="h" id="triangleH"><span> cm</span>
    <br><br>
    <button id="trianglrBtn">Calculate</button>
  </div>
</div>

<script>
  function getRandomColor() {
    const letters = '0123456789abcdefABCDEF';

    let color = '#';

    for (let i = 0; i < 6; i++) {
      color = color + letters[Math.floor(Math.random() * 22)];

    }
    return color;
  }
  
  document.getElementById('triangleColorChange').addEventListener('mouseover', function() {
    const triangleArea = document.getElementById('triangleColorChange');
    triangleArea.style.backgroundColor = getRandomColor();

  })
  
  document.getElementById('triangleColorChange').addEventListener('mouseleave', function() {
    const triangleArea = document.getElementById('triangleColorChange');
    triangleArea.style.backgroundColor = 'white';
  })
</script>

>Solution :

One way to do it would be to add a variable "mouseOn" that remembers if you’re on the div or not. Here is the code :

  let mouseOn = false;
  function getRandomColor() {
    const letters = "0123456789abcdefABCDEF";

    let color = "#";

    for (let i = 0; i < 6; i++) {
      color = color + letters[Math.floor(Math.random() * 22)];
    }
    return color;
  }
  document
    .getElementById("triangleColorChange")
    .addEventListener("mouseover", function () {
      if (!mouseOn) {
        mouseOn = true;
        const triangleArea = document.getElementById("triangleColorChange");
        triangleArea.style.backgroundColor = getRandomColor();
      }
    });
  document
    .getElementById("triangleColorChange")
    .addEventListener("mouseleave", function () {
      mouseOn = false;
      const triangleArea = document.getElementById("triangleColorChange");
      triangleArea.style.backgroundColor = "white";
    });
<div class="card-border" id="triangleColorChange">
  <img src="images/triangle.png" alt="..." />
  <div>
    <h5>Triangle</h5>
    <h6>Area(A)= .5 x b x h</h6>
    <input type="text" placeholder="b" id="triangleB" /><span> cm</span>
    <input type="text" placeholder="h" id="triangleH" /><span> cm</span>
    <br /><br />
    <button id="trianglrBtn">Calculate</button>
  </div>
</div>

Leave a Reply