Sub topic 7
Controlling popovers from JavaScript
The popover attribute works without any script, but some behavior needs code. You may want to open a popover after a timer, from a keyboard shortcut, or after a network request finishes. The HTML popover API gives you three methods for this, plus a few properties and a way to check state.
This chapter assumes you know how to add the popover attribute and wire a button with popovertarget. It also assumes you can select elements and add event listeners in JavaScript.
The three methods
Every HTML element has these methods. They only do something useful on an element that has a popover attribute.
| Method | What it does |
|---|---|
| `showPopover()` | Opens the popover. |
| `hidePopover()` | Closes the popover. |
| `togglePopover()` | Opens it if closed, closes it if open. |
These methods match the three values of popovertargetaction: show, hide, and toggle. A button with popovertarget is a declarative form of the same calls.
Here is a complete example. A manual popover is opened from script, and the Dismiss button closes it without script.
<div id="notice" popover="manual">
<p>Your changes were saved.</p>
<button popovertarget="notice" popovertargetaction="hide">Dismiss</button>
</div>
<script>
const notice = document.getElementById('notice');
notice.showPopover();
</script>The script runs once, when the page loads, and the notice appears at once. Because the popover is manual, clicking elsewhere or pressing Escape does not close it. Only the button or a call to hidePopover() does.
Return values and the toggle `force` option
showPopover() and hidePopover() return nothing. togglePopover() returns a boolean that is true if the popover is open after the call and false if it is closed. You can use that value to update other parts of the page, such as a button label.
togglePopover() also accepts a force argument. Passing true behaves like showPopover() when the popover is closed and does nothing when it is already open. Passing false closes it only if it is open.
const menu = document.getElementById('menu');
// Open the menu only if it is not open already, without throwing.
const isOpen = menu.togglePopover(true);
console.log(isOpen); // true
// Close it only if it is open.
menu.togglePopover(false);Using force is safer than calling showPopover() when you are not sure of the current state. The next sections explain why.
When these methods throw errors
The methods are strict. They throw a DOMException when you call them in a state that does not make sense.
InvalidStateErroris thrown if the element has nopopoverattribute, or if it is not connected to the document.NotSupportedErroris thrown if the element is not an HTML element, such as an SVG element.showPopover()on a popover that is already open throwsInvalidStateErrorin current specifications. Older browser versions did nothing in this case. Do not rely on either behavior.hidePopover()on a popover that is already closed is quiet and does nothing in current browsers, but you should still guard it in code that must work in older versions.
The safest approach is to check the state before you call a method, or to use togglePopover(force).
function openIfClosed(el) {
if (!el.matches(':popover-open')) {
el.showPopover();
}
}Checking whether a popover is open
There is no isOpen property on a popover. Instead, use the :popover-open pseudo-class with matches().
const panel = document.getElementById('panel');
if (panel.matches(':popover-open')) {
console.log('The panel is showing');
} else {
console.log('The panel is hidden');
}This is the same pseudo-class you use in CSS. It matches only while the popover is showing in the top layer.
The `popover` property
The popover attribute is also exposed as a property, element.popover. Its value is one of three strings or null.
| Value | Meaning |
|---|---|
| `"auto"` | An auto popover. An empty attribute, `popover=""`, also reads as `"auto"`. |
| `"manual"` | A manual popover. |
| `null` | The element is not a popover. |
You can set the property to change the type, or set it to null to remove the popover behavior entirely. Setting it to an invalid string makes it "manual", so check your values.
const box = document.getElementById('box');
console.log(box.popover); // "auto"
box.popover = 'manual';
console.log(box.popover); // "manual"If you change the type of a popover that is open, the browser closes it first. Plan for that if you switch types in response to user actions.
Reading the invoker from script
The popoverTargetElement property on a button lets you connect a button and a popover in script. Use it when the popover is not in the same tree as the button, for example when they live in different shadow roots, where an id lookup would fail.
const button = document.getElementById('open-btn');
const panel = document.getElementById('panel');
button.popoverTargetElement = panel;
button.popoverTargetAction = 'toggle';This is the property form of popovertarget and popovertargetaction. After this code runs, clicking the button toggles the panel with no click handler of your own.
The `source` option
Newer versions of the specification let showPopover() and togglePopover() take an options object with a source property. It names the element that invoked the popover, which affects how the browser handles focus return and anchor relationships. Support is still arriving, so treat it as an optional extra and test it in your target browsers. Do not depend on it for core behavior.
Controlling popovers from event handlers
A common pattern is to open a popover from a click handler that does more than show it. For example, you may need to load data first.
const details = document.getElementById('details');
const loadBtn = document.getElementById('load-btn');
loadBtn.addEventListener('click', async () => {
const response = await fetch('/api/details');
const text = await response.text();
details.querySelector('p').textContent = text;
details.showPopover();
});If you use popovertarget and a click handler on the same button, both run. The popover opens through the attribute, and your handler runs as well. That is fine for logging, but if your handler also calls togglePopover(), the two toggles cancel each other out and the popover appears not to open. Use one mechanism per button.
Light dismiss and script
An auto popover can close by itself when the user clicks outside it or presses Escape. When you open an auto popover from script, light dismiss still applies. Two problems follow from this.
First, a click on the button that opened the popover can be seen as an outside click if the button is not linked to the popover with popovertarget. The popover closes on pointer down and your click handler reopens it, so it flickers. Linking the button with popoverTargetElement, as above, avoids that, because the browser then treats the button as part of the popover.
Second, if you open one auto popover while another unrelated auto popover is open, the first one closes. If you need two independent overlays to stay open together, make them manual.
Popover state transitions as a diagram
The methods and the user's actions both move a popover between two states.
A worked example: a keyboard shortcut
This page opens a help popover when the user presses ?. It uses togglePopover() so the same key also closes it, and it ignores the key when the user is typing in a field.
<button popovertarget="help">Show help</button>
<div id="help" popover>
<p>Press ? to open or close this help. Press Escape to close it.</p>
</div>
<script>
const help = document.getElementById('help');
document.addEventListener('keydown', (event) => {
const target = event.target;
const typing =
target instanceof HTMLElement &&
(target.isContentEditable || target.matches('input, textarea, select'));
if (event.key === '?' && !typing) {
event.preventDefault();
help.togglePopover();
}
});
</script>Check what happens in each case. Pressing ? on the page opens the popover. Pressing it again closes it. Pressing it inside a text field types the character and leaves the popover alone. Escape closes the popover without any code, because it is an auto popover.
Common mistakes
- Calling
showPopover()on an element with nopopoverattribute. This throwsInvalidStateError. - Calling it before the element is in the document, for instance on an element created with
createElementthat you have not yet appended. - Using both
popovertargetand atogglePopover()call on one button, so the two cancel out. - Testing for openness with a custom flag that drifts from the real state. Use
:popover-open. - Expecting an auto popover to stay open when another auto popover opens. Use
manualfor that.
Summary
showPopover(),hidePopover(), andtogglePopover()control any element with apopoverattribute.togglePopover(force)returns the new state and is the safest call when state is uncertain.- Check state with
element.matches(':popover-open'). element.popoverreads and sets the type, andpopoverTargetElementlinks a button and a popover in script.- Do not mix a
popovertargetbutton with a toggle call on the same button.
Exercise
A button has popovertarget="tip" and also a click handler that calls document.getElementById('tip').togglePopover(). Clicking the button seems to do nothing. Why, and how do you fix it?
Show answer
Both mechanisms toggle the popover on the same click. The first opens it and the second closes it again, so it looks as if nothing happened. Fix it by using only one: remove the click handler and keep popovertarget, or remove popovertarget and keep the handler. If the handler must run extra code, call showPopover() or togglePopover(true) there and remove popovertarget.
Exercise
Write a function closeAll(popovers) that takes a list of elements and closes only those that are currently open, without throwing an error.
Show answer
``javascript is not needed here. Use this code: function closeAll(popovers) { for (const el of popovers) { if (el.matches(':popover-open')) { el.hidePopover(); } } }. Checking :popover-open first means hidePopover()` runs only on popovers that are showing.