HTMLElement: toggle event
Baseline 2024
Newly available
Since April 2024, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.
The toggle
event of the HTMLElement
interface fires on a popover element (i.e. one that has a valid popover
attribute) just after it is shown or hidden.
- If the popover element is transitioning from hidden to showing, the
event.oldState
property will be set toclosed
and theevent.newState
property will be set toopen
. - If the popover element is transitioning from showing to hidden, then
event.oldState
will beopen
andevent.newState
will beclosed
.
Syntax
Use the event name in methods like addEventListener()
, or set an event handler property.
js
addEventListener("toggle", (event) => {});
ontoggle = (event) => {};
Event type
A ToggleEvent
. Inherits from Event
.
Examples
Basic example
js
const popover = document.getElementById("mypopover");
// ...
popover.addEventListener("toggle", (event) => {
if (event.newState === "open") {
console.log("Popover has been shown");
} else {
console.log("Popover has been hidden");
}
});
A note on toggle event coalescing
It is worth pointing out that toggle
events are coalesced, meaning that if multiple toggle
events are fired before the event loop has a chance to cycle, only a single event will be fired.
For example:
js
popover.addEventListener("toggle", () => {
//...
});
popover.showPopover();
popover.hidePopover();
// `toggle` only fires once
Specifications
Specification |
---|
HTML Standard # event-toggle |
Browser compatibility
BCD tables only load in the browser
See also
popover
HTML global attribute- Popover API
- Related event:
beforetoggle