W3cubDocs

/Web APIs

HTMLElement: toggle event

Experimental: This is an experimental technology
Check the Browser compatibility table carefully before using this in production.

The toggle event of the HTMLElement interface fires on a popover element (i.e. one that has a valid popover attribute) just after it is shown or hidden.

  • If the popover 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 popover element is transitioning from showing to hidden, then event.oldState will be open and event.newState will be closed.

Note: The toggle event behaves differently when fired on <details> elements. In this case, it does not relate to popovers, and instead fires when the open/closed state of a <details> element is toggled. See the HTMLDetailsElement toggle event page for more information.

Syntax

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

js

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

ontoggle = (event) => {};

Event type

Examples

Basic example

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");
  }
});

A note on toggle event coalescing

It is worth pointing out that toggle events are coalesced, meaning that if multiple toggle events are fired before the event loop has a chance to cycle, only a single event will be fired.

For example:

js

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

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

Specifications

Browser compatibility

Desktop Mobile
Chrome Edge Firefox Internet Explorer Opera Safari WebView Android Chrome Android Firefox for Android Opera Android Safari on IOS Samsung Internet
toggle_event 114 114 114 No 100 17 114 114 No No 17 No

See also

© 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/toggle_event