Recipe 13.8
Showing a Tooltip
Compatibility Note: Popover
This feature may not be supported on all browsers yet. Please check the latest compatibility data before using in a production application.
Browser support for PopoverYou can use a popover element as a tooltip, showing and hiding it on the corresponding mouse events.
Demo
Here is some tooltip content
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>