Tooltip Component
Axiom01's tooltip component provides a small, contextual popup that displays informative text when a user hovers over or focuses on an element. It's designed to be non-intrusive and enhance user understanding without cluttering the interface.
Live Example
Basic Tooltip (Hover over me)
Tooltip Positions
HTML Structure
A tooltip consists of a trigger element and the tooltip content itself, typically wrapped in a container.
<div class="tooltip">
<button class="button primary tooltip-trigger" aria-describedby="my-tooltip-id">Hover for Info</button>
<div role="tooltip" id="my-tooltip-id" class="tooltip-content">
This is a helpful tooltip!
</div>
</div>
Styling
The .tooltip class provides the positioning context. The .tooltip-content is initially hidden and styled to appear as a small, informative box. Modifier classes like .top, .right, .bottom, and .left are used to control the tooltip's position relative to its trigger.
.tooltip: Container for the trigger and content, providing relative positioning..tooltip-trigger: The element that activates the tooltip (e.g., a button, icon, or text)..tooltip-content: The actual tooltip text, initially hidden and styled with background, text color, padding, and border-radius.- Positioning classes (
.top,.right,.bottom,.left) on the.tooltipcontainer adjust the absolute position of the.tooltip-content.
JavaScript Integration
Tooltips require JavaScript to handle their show/hide behavior on hover and focus. The script should toggle a class (e.g., .is-visible) on the .tooltip-content and manage ARIA attributes.
<script>
document.addEventListener('DOMContentLoaded', () => {
document.querySelectorAll('.tooltip').forEach(tooltipContainer => {
const trigger = tooltipContainer.querySelector('.tooltip-trigger');
const content = tooltipContainer.querySelector('.tooltip-content');
if (!trigger || !content) return;
const showTooltip = () => {
tooltipContainer.classList.add('is-visible');
};
const hideTooltip = () => {
tooltipContainer.classList.remove('is-visible');
};
trigger.addEventListener('mouseenter', showTooltip);
trigger.addEventListener('mouseleave', hideTooltip);
trigger.addEventListener('focus', showTooltip);
trigger.addEventListener('blur', hideTooltip);
});
});
</script>
Accessibility
Tooltips are designed with accessibility in mind:
- The trigger element has
aria-describedbypointing to the tooltip's ID, linking the two for screen readers. - The tooltip content has
role="tooltip". - Tooltips are activated on both hover (mouse users) and focus (keyboard users).
- The content is hidden from assistive technologies when not visible.
Customization
Customize the appearance using Axiom01's CSS variables for colors, spacing, and typography. You can adjust the background, text color, padding, border-radius, and shadow of the tooltip content.