HTMLElement: toggle event

Baseline Widely available *

This feature is well established and works across many devices and browser versions. It’s been available across browsers since January 2020.

* Some parts of this feature may have varying levels of support.

The toggle event of the HTMLElement interface fires on a popover element, <dialog> element, or <details> element just after it is shown or hidden.

  • If the element is transitioning from hidden to showing, the event.oldState property will be set to closed and the event.newState property will be set to open.
  • If the element is transitioning from showing to hidden, then event.oldState will be open and event.newState will be closed.

This event is not cancelable.

Syntax

Use the event name in methods like addEventListener(), or set an event handler property.

js
addEventListener("toggle", (event) => {});

ontoggle = (event) => {};

Event type

Examples

The example code below demonstrates how the toggle event might be used for popover. The same code is might be used for a <dialog> or <details> elements in the same way.

Basic example

This example shows how to listen for the toggle event and log the result.

HTML

The HTML consists of a popover and a button for toggling it open and closed.

html
<button popovertarget="mypopover">Toggle the popover</button>
<div id="mypopover" popover>Popover content</div>

JavaScript

The code adds an event listener for the toggle event and logs the state.

js
const popover = document.getElementById("mypopover");

popover.addEventListener("toggle", (event) => {
  if (event.newState === "open") {
    console.log("Popover has been shown");
  } else {
    console.log("Popover has been hidden");
  }
});

Result

A note on toggle event coalescing

If multiple toggle events are fired before the event loop has a chance to cycle, only a single event will be fired. This is referred to as "event coalescing".

For example:

js
popover.addEventListener("toggle", () => {
  //...
});

popover.showPopover();
popover.hidePopover();
// `toggle` only fires once

Other examples

Specifications

Specification
HTML
# event-toggle

Browser compatibility

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
toggle event
toggle event fires at details elements
toggle event fires at dialog elements
toggle event fires at popover elements

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
In development. Supported in a pre-release version.
In development. Supported in a pre-release version.
No support
No support

See also