How to Create a Hover Tooltip with JavaScript How to Create a Hover Tooltip with JavaScript

How to Create a Hover Tooltip with JavaScript

Learn how to create a tooltip over elements using JavaScript.

In this tutorial, we’ll learn how to use the JavaScript’s addEventListener method to create a tooltip (hover effect) for your element of choice. This can be done with CSS also using the attr() property, which I have talked about in my CSS tricks article.

In this context, “with JavaScript” means that we use JavaScript to toggle the display of the tooltip since all of the styling is still done with CSS, as is the fadeIn animation.

.addEventListener() works by letting us monitor various DOM Events and then perform an action based on the type of the said Event. For this tutorial, we’re going to focus on mouseover and mouseleave events. Here is an example you can hover over to see what it looks like:

The tooltip text.

Let’s look at the code that’s making all this possible.

CSSHTMLJavaScript
/* this is a _demo_ container. remember the importance of relative and absolute positioning */
.tooltip-container {
    position: relative;
    display: flex;
    place-content: center;
}

/* styling of the tooltip display */
p#tooltip-text {
    display: none;
    position: absolute;
    top: -60px;
    z-index: 1;
    background: #00732c;
    padding: 8px;
    font-size: 1rem;
    color: #fff;
    border-radius: 2px;
    animation: fadeIn 0.6s;
}

/* optional styling to add a "wedge" to the tooltip */
p#tooltip-text:before {
  content: "";
  position: absolute;
  top: 100%;
  left: 50%;
  margin-left: -8px;
  border: 8px solid transparent;
  border-top: 8px solid #00732c;
}

@keyframes fadeIn {
 from {
   opacity: 0;
 }
 to {
   opacity: 1;
 }
}
<div class="tooltip-container">
  <p id="tooltip-text">The tooltip text.</p>
  <button id="tooltip-button">A paragraph/button with a hover effect.</button>
</div>
// window.onload is optional since it depends on the way in which you fire events
window.onload=function(){

// selecting the elements for which we want to add a tooltip
const target = document.getElementById("tooltip-button");
const tooltip = document.getElementById("tooltip-text");

// change display to 'block' on mouseover
target.addEventListener('mouseover', () => {
  tooltip.style.display = 'block';
}, false);

// change display to 'none' on mouseleave
target.addEventListener('mouseleave', () => {
  tooltip.style.display = 'none';
}, false);

}

I think that overall this is a fairly self-explanatory example. We use getElementById to select the elements for which we want to change the style.display state. This, of course, also works with getElementsByClassName if you want to add the tooltip to a specific class.

This approach is often used in tandem with visual design elements, such as buttons or knobs – as you can add a hover tooltip to clarify the exact action that a specific button/knob is going to do.