Open UIOpen UI

Popup API (Explainer)

Table of Contents

Background

A very common UI pattern on the Web, for which there is no native API, is "popup UI" or "popups". Popups are a general class of UI that have three common behaviors:

  1. Popups always appear on top of other page content.
  2. Popups are ephemeral. When the user "moves on" to another part of the page (e.g. by clicking elsewhere, or hitting ESC), the popup closes.
  3. Popups (of a particular type) are generally "one at a time" - opening one popup closes others.

This document proposes a set of APIs to make this type of UI easy to build.

Goals

Here are the goals for this API:

  • Allow any element and its (arbitrary) descendants to be rendered on top of all other content in the host web application.
  • Include “light dismiss” management functionality, to remove the element/descendants from the top-layer upon certain actions such as hitting Esc (or any close signal) or clicking outside the element bounds.
  • Allow this “top layer” content to be fully styled, including properties which require compositing with other layers of the host web application (e.g. the box-shadow or backdrop-filter CSS properties).
  • Allow these top layer elements to reside at semantically-relevant positions in the DOM. I.e. it should not be required to re-parent a top layer element as the last child of the document.body simply to escape ancestor containment and transforms.
  • Allow this “top layer” content to be sized and positioned to the author's discretion.
  • Include an appropriate user input and focus management experience, with flexibility to modify behaviors such as initial focus.
  • Accessible by default, with the ability to further extend semantics/behaviors as needed for the author's specific use case.
  • Avoid developer footguns, such as improper stacking of dialogs and popups, and incorrect accessibility mappings.
  • Avoid the need for Javascript for the common cases.

See Also

See the original <popup> element explainer, and also the comments on Issue 410 and Issue 417. See also this CSSWG discussion which has mostly been about a CSS alternative for top layer.

This proposal was discussed on Issue 455, which was closed as resolved.

API Shape

This section lays out the full details of this proposal. If you'd prefer, you can skip to the examples section to see the code.

HTML Content Attribute

A new content attribute, popup, controls both the top layer status and the dismiss behavior. There are several allowed values for this attribute:

  • popup=popup - A top layer element following “Popup” dismiss behaviors (see below).
  • popup=hint - A top layer element following “Hint” dismiss behaviors (see below).
  • popup=async - A top layer element following “Async” dismiss behaviors (see below).

So this markup represents popup content:

<div popup=popup>I am a popup</div>

As written above, the <div> will be rendered display:none by the UA stylesheet, meaning it will not be shown when the page is loaded. To show the popup, one of several methods can be used: declarative triggering, Javascript triggering, or page load triggering.

Showing and Hiding a Popup

There are several ways to "show" a popup, and they are discussed in this section. When any of these methods are used to show a popup, it will be made visible and moved (by the UA) to the top layer. The top layer is a layer that paints on top of all other page content, with the exception of other elements currently in the top layer. This allows, for example, a "stack" of popups to exist.

Declarative Triggers

A common design pattern is to have an activating element, such as a <button>, which makes a popup visible. To facilitate this pattern, and avoid the need for Javascript in this common case, three content attribute (togglepopup, showpopup, and hidepopup) allow the developer to declaratively toggle, show, or hide a popup. To do so, the attribute's value should be set to the idref of another element:

<button togglepopup=foo>Toggle the popup</button>
<div id=foo popup=popup>Popup content</div>

When the button in this example is activated, the UA will call .showPopup() on the <div id=mypopup> element if it is currently hidden, or hidePopup() if it is showing. In this way, no Javascript will be necessary for this use case.

If the desire is to have a button that only shows or only hides a popup, the following markup can be used:

<button togglepopup=foo>Toggle the popup</button>
<button showpopup=foo>This button only shows the popup</button>
<button hidepopup=foo>This button only hides the popup</button>
<div id=foo popup=popup>Popup content</div>

Note that all three attributes can be used together like this, pointing to the same element. However, using more than one triggering attribute on a single button is not recommended.

When the togglepopup, showpopup, or hidepopup attributes are applied to an activating element, the UA may automatically map this attribute appropriate aria-* attributes, such as aria-haspopup, aria-describedby and/or aria-expanded, in order to ensure accessibility. There will need to be further discussion with the ARIA working group to determine the exact ARIA semantics, if any, are necessary.

Javascript Trigger

To show and hide the popup via Javascript, there are two methods on HTMLElement:

const popup = document.querySelector('[popup]');
popup.showPopup(); // Show the popup
popup.hidePopup(); // Hide a visible popup

