Tooltip
A popup that displays information related to an element when the element receives keyboard focus or the mouse hovers over it.
🤖 AI Implementation GuideDemo
Accessibility Features
WAI-ARIA Roles
-
tooltip- A contextual popup that displays a description for an element
WAI-ARIA tooltip role (opens in new tab)
WAI-ARIA States & Properties
aria-describedby
References the tooltip element to provide an accessible description for the trigger element.
| Applied to | Trigger element (wrapper) |
| When | Only when tooltip is visible |
| Reference | aria-describedby (opens in new tab) |
aria-hidden
Indicates whether the tooltip is hidden from assistive technology.
| Values | true (hidden) | false (visible)
|
| Default | true |
| Reference | aria-hidden (opens in new tab) |
Keyboard Support
| Key | Action |
|---|---|
| Escape | Closes the tooltip |
| Tab | Standard focus navigation; tooltip shows when trigger receives focus |
Focus Management
- Tooltip never receives focus - Per APG, tooltips must not be focusable. If interactive content is needed, use a Dialog or Popover pattern instead.
- Focus triggers display - When the trigger element receives focus, the tooltip appears after the configured delay.
- Blur hides tooltip - When focus leaves the trigger element, the tooltip is hidden.
Mouse/Pointer Behavior
- Hover triggers display - Moving the pointer over the trigger shows the tooltip after the delay.
- Pointer leave hides - Moving the pointer away from the trigger hides the tooltip.
Important Notes
Note: The APG Tooltip pattern is currently marked as "work in progress" by the WAI. This implementation follows the documented guidelines, but the specification may evolve. View APG Tooltip Pattern (opens in new tab)
Visual Design
This implementation follows best practices for tooltip visibility:
- High contrast - Dark background with light text ensures readability
- Dark mode support - Colors invert appropriately in dark mode
- Positioned near trigger - Tooltip appears adjacent to the triggering element
- Configurable delay - Prevents accidental activation during cursor movement
Source Code
Tooltip.vue
<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch } from 'vue';
import { cn } from '@/lib/utils';
export type TooltipPlacement = 'top' | 'bottom' | 'left' | 'right';
export interface TooltipProps {
/** Tooltip content */
content: string;
/** Controlled open state */
open?: boolean;
/** Default open state (uncontrolled) */
defaultOpen?: boolean;
/** Delay before showing tooltip (ms) */
delay?: number;
/** Tooltip placement */
placement?: TooltipPlacement;
/** Custom tooltip ID for SSR */
id?: string;
/** Whether the tooltip is disabled */
disabled?: boolean;
/** Additional class name for the wrapper */
class?: string;
/** Additional class name for the tooltip content */
tooltipClass?: string;
}
const props = withDefaults(defineProps<TooltipProps>(), {
open: undefined,
defaultOpen: false,
delay: 300,
placement: 'top',
id: undefined,
disabled: false,
class: '',
tooltipClass: '',
});
const emit = defineEmits<{
'update:open': [value: boolean];
}>();
// Generate unique ID
let uid = '';
onMounted(() => {
uid = props.id ?? `tooltip-${crypto.randomUUID().slice(0, 8)}`;
tooltipId.value = uid;
});
const tooltipId = ref(props.id ?? '');
const internalOpen = ref(props.defaultOpen);
const isControlled = computed(() => props.open !== undefined);
const isOpen = computed(() => (isControlled.value ? props.open : internalOpen.value));
let timeout: ReturnType<typeof setTimeout> | null = null;
const setOpen = (value: boolean) => {
if (!isControlled.value) {
internalOpen.value = value;
}
emit('update:open', value);
};
const showTooltip = () => {
if (props.disabled) return;
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(() => {
setOpen(true);
}, props.delay);
};
const hideTooltip = () => {
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
setOpen(false);
};
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === 'Escape' && isOpen.value) {
hideTooltip();
}
};
watch(isOpen, (newValue) => {
if (newValue) {
document.addEventListener('keydown', handleKeyDown);
} else {
document.removeEventListener('keydown', handleKeyDown);
}
});
onUnmounted(() => {
if (timeout) {
clearTimeout(timeout);
}
document.removeEventListener('keydown', handleKeyDown);
});
const placementClasses: Record<TooltipPlacement, string> = {
top: 'bottom-full left-1/2 -translate-x-1/2 mb-2',
bottom: 'top-full left-1/2 -translate-x-1/2 mt-2',
left: 'right-full top-1/2 -translate-y-1/2 mr-2',
right: 'left-full top-1/2 -translate-y-1/2 ml-2',
};
</script>
<template>
<span
:class="cn('apg-tooltip-trigger', 'relative inline-block', props.class)"
@mouseenter="showTooltip"
@mouseleave="hideTooltip"
@focusin="showTooltip"
@focusout="hideTooltip"
:aria-describedby="isOpen && !disabled ? tooltipId : undefined"
>
<slot />
<span
:id="tooltipId"
role="tooltip"
:aria-hidden="!isOpen"
:class="
cn(
'apg-tooltip',
'absolute z-50 px-3 py-1.5 text-sm',
'rounded-md bg-gray-900 text-white shadow-lg',
'dark:bg-gray-100 dark:text-gray-900',
'pointer-events-none whitespace-nowrap',
'transition-opacity duration-150',
placementClasses[placement],
isOpen ? 'visible opacity-100' : 'invisible opacity-0',
props.tooltipClass
)
"
>
{{ content }}
</span>
</span>
</template> Usage
Example
<script setup>
import Tooltip from './Tooltip.vue';
</script>
<template>
<Tooltip
content="Save your changes"
placement="top"
:delay="300"
>
<button>Save</button>
</Tooltip>
</template> API
| Prop | Type | Default | Description |
|---|---|---|---|
content | string | - | Tooltip content (required) |
open | boolean | - | Controlled open state (v-model:open) |
defaultOpen | boolean | false | Default open state (uncontrolled) |
delay | number | 300 | Delay before showing (ms) |
placement | 'top' | 'bottom' | 'left' | 'right' | 'top' | Tooltip position |
id | string | auto-generated | Custom ID |
disabled | boolean | false | Disable the tooltip |
Testing
Testing Overview
The Tooltip component tests are organized into priority levels based on APG compliance requirements.
Test Categories
High Priority: APG Core Compliance
| Test | APG Requirement |
|---|---|
| role="tooltip" exists | Tooltip container must have tooltip role |
| aria-hidden when closed | Hidden tooltips must not be read by AT |
| aria-describedby when visible | Trigger must reference tooltip only when visible |
| Escape key closes tooltip | Keyboard dismissal support |
| Focus shows tooltip | Keyboard accessibility |
| Blur hides tooltip | Focus management |
Medium Priority: Accessibility Validation
| Test | WCAG Requirement |
|---|---|
| No axe violations (hidden state) | WCAG 2.1 AA compliance |
| No axe violations (visible state) | WCAG 2.1 AA compliance |
| Tooltip is not focusable | APG: tooltips must not receive focus |
Low Priority: Props & Extensibility
| Test | Feature |
|---|---|
| placement prop changes position | Positioning customization |
| disabled prop prevents display | Disable functionality |
| delay prop controls timing | Delay customization |
| id prop sets custom ID | SSR/custom ID support |
| controlled open state | External state control |
| onOpenChange callback | State change notification |
| className inheritance | Style customization |
Running Tests
# Run all Tooltip tests
npm run test -- tooltip
# Run tests for specific framework
npm run test -- Tooltip.test.tsx # React
npm run test -- Tooltip.test.vue # Vue
npm run test -- Tooltip.test.svelte # Svelte Tooltip.test.vue.ts
import { render, screen, waitFor } from '@testing-library/vue';
import userEvent from '@testing-library/user-event';
import { axe } from 'jest-axe';
import { describe, expect, it, vi } from 'vitest';
import Tooltip from './Tooltip.vue';
describe('Tooltip (Vue)', () => {
describe('APG: ARIA 属性', () => {
it('role="tooltip" を持つ', () => {
render(Tooltip, {
props: { content: 'This is a tooltip' },
slots: { default: '<button>Hover me</button>' },
});
expect(screen.getByRole('tooltip', { hidden: true })).toBeInTheDocument();
});
it('非表示時は aria-hidden が true', () => {
render(Tooltip, {
props: { content: 'This is a tooltip' },
slots: { default: '<button>Hover me</button>' },
});
const tooltip = screen.getByRole('tooltip', { hidden: true });
expect(tooltip).toHaveAttribute('aria-hidden', 'true');
});
it('表示時は aria-hidden が false', async () => {
const user = userEvent.setup();
render(Tooltip, {
props: { content: 'This is a tooltip', delay: 0 },
slots: { default: '<button>Hover me</button>' },
});
const trigger = screen.getByRole('button');
await user.hover(trigger);
await waitFor(() => {
const tooltip = screen.getByRole('tooltip');
expect(tooltip).toHaveAttribute('aria-hidden', 'false');
});
});
});
describe('APG: キーボード操作', () => {
it('Escape キーで閉じる', async () => {
const user = userEvent.setup();
render(Tooltip, {
props: { content: 'This is a tooltip', delay: 0 },
slots: { default: '<button>Hover me</button>' },
});
const trigger = screen.getByRole('button');
await user.hover(trigger);
await waitFor(() => {
expect(screen.getByRole('tooltip')).toHaveAttribute('aria-hidden', 'false');
});
await user.keyboard('{Escape}');
await waitFor(() => {
expect(screen.getByRole('tooltip', { hidden: true })).toHaveAttribute(
'aria-hidden',
'true'
);
});
});
it('フォーカスで表示される', async () => {
const user = userEvent.setup();
render(Tooltip, {
props: { content: 'This is a tooltip', delay: 0 },
slots: { default: '<button>Hover me</button>' },
});
await user.tab();
await waitFor(() => {
expect(screen.getByRole('tooltip')).toHaveAttribute('aria-hidden', 'false');
});
});
});
describe('ホバー操作', () => {
it('ホバーで表示される', async () => {
const user = userEvent.setup();
render(Tooltip, {
props: { content: 'This is a tooltip', delay: 0 },
slots: { default: '<button>Hover me</button>' },
});
await user.hover(screen.getByRole('button'));
await waitFor(() => {
expect(screen.getByRole('tooltip')).toHaveAttribute('aria-hidden', 'false');
});
});
it('ホバー解除で閉じる', async () => {
const user = userEvent.setup();
render(Tooltip, {
props: { content: 'This is a tooltip', delay: 0 },
slots: { default: '<button>Hover me</button>' },
});
const trigger = screen.getByRole('button');
await user.hover(trigger);
await waitFor(() => {
expect(screen.getByRole('tooltip')).toHaveAttribute('aria-hidden', 'false');
});
await user.unhover(trigger);
await waitFor(() => {
expect(screen.getByRole('tooltip', { hidden: true })).toHaveAttribute(
'aria-hidden',
'true'
);
});
});
});
describe('アクセシビリティ', () => {
it('axe による WCAG 2.1 AA 違反がない', async () => {
const { container } = render(Tooltip, {
props: { content: 'This is a tooltip' },
slots: { default: '<button>Hover me</button>' },
});
const results = await axe(container);
expect(results).toHaveNoViolations();
});
it('tooltip がフォーカスを受け取らない', () => {
render(Tooltip, {
props: { content: 'This is a tooltip' },
slots: { default: '<button>Hover me</button>' },
});
const tooltip = screen.getByRole('tooltip', { hidden: true });
expect(tooltip).not.toHaveAttribute('tabindex');
});
});
describe('Props', () => {
it('placement prop で位置を変更できる', () => {
render(Tooltip, {
props: { content: 'Tooltip', placement: 'bottom' },
slots: { default: '<button>Hover me</button>' },
});
const tooltip = screen.getByRole('tooltip', { hidden: true });
expect(tooltip).toHaveClass('top-full');
});
it('disabled の場合、tooltip が表示されない', async () => {
const user = userEvent.setup();
render(Tooltip, {
props: { content: 'Tooltip', delay: 0, disabled: true },
slots: { default: '<button>Hover me</button>' },
});
await user.hover(screen.getByRole('button'));
await new Promise((r) => setTimeout(r, 50));
expect(screen.getByRole('tooltip', { hidden: true })).toHaveAttribute('aria-hidden', 'true');
});
it('id prop でカスタム ID を設定できる', () => {
render(Tooltip, {
props: { content: 'Tooltip', id: 'custom-tooltip-id' },
slots: { default: '<button>Hover me</button>' },
});
const tooltip = screen.getByRole('tooltip', { hidden: true });
expect(tooltip).toHaveAttribute('id', 'custom-tooltip-id');
});
});
}); Resources
- WAI-ARIA APG: Tooltip Pattern (opens in new tab)
- AI Implementation Guide (llm.md) (opens in new tab) - ARIA specs, keyboard support, test checklist