References

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

The HTML ontoggle event

Event All modern browsers Updated
Quick answer

The HTML ontoggle attribute runs JavaScript when a

element is opened or closed, or a popover is shown or hidden. It is an inline handler for the toggle event; in modern code prefer addEventListener('toggle', …).

Overview

The ontoggle event attribute runs JavaScript when a

or popover toggles open/closed. In JavaScript the event itself is named toggle — drop the on prefix when you call addEventListener.

It relates to native disclosure and dialog widgets — the <dialog> element, <details>, and popovers — letting you react when they open, close or are dismissed without wiring up the behavior yourself.

You can wire this up with the inline ontoggle HTML attribute, but the modern, recommended approach is element.addEventListener('toggle', 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 ontoggle="handler()">…</element>

element.addEventListener('toggle', handler);

Example

Live example
<details ontoggle="this.nextElementSibling.textContent = this.open ? 'Open' : 'Closed'"><summary>Toggle</summary>Content</details><span></span>

Best practices

  • Prefer element.addEventListener('toggle', handler) over the inline ontoggle 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 ontoggle event?
It runs JavaScript when a
or popover toggles open/closed. In JavaScript the event is named toggle.
Which elements fire this event?
Native disclosure and dialog widgets — <dialog>, <details> and popovers.
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 ontoggle attribute or addEventListener?
Prefer addEventListener('toggle', …) in JavaScript. The inline ontoggle attribute works but mixes behavior into the markup and allows only one handler per element.