HTML onbeforetoggle Event Attribute
Description
The onbeforetoggle event attribute runs a script just before a popover element is shown or hidden. In recent browsers it also fires on <dialog> elements before they open or close. It does not fire on <details> elements, which only have the ontoggle event.
The handler receives a ToggleEvent with two properties:
event.oldState- the state before the change,"open"or"closed".event.newState- the state after the change,"open"or"closed".
When the element is about to open (newState is "open"), the event is cancelable: calling event.preventDefault() keeps the popover or dialog closed. When it is about to close, the event cannot be canceled.
<button popovertarget="menu">Menu</button>
<div id="menu" popover onbeforetoggle="checkToggle(event)">Popover content</div>
function checkToggle(event) {
if (event.newState === "open" && !userIsLoggedIn) {
event.preventDefault(); // the popover stays closed
}
}
The order of events is: beforetoggle fires first, the element opens or closes, and then toggle fires asynchronously.
Use Cases
- Loading or updating the content of a popover just before it is shown.
- Preventing a popover from opening under certain conditions.
- Starting or stopping animations or timers that depend on the popover being visible.
Syntax
<element onbeforetoggle="script(event)">
Values
- scriptThe name of the script to use when the event has been triggered.
Example
Browser Support
The following information will show you the current browser support for the HTML onbeforetoggle event attribute. Hover over a browser icon to see the version that first introduced support for this HTML event attribute.
Desktop





Tablets & Mobile





