javascripthtmlmouseeventmouseout

Why is mouseout and mouseleave always firing


I really don't get why the p element is always hidden (and therefore why the mouseout is always firing):

const canvas = document.querySelector("canvas");
const infoBox = document.querySelector("#info-box")
canvas.addEventListener("mousemove", evt => {
    evt.preventDefault()
    infoBox.style.display="block"
    infoBox.style.position="absolute"
    infoBox.style.top= evt.clientY+"px"
    infoBox.style.left=evt.clientX+"px"
    console.log("moved")
})
canvas.addEventListener("mouseout", evt => {
    evt.preventDefault()
    infoBox.style.display="none"
    console.log("exit")
}, false)
canvas{
    border-width: 0px;
    border-color:#212121;
    background-color: blue;
}
<canvas></canvas>
<div id="info-box" style="display: none;"><p>Hello</p></div>


Solution

  • The exit happens every time the info-box appears. Adding an offset to the #info-box div means that the mouse doesn't think it has left the canvas.

    const canvas = document.querySelector("canvas");
    const infoBox = document.querySelector("#info-box");
    const mouseOffset = 2;
    
    canvas.addEventListener("mousemove", evt => {
      evt.preventDefault()
      infoBox.style.display = "block"
      infoBox.style.position = "absolute"
      infoBox.style.top = evt.clientY + mouseOffset + "px" // add an offset here
      infoBox.style.left = evt.clientX + mouseOffset + "px" // and here
      console.log("moved")
    })
    canvas.addEventListener("mouseout", evt => {
      evt.preventDefault()
      infoBox.style.display = "none"
      console.log("exit")
    }, false)
    canvas {
      border-width: 0px;
      border-color: #212121;
      background-color: blue;
    }
    <canvas></canvas>
    <div id="info-box" style="display: none;">
      <p>Hello</p>
    </div>