HTMLElement: beforetoggle event
Experimental: This is an experimental technology
Check the Browser compatibility table carefully before using this in production.
The beforetoggle
event of the HTMLElement
interface fires on a popover element (i.e. one that has a valid popover
attribute) just before it is shown or hidden.
- If the popover 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 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("beforetoggle", (event) => {});
onbeforetoggle = (event) => {};
Event type
A ToggleEvent
. Inherits from Event
.
Examples
Basic example
js
const popover = document.getElementById("mypopover");
// ...
popover.addEventListener("beforetoggle", (event) => {
if (event.newState === "open") {
console.log("Popover is being shown");
} else {
console.log("Popover is being hidden");
}
});
A note on toggle event coalescing
It is worth pointing out that beforetoggle
events are coalesced, meaning that if multiple beforetoggle
events are fired before the event loop has a chance to cycle, only a single event will be fired.
For example:
js
popover.addEventListener("beforetoggle", () => {
//...
});
popover.showPopover();
popover.hidePopover();
// `beforetoggle` only fires once
Specifications
Specification |
---|
HTML Standard # event-beforetoggle |
Browser compatibility
BCD tables only load in the browser
See also
- Popover API
- Related event:
toggle