HTMLDetailsElement: toggle event
The toggle
event fires when the open
/closed
state of a <details>
element is toggled.
This event is not cancelable and does not bubble.
Note: The toggle
event is also available in a different form on HTMLElement
; this version fires on popover elements just after they are shown or hidden. See the HTMLElement
toggle event
page for more information.
Syntax
Use the event name in methods like addEventListener()
, or set an event handler property.
addEventListener("toggle", (event) => {});
ontoggle = (event) => {};
Event type
Examples
This example logs chapters that are open. Chapters are removed from the log when they are closed.
HTML
<aside id="log">
<p>Open chapters:</p>
<div data-id="ch1" hidden>I</div>
<div data-id="ch2" hidden>II</div>
<div data-id="ch3" hidden>III</div>
</aside>
<section id="summaries">
<p>Chapter summaries:</p>
<details id="ch1">
<summary>Chapter I</summary>
Philosophy reproves Boethius for the foolishness of his complaints against
Fortune. Her very nature is caprice.
</details>
<details id="ch2">
<summary>Chapter II</summary>
Philosophy in Fortune's name replies to Boethius' reproaches, and proves
that the gifts of Fortune are hers to give and to take away.
</details>
<details id="ch3">
<summary>Chapter III</summary>
Boethius falls back upon his present sense of misery. Philosophy reminds him
of the brilliancy of his former fortunes.
</details>
</section>
CSS
body {
display: flex;
flex-direction: row-reverse;
}
#log {
flex-shrink: 0;
padding-left: 3em;
}
#summaries {
flex-grow: 1;
}
JavaScript
function logItem(e) {
const item = document.querySelector(`[data-id=${e.target.id}]`);
item.toggleAttribute("hidden");
}
const chapters = document.querySelectorAll("details");
chapters.forEach((chapter) => {
chapter.addEventListener("toggle", logItem);
});
Result
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 |
36 |
79 |
49 |
No |
23 |
10.1 |
37 |
36 |
49 |
24 |
10.3 |
3.0 |