Calling showPopup() on an element that has a valid value for the popup attribute will cause the UA to remove the display:none rule from the element and move it to the top layer. Calling hidePopup() on a showing popup will remove it from the top layer, and re-apply display:none.

There are several conditions that will cause showPopup() and/or hidePopup() to throw an exception:

  1. Calling showPopup() or hidePopup() on an element that does not contain a valid value of the popup attribute. This will throw a NotSupportedError DOMException.
  2. Calling showPopup() on a valid popup that is already in the showing state. This will throw an InvalidStateError DOMException.
  3. Calling showPopup() on a valid popup that is not connected to a document. This will throw an InvalidStateError DOMException.
  4. Calling hidePopup() on a valid popup that is not currently showing. This will throw an InvalidStateError DOMException.

Page Load Trigger

As mentioned above, a <div popup=popup> will be hidden by default. If it is desired that the popup should be shown automatically upon page load, the defaultopen attribute can be applied:

<div popup=popup defaultopen>

In this case, the UA will immediately call showPopup() on the element, as it is parsed. If multiple such elements exist on the page, only the first such element (in DOM order) on the page will be shown.

Note that hint popups cannot use the defaultopen attribute:

<div popup=hint defaultopen>I will not be shown on page load</div>

Note also that more than one async popup can use defaultopen and all such popups will be shown on load, not just the first one:

<div popup=async defaultopen>Shown on page load</div>
<div popup=async defaultopen>Also shown on page load</div>

Shown vs Hidden Popups

The styling for a popup is provided by roughly the following UA stylesheet rules:

[popup i]:not(:popup-open) {
display: none;
}
[popup i] {
position: fixed;
}

The above rules mean that a popup, when not "shown", has display:none applied, and that style is removed when one of the methods above is used to show the popup. Note that the display:none UA stylesheet rule is not !important. In other words, developer style rules can be used to override this UA style to make a not-showing popup visible in the page. In this case, the popup will not be displayed in the top layer, but rather at it's ordinary z-index position within the document. This can be used, for example, to animate the show/hide behavior of the popup, or make popup content "return to the page" instead of becoming hidden.

IDL Attribute and Feature Detection

The popup content attribute will be reflected as an IDL attribute:

[Exposed=Window]
partial interface Element {
attribute DOMString popup;

This not only allows developer ease-of-use from Javascript, but also allows for a feature detection mechanism:

function supportsPopup() {
return Element.prototype.hasOwnProperty("popup");
}

Further, only valid values of the content attribute will be reflected to the IDL property, with invalid values being reflected as the empty string "". For example:

const div = document.createElement('div');
div.setAttribute('popup','hint');
div.popup === 'hint'; // true
div.setAttribute('popup','invalid!');
div.popup === ''; // true

Events

Events are fired (asynchronously) when a popup is shown (show event) and hidden (hide event). These events can be used, for example, to populate content for the popup just in time before it is shown, or update server data when it closes. The events are:

const popup = Object.assign(document.createElement('div'), {popup: 'popup'});
popup.addEventListener('show',() => console.log('Popup is being shown!'));
popup.addEventListener('hide',() => console.log('Popup is being hidden!'));

Neither of these events are cancellable, and both are fired asynchronously.

Focus Management

Elements that move into the top layer may require focus to be moved to that element, or a descendant element. However, not all elements in the top layer will require focus. For example, a modal <dialog> will have focus set to its first interactive element, if not the dialog element itself, because a modal dialog is something that requires immediate attention. On the other hand, a <div popup=hint> (which will more often than not represent a "tooltip") does not receive focus at all (nor is it expected to contain focusable elements). Similarly, a <div popup=async> should not immediately receive focus (even if it contains focusable elements) because it is meant for out-of-band communication of state, and is not meant to interrupt a user's current action. Additionally, if the top layer element should receive immediate focus, there is a question about which part of the element gets that initial focus. For example, the element itself could receive focus, or one of its focusable descendants could receive focus. To provide control over these behaviors, two attributes can be used on popups:

  • autofocus. When present on a popup or one of its descendants, it will result in focus being moved to the specified element when the popup is rendered. Note that autofocus is already a global attribute, but the existing behavior applies to element focus on page load. This proposal extends that definition to be used within popups, and the focus behavior happens when they are shown. Note that adding autofocus to a popup descendant does not cause the popup to be shown on page load, and therefore it does not cause focus to be moved into the popup on page load, unless the defaultopen attribute is also used.

