Sub topic 7
Reacting to changes with the toggle event
This chapter assumes you can build a details and summary widget, know that the open attribute sets the initial state, and can select elements and add event listeners in JavaScript. Here you will learn when the browser fires the toggle event, what the event tells you, and the mistakes that most often cause trouble.
What the toggle event does
A details element changes state when the user activates its summary, when your script sets details.open, or when a script adds or removes the open attribute. After any of these changes, the browser fires a toggle event on the details element.
The event is a signal that the state has changed. It is not a request you can cancel. By the time your listener runs, the content is already shown or hidden.
A basic listener
The first example logs the new state each time it changes.
const details = document.querySelector('details');
details.addEventListener('toggle', () => {
console.log(details.open ? 'expanded' : 'collapsed');
});Inside the listener, read details.open to learn the current state. It is true when the content is visible and false when it is hidden.
Reading the old and new state
Modern browsers pass a ToggleEvent to the listener. It has two extra properties, oldState and newState. Their values are the strings "open" and "closed".
const details = document.querySelector('details');
details.addEventListener('toggle', (event) => {
console.log(`Changed from ${event.oldState} to ${event.newState}`);
});Older browsers fire a plain Event without these properties. If you need to support them, read details.open instead. It works everywhere.
Loading content on first open
A common use of toggle is to do work only when the user first expands the widget. This example fetches text the first time the widget opens and never fetches it again.
<details id="changelog">
<summary>Show changelog</summary>
<div id="changelog-body">Loading...</div>
</details>
<script>
const changelog = document.getElementById('changelog');
const body = document.getElementById('changelog-body');
let loaded = false;
changelog.addEventListener('toggle', async () => {
if (!changelog.open || loaded) return;
loaded = true;
try {
const response = await fetch('/changelog.txt');
body.textContent = response.ok ? await response.text() : 'Could not load.';
} catch (error) {
body.textContent = 'Could not load.';
loaded = false;
}
});
</script>The listener exits early when the widget is closing, or when the data is already loaded. The loaded flag is set before the request starts, so a quick open, close, open sequence does not start two requests. It is reset on a network failure so the user can try again.
Common errors
The event fires on page load
If a details element has the open attribute in the HTML, browsers fire a toggle event once after the page is parsed, because the element starts in the open state. A listener that assumes "toggle means the user did something" will run at load time. Check for this case if your listener has side effects such as analytics calls or saved preferences.
The event does not bubble
The toggle event does not bubble. A listener on a parent element or on document will not see it with default settings. You have three options:
- Attach a listener to each
detailselement. - Use the capture phase, which still works for events that do not bubble.
- Listen on each element inside a loop.
This example uses capture to handle every details element on the page with one listener.
document.addEventListener(
'toggle',
(event) => {
if (event.target.matches('details')) {
console.log(event.target.id, event.target.open);
}
},
true
);The true argument turns on capture. Without it, the listener never runs.
Events are batched
The browser queues one toggle event for each change, but it delivers the events asynchronously. If a script sets details.open = true and then details.open = false in the same task, the listener may run once, or not at all, because the state it sees is the final one. Always read the state inside the listener instead of assuming it from your own code.
Infinite loops
Setting details.open inside a toggle listener fires another event if the value actually changes. A listener that always sets open = true is safe, because the second event does not change anything. A listener that flips open each time will loop forever.
// Unsafe: each toggle triggers another toggle
details.addEventListener('toggle', () => {
details.open = !details.open;
});Accordion groups
Details elements that share a name close each other. When the user opens one, the browser closes the other open one, and each of those changes fires its own toggle event. You get one event for the closing element and one for the opening element. Use event.target or a reference to the specific element to tell them apart.
document.querySelectorAll('details[name="faq"]').forEach((item) => {
item.addEventListener('toggle', () => {
console.log(item.querySelector('summary').textContent, item.open);
});
});Summary of key points
| Behavior | What to do |
|---|---|
| Need the current state | Read `details.open` in the listener |
| Need the previous state | Use `event.oldState` where supported |
| Listening on a parent | Use capture, because the event does not bubble |
| Side effects on load | Guard against the initial event for `open` elements |
| Accordion groups | Expect one event per element that changes |
Exercise
You attach a single toggle listener to document (without the capture argument) to track every details element on the page, and it never runs. Why, and how do you fix it?
Show answer
The toggle event does not bubble, so a listener on document in the default bubbling phase never receives it. Pass true as the third argument to addEventListener to use the capture phase, or attach a listener to each details element.
Exercise
A page has <details open> and a toggle listener that sends an analytics event "user expanded section". The analytics shows an expansion for every page view. What is the cause, and what check could you add?
Show answer
Browsers fire a toggle event at load for a details element that starts open, so the listener runs without any user action. Compare event.oldState with event.newState where supported, or ignore the first event for elements that had the open attribute at load. A more reliable approach is to track user clicks on the summary for analytics.