files/en-us/web/api/htmlelement/toggle_event/index.md
{{APIRef("HTML DOM")}}
The toggle event of the {{domxref("HTMLElement")}} interface fires on a {{domxref("Popover_API", "popover", "", "nocode")}} element, {{htmlelement("dialog")}} element, or {{htmlelement("details")}} element just after it is shown or hidden.
event.oldState property will be set to closed and the event.newState property will be set to open.event.oldState will be open and event.newState will be closed.This event is not cancelable.
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
addEventListener("toggle", (event) => { })
ontoggle = (event) => { }
A {{domxref("ToggleEvent")}}. Inherits from {{domxref("Event")}}.
{{InheritanceDiagram("ToggleEvent")}}
The example code below demonstrates how the toggle event might be used for {{domxref("Popover_API", "popover", "", "nocode")}}.
The same code is might be used for a {{htmlelement("dialog")}} or {{htmlelement("details")}} elements in the same way.
This example shows how to listen for the toggle event and log the result.
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>
<pre id="log"></pre>
#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;
}
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") {
log("Popover has been shown");
} else {
log("Popover has been hidden");
}
});
{{EmbedLiveSample("Basic example", '100%', "250px")}}
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
HTMLDialogElement{{Specifications}}
{{Compat}}
popover HTML global attributebeforetoggle