  • delegatesfocus. When present on the popup element itself, this causes the first focusable descendent of the popup to be focused when the popup is shown. The purpose of this attribute is to handle the cases in which the popup content or ordering is not known prior to rendering, so that autofocus cannot be used effectively. (Eventually, the delegatesfocus attribute might be made applicable to any element, not just popups, to control focus behavior more generally.)

If both autofocus and delegatesfocus are both present on the popup element, the popup element is focused when shown.

Anchoring

A new attribute, anchor, can be used on a popup element to refer to the popup's "anchor". The value of the attribute is a string idref corresponding to the id of another element (the "anchor element"). This anchoring relationship is used for two things:

  1. Establish the provided anchor element as an “ancestor” of this popup, for light-dismiss behaviors. In other words, the anchor attribute can be used to form nested popups.
  2. The referenced anchor element could be used by the Anchor Positioning feature.

Backdrop

Akin to modal <dialog> and fullscreen elements, popups allow access to a ::backdrop pseudo element, which is a full-screen element placed directly behind the popup in the top layer. This allows the developer to do things like blur out the background when a popup is showing:

<div popup=popup>I'm a popup</div>
<style>
[popup]::backdrop {
backdrop-filter: blur(3px);
}
</style>

Note that in contrast to the ::backdrop pseudo element for modal dialogs and fullscreen elements, the ::backdrop for a popup is styled by a UA stylesheet rule pointer-events: none !important, which means it cannot trap clicks outside the popup. This ensures the "click outside" light dismiss behavior continues to function.

Behaviors

Automatic Dismiss Behavior

For elements that are displayed on the top layer via this API, there are a number of things that can cause the element to be removed from the top-layer, besides the ones described above. These fall into three main categories:

  • One at a Time. Another element being added to the top-layer causes existing top layer elements to be removed. This is typically used for “one at a time” type elements: when one popup is shown, other popups should be hidden, so that only one is on-screen at a time. This is also used when “more important” top layer elements get added. For example, fullscreen elements should close all open popups.
  • Light Dismiss. User action such as clicking outside the element, hitting Escape, or causing keyboard focus to leave the element should all cause a displayed popup to be hidden. This is typically called “light dismiss”, and is discussed in more detail in this section.
  • Other Reasons. Because the top layer is a UA-managed resource, it may have other reasons (for example a user preference) to forcibly remove elements from the top layer.

In all such cases, the UA is allowed to forcibly remove an element from the top layer and re-apply the display:none popup UA rule. The rules the UA uses to manage these interactions depends on the element types, and this is described in more detail in this section.

Light Dismiss

The term "light dismiss" for a popup is used to describe the user "moving on" to another part of the page, or generally being done interacting with the popup. When this happens, the popup should be hidden. Several actions trigger light dismiss of a popup:

  1. Clicking or tapping outside the bounds of the popup. Any mousedown event will trigger all open popups to be hidden, starting from the top of the popup stack, and ending with the nearest open ancestral popup of the mousedown event's target Node. This means clicking on a popup or its trigger or anchor elements will not hide that popup.
  2. Hitting the Escape key, or generally any "close signal". This will cause the topmost popup on the popup stack to be hidden.
  3. Using keyboard or other navigation sources to move the focus off of the popup. When the focus changes, all popups up to the "nearest open ancestral popup" for the newly-focused element will be hidden. Note that this includes subframes and the user changing windows (a window blur) - both will cause all open popups to be closed.

Nested Popups

For at least popup=popup, it is possible to have "nested" popups. I.e. two popups that are allowed to both be open at the same time, due to their relationship with each other. A simple example where this would be desired is a popup menu that contains sub-menus: it should be possible to keep the main menu showing while the sub-menu is shown.

Popup nesting is not posslbe/applicable to the other popup types, such as popup=hint and popup=async.

The Popup Stack

The Document contains a "stack of open popups", which is initially empty. When a popup=popup element is shown, that popup is pushed onto the top of the stack, and when a popup=popup element is hidden, it is popped from the top of the stack.

Nearest Open Ancestral Popup

The "nearest open ancestral popup" P to a given Node N is defined in this way:

P is the topmost popup in the popup stack for which any one of the following is true:

