References

Beginner-friendly references for web development, with live, editable examples.

The HTML onbeforetoggle event

Event All modern browsers Updated
Quick answer

The HTML onbeforetoggle attribute runs JavaScript when a popover or <dialog> is about to open or close. It is an inline handler for the beforetoggle event; in modern code prefer addEventListener('beforetoggle', …).

Overview

The onbeforetoggle event attribute runs JavaScript just before a popover or <dialog> toggles. In JavaScript the event itself is named beforetoggle. Drop the on prefix when you call addEventListener.

It relates to popovers and the <dialog> element, letting you react just before one opens or closes, for example to load content before it appears. On a popover the event is cancelable, so preventDefault() stops the change; on a <dialog> it is not. <details> does not fire it at all; it fires only toggle.

You can wire this up with the inline onbeforetoggle HTML attribute, but the modern, recommended approach is element.addEventListener('beforetoggle', handler) in JavaScript. That keeps behavior out of your markup, lets you attach several handlers to the same event, and makes them easy to remove. The inline attribute is fine for quick demos.

Syntax

<element onbeforetoggle="handler()"></element>

element.addEventListener('beforetoggle', handler);

Best practices

  • Prefer element.addEventListener('beforetoggle', handler) over the inline onbeforetoggle attribute; it separates behavior from markup and allows multiple handlers.
  • Prefer the native <dialog>, <details> and popover APIs that fire these events over hand-built widgets.
  • Use the event to sync state, for example to lazy-load content when a panel opens.
  • Keep these widgets accessible: manage focus and provide an accessible name.

Frequently asked questions

What is the onbeforetoggle event?
It runs JavaScript just before a popover or <dialog> toggles. In JavaScript the event is named beforetoggle.
Which elements fire this event?
Popovers and the <dialog> element. <details> fires only the toggle event, not beforetoggle.
How do I react when a details element opens?
Listen for the toggle event and check the element's open property.
Should I use the onbeforetoggle attribute or addEventListener?
Prefer element.addEventListener('beforetoggle', …) in JavaScript. The inline onbeforetoggle attribute works but mixes behavior into the markup and allows only one handler per element.