Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / HTML

onbeforetoggle — handle an upcoming state change

The `onbeforetoggle` attribute sets a handler for `beforetoggle`. The event fires before a popover opens but not before every close. It also fires before dialog transitions initiated by methods such as `showModal()` or `close()`. Directly adding or removing a dialog’s `open` attribute does not fire the event. The handler can inspect the previous and intended states and cancel opening.

Version: WHATWG HTML Living Standard; index snapshot date recorded separately

Syntax

onbeforetoggle="JavaScript statements"
element.onbeforetoggle = (event) => { /* handler */ };
element.addEventListener("beforetoggle", (event) => { /* listener */ });

onbeforetoggle is an event-handler attribute for beforetoggle; its value contains JavaScript code, not a Boolean value. Its corresponding property is element.onbeforetoggle. The event fires before a popover opens but not before every close. For example, removing an open popover from the document closes it without firing beforetoggle. Do not rely on this event to observe every close. For a dialog element, it fires when opening through methods such as show() or showModal() or closing through close(). Directly adding or removing the open attribute changes the dialog’s state without firing beforetoggle.

The ToggleEvent object exposes oldState and newState, whose values are "closed" or "open". When opening, the event can be canceled with event.preventDefault(). If the event fires when closing, it is not cancelable. toggle is a separate event reporting a state change; do not confuse it with beforetoggle.

Attribute code has access to event; return false also cancels a cancelable event. Assigning a function to element.onbeforetoggle replaces that property's existing handler. Alternatively, addEventListener("beforetoggle", handler) allows independent listeners to be added.

The example cancels opening requested by showPopover(), so the expected text is open: false. It requires a browser implementing these features and permitting inline event handlers. Adding onbeforetoggle alone does not give an element popover behavior.

Examples

<!doctype html>
<meta charset="utf-8">
<title>onbeforetoggle</title>
<div id="panel" popover="manual"
     onbeforetoggle="if (event.newState === 'open') event.preventDefault()">
  Popover
</div>
<pre id="result"></pre>
<script>
  const panel = document.getElementById('panel');
  panel.showPopover();
  document.getElementById('result').textContent =
    'open: ' + panel.matches(':popover-open');
</script>

Result

open: false

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources