Recipe 13.8

Showing a Tooltip

You can use a popover element as a tooltip, showing and hiding it on the corresponding mouse events.

Demo

Code

JavaScript
const button = document.querySelector('#trigger');
const tooltip = document.querySelector('#tooltip');

function showTooltip() {
  // Find the position of the trigger element
  const triggerRect = trigger.getBoundingClientRect();

  // Since the popover is positioned relative to the viewport,
  // you need to account for the scroll offset.
  tooltip.style.top = `${triggerRect.bottom + window.scrollY}px`;
  tooltip.style.left = `${triggerRect.left}px`;

  tooltip.showPopover();
}

// Show and hide the tooltip in response to mouse events.
button.addEventListener('mouseover', () => {
  showTooltip();
});

button.addEventListener('mouseout', () => {
  tooltip.hidePopover();
});

// For keyboard accessibility, also show and hide the tooltip
// in response to focus events.
button.addEventListener('focus', () => {
  showTooltip();
});

button.addEventListener('blur', () => {
  tooltip.hidePopover();
});
HTML
<style>
  #tooltip {
    margin: 0;
    margin-top: 1em;
    position: absolute;
  }
</style>

<button type="button" class="btn btn-primary" id="trigger">Hover Me</button>
<div id="tooltip" popover="manual" role="tooltip">Here is some tooltip content</div>
Web API Cookbook
Joe Attardi