Search code examples
javascriptdelaymouseout

js Tooltip with delayed mouseout without jQuery


I want to display a tooltip when hovering a div. It should also be displayed when the mouse is hovering the tooltip-div.

Adding an event listener does this job, but if both divs are not overlapping the mouseout calls when the mouse is between them and the tooltip disappears.

Now I want to add a delay for the mouseout which is cancelled when it gets a new mouseover, but I don't know how.

document.getElementById("hoverElem").addEventListener("mouseover", function() {
  document.getElementById("displayElem").style.visibility = "visible";
});

document.getElementById("hoverElem").addEventListener("mouseout", function() {
  document.getElementById("displayElem").style.visibility = "hidden";
});
#hoverElem {
  position: fixed;
  height: 100px;
  weidth: 200px;
  top: 0px;
  left: 50%;
  background-color: white;
}
#displayElem {
  position: fixed;
  height: 100px;
  weidth: 20px;
  top: 150px;
  left: 50%;
  background-color: yellow;
  visibility: hidden;
}
<div id="hoverElem">
  A little Div
  <div id="displayElem">
    Tooltip to show
  </div>
</div>


Solution

  • You can intiate a timer in the mouseleave and then clear it in mouseenter of displayElem like

    document.getElementById("hoverElem").addEventListener("mouseenter", function() {
      document.getElementById("displayElem").style.visibility = "visible";
    });
    
    var hoverTimer;
    document.getElementById("hoverElem").addEventListener("mouseleave", function() {
      hoverTimer = setTimeout(function() {
        document.getElementById("displayElem").style.visibility = "hidden";
      }, 500);
    });
    document.getElementById("displayElem").addEventListener("mouseenter", function() {
      clearTimeout(hoverTimer);
    });
    
    document.getElementById("displayElem").addEventListener("mouseleave", function() {
      this.style.visibility = "hidden";
    });
    #hoverElem {
      position: fixed;
      height: 100px;
      weidth: 200px;
      top: 0px;
      left: 50%;
      background-color: white;
    }
    #displayElem {
      position: fixed;
      height: 100px;
      weidth: 20px;
      top: 150px;
      left: 50%;
      background-color: yellow;
      visibility: hidden;
    }
    <div id="hoverElem">
      A little Div
      <div id="displayElem">
        Tooltip to show
      </div>
    </div>