Sub topic 8
Reacting to beforetoggle and toggle events
This chapter assumes you can add event listeners in JavaScript and that you know how a popover opens and closes through popovertarget, light dismiss, and the showPopover() family of methods. Here you learn how to run code at the moment a popover changes state, whatever caused the change.
Why events instead of click handlers
A popover can open or close in several ways:
- An invoker button.
- A call to
showPopover(),hidePopover(), ortogglePopover(). - Light dismiss.
- The Escape key.
- Another popover opening.
A click handler on your button sees only the first of these. Listening on the popover itself catches all of them.
The two events
The browser fires two events on the popover element, in this order:
beforetogglefires before the state changes. The popover has not yet opened or closed.togglefires after the state has changed.
Both are ToggleEvent objects with two properties, oldState and newState. Each is the string "open" or "closed".
A working example
<button id="open-btn">Toggle panel</button>
<div id="panel" popover>
<p>Panel content</p>
</div>
<script>
const panel = document.getElementById('panel');
panel.addEventListener('beforetoggle', (event) => {
if (event.newState === 'open') {
console.log('about to open');
}
});
panel.addEventListener('toggle', (event) => {
console.log(`${event.oldState} -> ${event.newState}`);
});
document.getElementById('open-btn').addEventListener('click', () => {
panel.togglePopover();
});
</script>Open the panel, then press Escape. The console shows about to open, then closed -> open, then open -> closed. The Escape close was logged even though no code of yours ran on that key press.
Choosing between the two events
Use beforetoggle when the work must happen before the popover is visible or hidden. Use toggle when the popover is already in its new state.
| Task | Event |
|---|---|
| Fill the popover with fresh content before it shows | `beforetoggle` |
| Prevent the popover from opening | `beforetoggle` |
| Update the invoker's `aria-expanded` or label | `toggle` |
| Move focus to an element inside the open popover | `toggle` |
| Stop a timer or polling when the popover closes | `toggle` |
You can cancel the open with event.preventDefault() in beforetoggle:
panel.addEventListener('beforetoggle', (event) => {
if (event.newState === 'open' && !userIsSignedIn()) {
event.preventDefault();
}
});
function userIsSignedIn() {
return document.cookie.includes('session=');
}Only the opening beforetoggle is cancelable. A closing one is not, so a popover cannot refuse to close.
Common errors
- Listening on the button. The events fire on the popover element, not on the invoker. A listener on the button never receives them.
- Expecting bubbling. Toggle events do not bubble. Attach the listener to each popover directly, or use a capturing listener on a parent.
- Ignoring the state. Each event fires for both opening and closing. Without checking
newState, your open-only code also runs on close. - Cancelling a close. Calling
preventDefault()whennewStateis"closed"has no effect. - Slow work in
toggle. The event fires after the change is painted or about to be painted. Anything that should be ready on the first frame belongs inbeforetoggle.
Exercise
A popover has a "Refresh" feature that should load new data each time the popover opens, including when it is opened by an invoker button, by showPopover(), or by another script. Which event and which check would you use, and why not a click handler?
Show answer
Add a beforetoggle listener on the popover and run the loading code when event.newState === 'open'. The event fires for every way of opening, while a click handler on one button misses opens triggered by scripts or other invokers. The newState check keeps the code from running on close.