Sub topic 8
Reacting to beforetoggle and toggle events
This chapter assumes you can open and close a popover with popovertarget or showPopover(), and that you can attach event listeners in JavaScript. Popover types and light dismiss are covered in earlier chapters. Here you will learn how to run code when a popover changes state, and how to stop it from opening.
Two events, two moments
A popover reports state changes through two events. Both are ToggleEvent objects, and both carry two properties:
oldStateis the state before the change, either"closed"or"open".newStateis the state after the change, using the same two values.
The events differ in when they fire and what you can do with them.
| Property | `beforetoggle` | `toggle` |
|---|---|---|
| When it fires | Just before the state changes | After the state has changed |
| Timing | Synchronous, inside the call that caused the change | Queued, runs as a later task |
| Cancelable | Yes, but only when `newState` is `"open"` | No |
| Typical use | Prepare content, veto an opening | Update the page after the fact |
| Bubbles | No | No |
Neither event bubbles. A listener must sit on the popover itself, or you must listen in the capture phase on an ancestor. Capture still works for events that do not bubble, which is how you handle many popovers with one listener.
Listening to both events
The example below logs each event. The toggle listener uses the same properties as beforetoggle.
<button popovertarget="panel">Toggle panel</button>
<div id="panel" popover>
<p>Panel content</p>
</div>
<script>
const panel = document.getElementById('panel');
panel.addEventListener('beforetoggle', (event) => {
console.log(`beforetoggle: ${event.oldState} -> ${event.newState}`);
});
panel.addEventListener('toggle', (event) => {
console.log(`toggle: ${event.oldState} -> ${event.newState}`);
});
</script>Open the panel and the console shows beforetoggle: closed -> open, then toggle: closed -> open. The events fire the same way whatever caused the change: the invoker button, showPopover(), light dismiss, the Escape key, or another popover opening and closing this one.
Using beforetoggle to prepare content
Because beforetoggle fires before the popover is shown, you can fill it with content first. This avoids a visible flash of stale content. At this point the popover is still display: none when opening, so do not measure its size here. Layout information is not available yet.
<button popovertarget="clock">What time is it?</button>
<div id="clock" popover>
<p>Opened at: <span id="clock-time"></span></p>
</div>
<script>
const clock = document.getElementById('clock');
const clockTime = document.getElementById('clock-time');
clock.addEventListener('beforetoggle', (event) => {
if (event.newState === 'open') {
clockTime.textContent = new Date().toLocaleTimeString();
}
});
</script>Always test newState. The same listener also runs when the popover closes, and you usually want different work for each direction.
The same pattern works for loading remote content. Start the fetch in beforetoggle when newState is "open", show a "Loading..." placeholder, and replace it when the response arrives. Guard it with a flag so a second opening does not fetch again.
Cancelling an opening
For an opening, beforetoggle is cancelable. Calling event.preventDefault() keeps the popover closed. This is useful when some condition makes opening wrong.
<button popovertarget="share">Share</button>
<div id="share" popover>
<p>Choose how to share this page.</p>
</div>
<script>
const share = document.getElementById('share');
share.addEventListener('beforetoggle', (event) => {
if (event.newState === 'open' && !navigator.onLine) {
event.preventDefault();
alert('You are offline. Sharing is unavailable.');
}
});
</script>Closing cannot be cancelled. If you call preventDefault() when newState is "closed", nothing happens. This is deliberate: a user must always be able to dismiss an overlay, so the browser does not let a script trap them in it.
Two cases to know about:
- If the cancelled opening came from
showPopover(), the call returns normally and the popover stays closed. Checkmatches(':popover-open')afterwards if your code depends on the result. - If another auto popover was about to be closed to make room for this one, check what actually happened before you rely on it. Do not assume the other popover closed.
Using toggle to react after the fact
Use toggle when you only need to respond to the result. It fires after the change, so the popover is rendered. You can measure it, move focus, or update other parts of the page.
const menu = document.getElementById('menu');
const status = document.getElementById('status');
menu.addEventListener('toggle', (event) => {
if (event.newState === 'open') {
status.textContent = 'Menu is open';
menu.querySelector('a, button')?.focus();
} else {
status.textContent = 'Menu is closed';
}
});This works with a page that has <div id="menu" popover> and a status element with id="status".
A note on focus. Popovers already manage focus in many cases: the browser moves focus to an element with the autofocus attribute inside the popover, and returns it to the invoker when an auto popover closes. Move focus yourself only when the default does not fit.
You do not need to set aria-expanded on invoker buttons. Browsers expose the expanded state of a popovertarget button on their own.
Toggle events are coalesced
beforetoggle fires once for every change, immediately. toggle is queued as a task, and the specification coalesces pending toggle events for one element. If a popover changes state several times before the queued task runs, you get a single toggle event. Its oldState comes from the first change, and its newState reflects the latest state.
Two consequences follow:
- Do not count
toggleevents to count how often a popover changed. Usebeforetogglefor that. - Do not assume
oldStateandnewStatediffer. If the popover ends up where it started, compare the two values before acting.
Handling many popovers with one listener
Since the events do not bubble, a listener on document only sees them if you register it with capture:
document.addEventListener(
'toggle',
(event) => {
const target = event.target;
if (!(target instanceof HTMLElement) || !target.hasAttribute('popover')) {
return;
}
target.dataset.state = event.newState;
},
true
);The third argument, true, enables the capture phase. Each popover now carries a data-state attribute you can use in CSS or in tests. Without true, this listener never runs.
The toggle event also fires on other elements. <details> fires toggle when it opens or closes, and newer browsers also fire both events on <dialog>. The hasAttribute('popover') check keeps the handler from reacting to those.
Events during stacking
Opening an auto popover closes other open auto popovers that are not its ancestors. Each popover that closes fires its own beforetoggle and toggle. If popover A is open and the user opens unrelated popover B, you see these events in order:
beforetoggleon A,opentoclosedbeforetoggleon B,closedtoopentoggleon A, thentoggleon B (queued, so they fire after both changes)
Treat each popover's events independently, and never assume that one popover's toggle arrives before another's beforetoggle.
Common mistakes
- Doing layout work in
beforetoggle. The element is not rendered yet when opening. Usetogglefor measuring. - Forgetting to test
newState. Handlers run on both opening and closing. - Expecting to cancel a close. Only an opening can be cancelled.
- Listening on a parent without capture. The events do not bubble.
- Treating
toggleas synchronous. Code right aftershowPopover()runs before thetoggleevent does.
Exercise
A popover's listener for beforetoggle calls event.preventDefault() unconditionally. A user clicks the invoker button while the popover is closed, then clicks it again while it is open. What happens each time, and why?
Show answer
The first click is cancelled, so the popover never opens. The popover is therefore never open for the second click. If it were open (for example, opened earlier by a different code path), the second click would still close it, because beforetoggle is cancelable only when newState is "open". Calling preventDefault() on a closing event has no effect. To make the listener correct, check event.newState === 'open' before calling it.
Exercise
You want one script to add the class is-open to whichever popover is currently showing, for any number of popovers on the page. Which event and listener setup do you use, and why is a plain document.addEventListener('toggle', handler) not enough?
Show answer
Use the toggle event with a listener on document registered with the capture flag set to true, document.addEventListener('toggle', handler, true). Toggle events do not bubble, so a listener without capture never receives events fired on the popovers. In the handler, read event.target and event.newState, and add or remove is-open depending on whether newState is "open". Confirm the target has a popover attribute, since <details> and <dialog> fire similar events.