Sub topic 2
Light dismiss for HTML popovers
Assume you know basic HTML, CSS selectors, and JavaScript event listeners. This chapter focuses on dismissal, styling, and state changes.
Clicking outside and pressing Escape
A popover with popover="auto" supports light dismiss. The browser closes it when the user clicks outside it or presses Escape. Auto popovers also participate in the browser's popover stack, so opening another auto popover can close the current one.
Use popover="manual" when the popover must stay open until code or an explicit control closes it. Manual popovers do not close from outside clicks or Escape.
<button popovertarget="help">Show help</button>
<div id="help" popover="auto">
<p>Choose a date before continuing.</p>
<button popovertarget="help" popovertargetaction="hide">
Close
</button>
</div>Styling the open popover and backdrop
The :popover-open pseudo-class matches only while the popover is visible. The ::backdrop pseudo-element styles the layer behind the popover in the top layer.
[popover] {
border: 1px solid #888;
border-radius: 0.5rem;
padding: 1rem;
}
[popover]:popover-open {
background: white;
}
[popover]::backdrop {
background: rgb(0 0 0 / 20%);
}A popover is non-modal even when its backdrop is styled. The page behind it remains available to the user.
Controlling a popover from JavaScript
Use showPopover(), hidePopover(), and togglePopover() when application logic must control the state.
const panel = document.querySelector("#panel");
panel.showPopover();
panel.hidePopover();
panel.togglePopover();These methods require the element to have the popover attribute. Prefer invoker buttons for ordinary controls because they provide the browser's built-in dismissal and interaction behavior.
Reacting to state changes
beforetoggle fires before the state changes. toggle fires after it changes. Both events provide oldState and newState, whose values are "open" or "closed".
panel.addEventListener("beforetoggle", (event) => {
if (event.newState === "open") {
console.log("Opening the panel");
}
});
panel.addEventListener("toggle", (event) => {
console.log(`${event.oldState} -> ${event.newState}`);
});Exercise
Which popover type should you choose when Escape and outside clicks must close the popover?
Show answer
Use popover="auto".