tezvyn:

The Popover API: Native Tooltips and Menus

AI-drafted, machine-checkedSource: html.spec.whatwg.orgintermediate

The Popover API creates tooltips and menus with just HTML, placing them in a top layer above all other content without `z-index` hacks. Use it for action menus or notifications.

WHY IT EXISTS: Before the Popover API, creating elements like tooltips or custom menus required significant JavaScript for state management and CSS wizardry with position and z-index to ensure they appeared on top of other content. This was brittle and often had accessibility issues. The Popover API standardizes this common UI pattern directly in the browser.

THE MENTAL MODEL: Think of the popover attribute as giving an element a 'get out of the document flow free' card. When triggered, the element is teleported to a special 'top layer' that always renders above everything else on the page, regardless of z-index or parent stacking contexts. It handles the showing, hiding, and (in most cases) dismissal logic that you used to write yourself.

HOW IT WORKS: You add the popover attribute to any element you want to hide by default, giving it an id. A trigger element, like a <button>, uses the popovertarget attribute with that id to control it. Clicking the button toggles the popover's visibility. The popover attribute has three modes: auto (the default) provides light dismiss, closing when you click outside or press Escape; manual requires explicit JavaScript calls to showPopover() and hidePopover(); and hint is for non-essential popovers like tooltips.

WHEN TO USE IT: Use the Popover API for transient UI elements that shouldn't disrupt the main page flow. Good examples include: action menus attached to a button, custom 'select' component dropdowns, teaching UI tooltips, or temporary confirmation messages after a user action. It's perfect for things that need to appear on top of everything and be easily dismissed.

WHEN NOT TO USE IT: Do not use popovers for modal dialogs that require the user to make a choice before interacting with the rest of the page. The Popover API does not trap focus. For that, use the native <dialog> element with its showModal() method. Also, avoid it for content that should always be part of the document flow, like an accordion panel.

ONE CANONICAL EXAMPLE: To create a simple action menu, you define a button to trigger it and a list to be the popover content. <button popovertarget="actions-menu">Actions</button>

<button role="menuitem">Edit</button> <button role="menuitem">Delete</button>

Clicking the button shows the menu. Clicking away from it automatically hides it. Notice the ARIA roles are still necessary for screen readers to understand it's a menu.

Read the original → html.spec.whatwg.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.