Exercise: Creating a Custom Tooltip with Vanilla JavaScript

Tooltips are small, interactive pop-up elements that provide additional information when hovering over a particular element on a webpage. They are commonly used to offer more context, explain features, or give brief instructions without cluttering the interface. In this blog post, we’ll walk through how to create a simple, custom tooltip using vanilla JavaScript, HTML, and CSS.

What is a Tooltip?

A tooltip is a brief, informative message that appears when a user hovers over, focuses on, or taps an element. Tooltips are particularly useful for enhancing user experience by providing extra context or guidance without overwhelming the interface.

Implementing the Custom Tooltip

Here’s the code to create a custom tooltip:

document.addEventListener("DOMContentLoaded", function() {
const tooltip = document.createElement("div");
tooltip.className = "tooltip";
document.body.appendChild(tooltip);

document.querySelectorAll("[data-tooltip]").forEach(elem => {
elem.addEventListener("mouseenter", function() {
tooltip.textContent = this.dataset.tooltip;
const rect = this.getBoundingClientRect();
tooltip.style.left = rect.left + window.scrollX + "px";
tooltip.style.top = rect.bottom + window.scrollY + "px";
tooltip.style.display = "block";
});

elem.addEventListener("mouseleave", function() {
tooltip.style.display = "none";
});
});
});

Code Explanation

  1. Event Listener for DOMContentLoaded:
    • The script starts by listening for the DOMContentLoaded event, ensuring that all the HTML content is fully loaded and parsed before executing the script. This prevents issues that might arise from trying to manipulate elements that aren’t yet available in the DOM.
  2. Creating the Tooltip Element:
    • const tooltip = document.createElement("div");: This line creates a new div element in the document. This div will serve as our tooltip.
    • tooltip.className = "tooltip";: The div is given a class name of tooltip, allowing us to style it with CSS.
    • document.body.appendChild(tooltip);: The tooltip div is appended to the body of the document, making it available for display when needed.
  3. Selecting Elements with Tooltips:
    • document.querySelectorAll("[data-tooltip]"): This selects all elements in the document that have a data-tooltip attribute. This attribute will hold the text to be displayed in the tooltip.
  4. Handling Mouse Enter:
    • elem.addEventListener("mouseenter", function() { ... });: This adds an event listener to each element with the data-tooltip attribute. The listener triggers when the mouse enters the element.
    • Inside this event listener:
      • tooltip.textContent = this.dataset.tooltip;: The text content of the tooltip is set to the value of the data-tooltip attribute of the hovered element.
      • const rect = this.getBoundingClientRect();: The getBoundingClientRect() method returns the position of the hovered element relative to the viewport.
      • tooltip.style.left = rect.left + window.scrollX + "px";: The left position of the tooltip is set to align with the left side of the hovered element.
      • tooltip.style.top = rect.bottom + window.scrollY + "px";: The top position of the tooltip is set just below the hovered element.
      • tooltip.style.display = "block";: The tooltip is made visible.
  5. Handling Mouse Leave:
    • elem.addEventListener("mouseleave", function() { ... });: This adds an event listener that triggers when the mouse leaves the hovered element.
    • Inside this event listener:
      • tooltip.style.display = "none";: The tooltip is hidden by setting its display property to none.

HTML Structure

Here’s an example of how the HTML might look when using this custom tooltip:

<button data-tooltip="This is a tooltip">Hover over me</button>
  • data-tooltip Attribute:
    • The data-tooltip attribute is used to store the text that will be displayed in the tooltip. In this example, hovering over the button will display the tooltip with the text “This is a tooltip”.

CSS Styling

To style the tooltip, we can use the following CSS:

.tooltip {
display: none;
position: absolute;
background-color: #333;
color: #fff;
padding: 5px;
border-radius: 5px;
font-size: 12px;
z-index: 1000;
}

CSS Explanation

  1. Initial Hidden State (display: none;):
    • The tooltip is hidden by default. It only becomes visible when the user hovers over an element with a data-tooltip attribute.
  2. Positioning (position: absolute;):
    • The tooltip is positioned absolutely relative to the document. This allows it to be placed exactly where needed, based on the position of the hovered element.
  3. Styling:
    • The background color is set to a dark shade (#333), with white text (#fff).
    • Padding and border-radius are added for a clean, rounded look.
    • The font size is set to a smaller size (12px) to keep the tooltip compact.
    • The z-index is set to 1000 to ensure that the tooltip appears on top of other content.

How It Works

  • When the page loads, the tooltip element is created and added to the document.
  • As the user hovers over any element with a data-tooltip attribute, the tooltip is populated with the corresponding text and positioned near the element.
  • The tooltip is shown or hidden based on the mouse events (mouseenter and mouseleave).

Conclusion

Creating a custom tooltip with vanilla JavaScript is a straightforward task that provides a lot of flexibility in terms of styling and behavior. This implementation is lightweight and can be easily customized or extended to fit different needs. By understanding how the tooltip works, you can create more interactive and user-friendly web pages, enhancing the overall user experience.