  1. P is a flat-tree DOM ancestor of N.
  2. P has an anchor attribute whose value is equal to N's id or any of N's flat-tree descendent's ids.*
  3. N has an ancestor triggering element whose target is P. If none of the popups in the popup stack match the above conditions, then P is null.

The above description needs to be more crisply defined. The implementation from Chromium should be a good starting point to describe the algorithm.

Close signal

The "close signal" proposal attempts to unify the concept of "closing" something. Most typically, the Escape key is the standard close signal, but there are others, including the Android back button, Accessibility Tools dismiss gestures, and the Playstation square button. Any of these close signals is a light dismiss trigger for the topmost popup.

The fact that only valid values are reflected allows feature detection of the values, for forward compatibility:

function supportsAsyncPopups() {
if !Element.prototype.hasOwnProperty("popup")
return false;
const div = document.createElement('div');
div.setAttribute('popup','async');
return div.popup === 'async';
}

Classes of Top Layer UI

As described in this section, the three popup types (popup, hint, and async) each have slightly different interactions with each other. For example, popups hide other hints, but the reverse is not true. Additionally, there are other (non-popup) elements that participate in the top layer. This section describes the general interactions between the various top layer element types, including the various flavors of popup:

  • Popup (popup=popup)
    • When opened, force-closes other popups and hints, except for ancestor popups.
    • It would generally be expected that a popup of this type would either receive focus, or a descendant element would receive focus when invoked.
    • Dismisses on close signal, click outside, or blur.
  • Hint/Tooltip (popup=hint)
    • When opened, force-closes only other hints, but leaves all other popup types open.
    • Dismisses on close signal, click outside, when no longer hovered (after a timeout), or when the anchor element loses focus.
  • Async (popup=async)
    • Does not force-close any other element type.
    • Does not light-dismiss - closes via timer or explicit close action.
  • Dialog (<dialog>.showModal())
    • When opened, force-closes popup and hint.
    • Dismisses on close signal
  • Fullscreen (<div>.requestFullscreen())
    • When opened, force-closes popup, hint, and (with spec changes) dialog
    • Dismisses on close signal

One at a time behavior summary

This table summarizes the interactions between a first top layer element (rows) and a second top layer element (columns), as the second element is shown:

Second element
FullscreenModal DialogPopupHintAsync
First ElementFullscreenHideLeaveLeaveLeaveLeave
Modal DialogHide*LeaveLeaveLeaveLeave
PopupHideHideHideLeaveLeave
HintHideHideHideHideLeave
AsyncHideHideLeaveLeaveLeave

*Not current behavior

In the table, "hide" means that when the second element is shown (enters the top layer), the first element is removed from the top layer. In contrast, "leave" means both elements will remain in the top layer together.

Detailed description of interactions among popup types

This section details the interactions between the three popup types:

  1. If a popup=hint is shown, it should hide any other open popup=hints, including ancestral popup=hints. ("You can't nest popup=hints".)
  2. If a popup=popup is shown, it should hide any open popup=hints, including if the popup=hint is an ancestral popup of the popup=popup. ("You can't nest a popup inside a popup=hint".)
  3. If you: a) show a popup=popup (call it D), then b) show an ancestral popup=hint of D (call it T) , then c) hide D, the popup=hint T should be hidden. ("A popup=hint can be nested inside a popup.")
  4. If you: a) show a popup=popup (call it D), then b) show an non-ancestral popup=hint (call it T) , then c) hide D, the popup=hint T should be left showing. ("Non-nested popup=hints can stay open when unrelated popups are hidden.")
  5. The defaultopen attribute should have no effect on popup=hints. I.e. this attribute cannot be used to cause a popup=hint to be shown upon page load.
  6. The defaultopen attribute can be used on as many popup=asyncs as desired, and all of them will be shown upon page load.
  7. Only the first popup=popup (in DOM order) containing the defaultopen attribute will be shown upon page load. (This is per-explainer, and included here for completeness.)

Accessibility / Semantics

Since the popup content attribute can be applied to any element, and this only impacts the element's presentation (top layer vs not top layer), this addition does not have any direct semantic or accessibility impact. The element with the popup attribute will keep its existing semantics and AOM representation. For example, <article popup=popup>...</article> will continue to be exposed as an implicit role=article, but will be able to be displayed on top of other content. Similarly, ARIA can be used to modify accessibility mappings in the normal way, for example <div popup=popup role=note>...</div>.

As mentioned in the Declarative Triggers section, accessibility mappings will be automatically configured to associate the popup with its trigger element, as needed.

Disallowed elements

While the popup API can be used on most elements, there are some limitations. For example, calling showPopup() on a modal (via .showModal()) <dialog> element will result in an exception being thrown, as will calling it on an active fullscreen element. All other element types are valid.

Example Use Cases

This section contains several HTML examples, showing how various UI elements might be constructed using this API.

Note: these examples are for demonstrative purposes of how to use the togglepopup and popup attributes. They may not represent all necessary HTML, ARIA or JavaScript features needed to fully create such components.

Generic Popup (Date Picker)

