slop audit
Blog post 88 / Accessibility and interaction

Accessible tooltip: HTML, dismissal, and browser tests

Build an accessible tooltip with aria-describedby, Escape dismissal, and persistent hover behavior. Test keyboard access and pointer movement before launch.

By Slop Audit · 8 min read

An accessible tooltip adds a short description to a control without taking keyboard focus away from it. Show the same explanation on pointer hover and keyboard focus, let people move onto the tooltip, and provide a way to dismiss it without leaving the control. Test those transitions before launching a portfolio, dashboard, or student project.

A popup that looks correct in a screenshot can still close while someone moves toward it, cover nearby text, or reopen immediately after Escape. This guide covers the tooltip's markup and interaction contract, with a small implementation and browser tests you can adapt to your public page.

Choose an accessible tooltip or a visible hint

Use a tooltip for supplementary, noninteractive text. Keep instructions needed to complete a task visible. A password requirement, pricing restriction, or destructive-action warning should not depend on discovering a hover target.

If the popup needs a link, input, or close button, choose a disclosure or dialog with its own focus behavior. A tooltip does not receive focus. W3C's ARIA tooltip pattern describes Escape dismissal and keeping focus on the trigger; the page also explicitly marks the pattern as work in progress without task force consensus.

For touch users, the control's visible text should explain the action without a tooltip. If an explanation is necessary on a phone, use a persistent hint or an explicit help disclosure. Do not make a first tap reveal information and a second tap unexpectedly perform an action.

For example, “Download CSV” already names an action and file format. A tooltip can add that the export includes the current filters. A button called only “i” is a different problem: establish its accessible name and decide whether it opens help that people need to interact with.

Connect the trigger to its description

Give the tooltip an ID and reference it from the trigger with aria-describedby. Keep the trigger's name in its visible text. The description supplements that name rather than replacing it.

<div class="tooltip-wrap" data-tooltip>
  <a href="/reports/latest.csv" aria-describedby="export-tip">
    Download CSV
  </a>
  <span id="export-tip" role="tooltip" class="tooltip">
    <span>Includes the filters currently applied to this report.</span>
  </span>
</div>

MDN's tooltip role reference explains the description relationship and why tooltips should not contain interactive descendants. Do not add aria-label to the tooltip container: its actual explanatory text should supply the description. Use unique IDs when rendering several instances.

The example leaves the explanation visible until JavaScript initializes. That gives visitors readable text if the script fails. Once enhanced, the tooltip is visually hidden at rest while the referenced description remains available to accessibility APIs. Verify its announcement in your supported browser and screen-reader combinations.

Keep hover content dismissible and persistent

WCAG 2.2 Content on Hover or Focus, a Level AA criterion, covers additional author-controlled content revealed by hover or focus. It requires a dismissal mechanism unless an exception applies, permits moving the pointer onto revealed content, and prevents arbitrary disappearance while the relevant interaction continues. Browser-controlled presentation, such as an unmodified native title tooltip, has an exception.

For this component, implement these state rules:

  • Show it while the pointer is over the trigger or tooltip, or the trigger has focus.
  • Keep it open when the pointer crosses from the trigger into the explanation.
  • Hide it on Escape, preserving focus and pointer position.
  • After Escape, suppress reopening until both pointer and focus leave the component.
  • Close it after both pointer and focus leave; do not expire it on a reading timer.

A CSS-only :hover rule cannot maintain the Escape suppression state. Pair styles with explicit state, and review the surrounding CSS hover and focus feedback separately.

.tooltip-wrap[data-enhanced] {
  position: relative;
  display: inline-block;
}

.tooltip-wrap[data-enhanced] .tooltip {
  position: absolute;
  inset-block-start: 100%;
  inset-inline-start: 0;
  width: min(18rem, calc(100vw - 2rem));
  padding-block-start: 0.5rem;
  z-index: 10;
}

.tooltip-wrap[data-enhanced] .tooltip > span {
  display: block;
  padding: 0.75rem;
  color: #fff;
  background: #172033;
  border-radius: 0.25rem;
  overflow-wrap: anywhere;
}

.tooltip[hidden] {
  display: none;
}

.tooltip-wrap a:focus-visible {
  outline: 3px solid #005fcc;
  outline-offset: 3px;
}

The tooltip's top padding forms a pointer bridge. A margin would create a gap outside its hit area. This CSS places the popup below the trigger; it is a starting placement, not a collision engine. Near a viewport edge, change its alignment or use a positioning library that handles available space. Check clipping ancestors and stacking contexts: increasing z-index cannot escape an ancestor's overflow clipping.

for (const wrap of document.querySelectorAll('[data-tooltip]')) {
  const trigger = wrap.querySelector('a');
  const tip = wrap.querySelector('[role="tooltip"]');
  let pointerInside = false;
  let focused = false;
  let dismissed = false;

  function render() {
    if (!pointerInside && !focused) dismissed = false;
    tip.hidden = dismissed || !(pointerInside || focused);
  }

  wrap.dataset.enhanced = '';
  render();

  wrap.addEventListener('pointerenter', (event) => {
    if (event.pointerType === 'touch') return;
    pointerInside = true;
    render();
  });
  wrap.addEventListener('pointerleave', () => {
    pointerInside = false;
    render();
  });
  trigger.addEventListener('focus', () => {
    focused = true;
    render();
  });
  trigger.addEventListener('blur', () => {
    focused = false;
    render();
  });
  document.addEventListener('keydown', (event) => {
    if (event.key === 'Escape' && !tip.hidden) {
      dismissed = true;
      render();
    }
  });
}

The document listener also supports a pointer-open tooltip when focus is elsewhere. It does not cancel the key event, so other components may respond to Escape too. In an application with nested popups, coordinate dismissal centrally so one key closes the intended layer. Remove document listeners when a component unmounts, and ensure initialization runs once per instance.

This example does not change the link's navigation behavior. Serve a real export at the destination; connect filter state to that destination in your application. Use the text as an illustration of a description, not as a promise about what an unimplemented export contains.

Test accessible tooltip transitions in Playwright

Mount the example on a dedicated preview route and use a desktop browser project for the pointer tests. Replace the example URL with your fixture. Playwright supports accessible description assertions and pointer hover actions.

import { expect, test } from '@playwright/test';

test('tooltip describes the link and dismisses without blur', async ({ page }) => {
  await page.goto('https://preview.example.com/tooltip-demo');
  const trigger = page.getByRole('link', { name: 'Download CSV' });
  const tip = page.locator('#export-tip');

  await expect(tip).toBeHidden();
  await page.keyboard.press('Tab');
  await expect(trigger).toBeFocused();
  await expect(tip).toBeVisible();
  await expect(trigger).toHaveAccessibleDescription(
    'Includes the filters currently applied to this report.'
  );

  await page.keyboard.press('Escape');
  await expect(tip).toBeHidden();
  await expect(trigger).toBeFocused();
  await trigger.hover();
  await expect(tip).toBeHidden();
});

test('pointer can enter the tooltip and dismiss it in place', async ({ page }) => {
  await page.goto('https://preview.example.com/tooltip-demo');
  const trigger = page.getByRole('link', { name: 'Download CSV' });
  const tip = page.locator('#export-tip');

  await trigger.hover();
  await expect(tip).toBeVisible();
  const box = await tip.boundingBox();
  const origin = await trigger.boundingBox();
  if (!box || !origin) throw new Error('Missing tooltip or trigger box');
  await page.mouse.move(
    origin.x + origin.width / 2, box.y + 2, { steps: 12 }
  );
  await tip.hover();
  await expect(tip).toBeVisible();

  await page.keyboard.press('Escape');
  await expect(tip).toBeHidden();
  await page.mouse.move(0, 0);
  await trigger.hover();
  await expect(tip).toBeVisible();
  await page.mouse.move(0, 0);
  await expect(tip).toBeHidden();
});

The first test assumes this fixture's link is the first Tab stop. On a real page, follow the route's actual keyboard sequence rather than adding positive tabindex values to satisfy the test. Keep these checks in your website regression testing suite.

These assertions check transitions and the computed description. They do not establish screen-reader speech, enough reading time in every implementation, unobscured placement, or correct touch behavior. Manually pause over the text, move diagonally across its edges, zoom the page, and test near the bottom and right of the viewport. Use a screen reader to check that the control's name and description make sense without repeated or missing information.

Check the public page with Slop Audit

After testing the tooltip itself, run Slop Audit on the public page. Its bounded Browser Run collects axe accessibility findings, sampled hover and focus style evidence, keyboard traversal, and mobile and desktop screenshots when browser coverage completes. Use that report to find surrounding label, focus, contrast, and layout issues before sharing the release.

Slop Audit does not run the tooltip state machine above, verify Escape suppression, or certify WCAG conformance. Read any skipped coverage, repair the observed findings, and rescan after deployment. Pair the report with the focused tests and a manual keyboard accessibility pass for the tooltip's actual interaction.