A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/toggle_event below:

HTMLElement: toggle event - Web APIs

HTMLElement: toggle event

Baseline Widely available *

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

This event is not cancelable.

Syntax

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

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.

<button popovertarget="mypopover">Toggle the popover</button>
<div id="mypopover" popover>Popover content</div>
#log {
  height: 150px;
  overflow: scroll;
  padding: 0.5rem;
  border: 1px solid black;
}
const logElement = document.querySelector("#log");
function log(text) {
  logElement.innerText = `${logElement.innerText}${text}\n`;
  logElement.scrollTop = logElement.scrollHeight;
}
JavaScript

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

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:

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

popover.showPopover();
popover.hidePopover();
// `toggle` only fires once
Other examples Specifications Browser compatibility See also

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.3