<button togglepopup=datepicker>Pick a date</button>
<my-date-picker role=dialog id=datepicker popup=popup>
...date picker implementation...
</my-date-picker>
<!-- No script - the togglepopup attribute takes care of activation -->

Generic popup (<selectmenu> listbox example)

<selectmenu>
<template shadowroot=closed>
<button togglepopup=listbox>Icon</button>
<div role=listbox id=listbox popup=popup>
<slot></slot>
</div>
</template>
<option>Option 1</option>
<option>Option 2</option>
</selectmenu>
<!-- No script - the togglepopup attribute takes care of activation -->

Hint/Tooltip

<div id=hint-trigger aria-describedby=hint>
Hover me
</div>
<my-hint id=hint role=tooltip popup=hint anchor=hint-trigger>
Hint text
</my-tooltip>
<script>
const trigger = document.getElementById('hint-trigger');
const hint = document.querySelector('my-hint');
trigger.addEventListener('mouseover',() => {
// This behavior could potentially be built into a new activation
// content attribute, like <div trigger-on-hover=my-hint>.
hint.showPopup();
});
</script>

Async

<div role=alert>
<my-async-container popup=async></my-async-container>
</div>
<script>
window.addEventListener('message',e => {
const container = document.querySelector('my-async-container');
container.appendChild(document.createTextNode('Msg: ' + e.data));
container.showPopup();
});
</script>

Additional Considerations

Exceeding the Frame Bounds

Allowing a popup/top-layer element to exceed the bounds of its containing frame poses a serious security risk: such an element could spoof browser UI or containing-page content. While the original <popup> proposal did not discuss this issue, the <selectmenu> proposal does have a specific section at least mentioning this issue. Some top-layer APIs (e.g. the fullscreen API) make it possible for an element to exceed the frame bounds in some cases, great care must be taken in these cases to ensure user safety. Given the complete flexibility offered by the Popup API (any element, arbitrary content, etc.), there would be no way to ensure the safety of this feature if it were allowed to exceed frame bounds.

For completeness, several use counters were added to Chromium to measure how often this type of behavior (content exceeding the frame bounds) might be needed. These are approximations, as they merely measure the total number of times one of the built-in “popup” windows, which can exceed frame bounds because of their carefully-controlled content, is shown. The popups included in this count include the <select> popup, the <input type=color> color picker, and the <input type=date/etc> date/time picker. Data can be found here:

So about 11% of all popups currently exceed their owner frame bounds. That should be considered a rough upper bound, as it is possible that some of those popups could have fit within their frame if an attempt was made to do so, but they just happened to exceed the bounds anyway.

In any case, it is important to note that this API cannot be used to render content outside the containing frame.

Shadow DOM

Note that using the API described in this explainer, it is possible for elements contained within a shadow root to be popups. For example, it is possible to construct a custom element that wraps a popup type UI element, such as a <my-tooltip>, with this DOM structure:

<my-tooltip>
<template shadowroot=closed>
<div popup=hint>This is a tooltip: <slot></slot></div>
</template>
Tooltip text here!
</my-tooltip>

In this case, the (closed) shadow root contains a <div> that has popup=hint and that element will be shown on the top layer when the custom element calls div.showPopup().

This is "normal", and the only point of this section is to point out that even shadow dom children can be promoted to the top layer, in the same way that a shadow root can contain a <dialog> that can be showModal()'d, or a <div> that can be requestFullscreen()'d.

Eventual Single-Purpose Elements

There might come a time, sooner or later, where a new popup-type HTML element is desired which combines strong semantics and purpose-built behaviors. For example, a <tooltip> or <listbox> element. Those elements could be relatively easily built via the APIs proposed in this document. For example, a <tooltip> element could be defined to have role=tooltip and popup=hint, and therefore re-use this Popup API for always-on-top rendering, one-at-a-time management, and light dismiss. In other words, these new elements could be explained in terms of the lower-level primitives being proposed for this API.

The Choices Made in this API

Many decisions and choices were made in the design of this API, and those decisions were made via numerous discussions (live and on issues) in OpenUI, a WHATWG Community Group.

Alternatives Considered

To achieve the goals of this project, a number of approaches could have been used:

  • An HTML content attribute (this proposal).
  • A dedicated <popup> element.
  • A CSS property.
  • A Javascript API.

Each of these options is significantly different from the others. To properly evaluate them, each option was fleshed out in some detail. Please see this document for the details of that effort:

That document discusses the pros and cons for each alternative. After exploring these options, the HTML content attribute approach was resolved by OpenUI to be the best overall.

Design decisions

Many small (and large!) behavior questions were answered via discussions at OpenUI. This section contains links to some of those: