Sub topic 7
Reacting to changes with the toggle event
This chapter assumes you can build a details and summary widget, know how the open attribute and the open property relate, and can attach event listeners in JavaScript. The toggle event is how your code finds out that a disclosure widget changed state. It looks simple, but its timing and propagation rules cause most of the bugs people hit.
What the toggle event is
The toggle event fires on a details element after its open state has changed. It reports that the state is now different. It does not ask permission, and you cannot cancel it.
const details = document.querySelector('details');
details.addEventListener('toggle', () => {
console.log(details.open ? 'expanded' : 'collapsed');
});Three facts define how it behaves:
- It fires after the change. When your handler runs,
details.openalready holds the new value. - It fires asynchronously. The browser queues it as a task instead of calling your handler during the click.
- It does not bubble. A listener on
documentor on a parentdivwill not see it in the normal bubbling phase.
The sections below explain each of these and show how to work with them.
What causes the event to fire
The event is tied to the open state, not to a particular input. Anything that changes the state produces it.
| Cause | Fires toggle? |
|---|---|
| Mouse click on the summary | Yes |
| Enter or Space on a focused summary | Yes |
| Browser find-in-page revealing text inside a closed widget | Yes, because the browser opens the widget |
| `details.open = true` in script | Yes |
| `details.setAttribute('open', '')` or `removeAttribute('open')` | Yes |
| Another `details` with the same `name` opening, which closes this one | Yes, on the one that closes |
| Setting `open` to the value it already has | No, nothing changed |
This is why you should prefer toggle over a click listener on the summary. A click handler runs before the state changes, so details.open still holds the old value. It also misses keyboard activation in some setups, find-in-page, scripted changes, and the automatic closing in a named group. toggle covers all of them.
// Fragile: reads the state before it changes, and misses non-click causes
summary.addEventListener('click', () => {
console.log(details.open); // the old value
});
// Reliable: runs after any cause of a change
details.addEventListener('toggle', () => {
console.log(details.open); // the new value
});Timing: the event is asynchronous
When the state changes, the browser queues a task to fire toggle. Your own synchronous code runs first. This has one visible consequence.
const details = document.querySelector('details');
details.addEventListener('toggle', () => {
console.log('toggle fired, open =', details.open);
});
details.open = true;
console.log('after assignment, open =', details.open);The output order is:
after assignment, open = true
toggle fired, open = trueThe property changes immediately, so you can read it right away. The event arrives later. If you need to do something "when it has finished opening", do it in the toggle handler, not on the line after the assignment.
Because the event is queued, you should not expect one event for each intermediate change. If a script flips open several times in the same task, the browser may deliver fewer events than there were changes. Always read the current state in the handler instead of counting events.
Reading the new state
There are two ways to learn the state inside a handler.
- Read
event.target.open, which is a boolean. This works in every browser that supportsdetails. - Read
event.newStateandevent.oldState, which are the strings"open"or"closed". These exist on theToggleEventinterface in newer browsers. Check your support targets before depending on them.
document.querySelector('details').addEventListener('toggle', (event) => {
const details = event.target;
console.log('boolean:', details.open);
if ('newState' in event) {
console.log(`changed from ${event.oldState} to ${event.newState}`);
}
});The feature check with 'newState' in event lets the same code run in older browsers, where the event is a plain Event without those properties. The boolean works everywhere, so use it by default and treat newState as an extra.
The event does not bubble
The toggle event is dispatched on the details element and does not bubble up the tree. This surprises people who try ordinary event delegation, where one listener on a container handles all its children.
// Does NOT work: the event never reaches the container during bubbling
document.querySelector('#faq').addEventListener('toggle', (event) => {
console.log('never runs for child details');
});You have two options.
The first is to attach a listener to every details:
document.querySelectorAll('details').forEach((details) => {
details.addEventListener('toggle', () => {
console.log(details.id, details.open);
});
});This is simple and fine for a fixed page. It misses widgets added to the page later.
The second is to listen in the capture phase. Events that do not bubble still travel down through ancestors during capture, so a capturing listener on a container sees them first.
document.querySelector('#faq').addEventListener(
'toggle',
(event) => {
const details = event.target;
if (!(details instanceof HTMLDetailsElement)) return;
console.log(details.id, details.open);
},
true // capture
);This handles widgets added later, because the listener lives on the container. The instanceof check matters. Other elements, such as popovers, also fire toggle events, and with a capturing listener you will see those too. If your container holds nested details, remember that event.target is the one that changed, not the container.
Example: load content the first time it opens
A common use of toggle is deferring work until the user asks for the content. The body of a closed details costs the user nothing to skip, so fetch it only when it opens.
<details id="shipping" data-src="/fragments/shipping.html">
<summary>Shipping information</summary>
<div class="body">Loading is not started yet.</div>
</details>
<script>
const details = document.querySelector('#shipping');
const body = details.querySelector('.body');
details.addEventListener('toggle', async () => {
if (!details.open) return;
if (details.dataset.loaded === 'true') return;
details.dataset.loaded = 'true';
body.textContent = 'Loading...';
try {
const response = await fetch(details.dataset.src);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
body.innerHTML = await response.text();
} catch (error) {
details.dataset.loaded = 'false';
body.textContent = 'Could not load this section. Close and reopen to retry.';
}
});
</script>Points to notice:
- The handler ignores closing, because
details.openis false then. - A
data-loadedflag stops repeat fetches when the user opens and closes the widget many times. - On failure the flag is reset, so the next opening retries.
- The fetched HTML is inserted with
innerHTML. Only do this with content from your own server. For anything user-supplied, usetextContentor sanitize it first.
If the widget carries the open attribute in the markup, the content must also load for that initial state. Browsers differ in whether they fire toggle for an element that is open when the page is parsed, so do not rely on the event for the first load. A safe pattern is to put the loading code in a function, call it once at startup for widgets that are already open, and call it from the handler afterward.
Example: remember which sections are open
Saving state across visits shows the capture pattern and the effect of programmatic changes.
<details id="intro" open>
<summary>Introduction</summary>
<p>Welcome to the guide.</p>
</details>
<details id="setup">
<summary>Setup</summary>
<p>Install the tool, then run it.</p>
</details>
<script>
const KEY = 'details-state';
const saved = JSON.parse(localStorage.getItem(KEY) ?? '{}');
// Restore saved states
document.querySelectorAll('details[id]').forEach((details) => {
if (details.id in saved) {
details.open = saved[details.id];
}
});
// Save every later change
document.addEventListener(
'toggle',
(event) => {
const details = event.target;
if (!(details instanceof HTMLDetailsElement) || !details.id) return;
saved[details.id] = details.open;
localStorage.setItem(KEY, JSON.stringify(saved));
},
true
);
</script>The restore step sets open, which queues toggle events. Those events arrive after the listener is attached, so they run the save code and write back the same values. That is harmless here, but it is worth knowing: a toggle handler cannot tell a user action from a script action. If the difference matters, set a flag around your own changes:
let restoring = true;
// ... restore states here ...
setTimeout(() => {
restoring = false;
}, 0);Then ignore events while restoring is true. Because the event is queued as a task, you must clear the flag in a later task, as above, and not on the line right after the restore loop.
Toggle events in an exclusive group
When several details share a name, opening one closes the others. Each element that changes gets its own toggle event. Opening one item in a group of three, with another item previously open, produces two events: one for the item that closed and one for the item that opened.
<details name="faq" id="q1" open>
<summary>How do I reset my password?</summary>
<p>Use the reset link on the sign-in page.</p>
</details>
<details name="faq" id="q2">
<summary>How do I change my email?</summary>
<p>Open account settings and edit the email field.</p>
</details>
<script>
document.addEventListener(
'toggle',
(event) => {
const details = event.target;
if (!(details instanceof HTMLDetailsElement)) return;
console.log(`${details.id}: ${details.open ? 'opened' : 'closed'}`);
},
true
);
</script>Clicking the second summary logs two lines, one q1: closed and one q2: opened. The order between the two is not something to build logic on. If your code needs to know "which item is open now", read it directly instead of tracking events:
const current = document.querySelector('details[name="faq"][open]');
console.log(current ? current.id : 'none open');Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Listener on a container never runs | `toggle` does not bubble | Add the listener to each `details`, or use capture (`true` as the third argument) |
| Handler reads the old state | Listening to `click` on the summary, which runs before the change | Listen to `toggle` and read `details.open` |
| Code after `details.open = true` expects the event to have run | The event is queued and fires later | Put follow-up work in the `toggle` handler |
| Handler fires for non-`details` elements | A capturing listener also sees `toggle` from popovers | Check `event.target instanceof HTMLDetailsElement` |
| Endless open and close loop | The handler sets `open`, which queues another event | Only set `open` when it differs from the desired value |
| Counts of events do not match counts of changes | Several changes in one task can coalesce | Read the current state instead of counting |
| Content loads twice | Handler runs on every opening | Guard with a flag such as `data-loaded` |
The loop error deserves an example, because it looks innocent.
// Bug: forces the widget back open, so every close queues another event
details.addEventListener('toggle', () => {
details.open = true;
});This particular handler stops after one extra pass, since setting open to its current value does nothing. A handler that flips the state, such as details.open = !details.open, never settles. If you want a widget the user cannot close, use a div instead. Fighting the native behavior from inside its own event is brittle.
Choosing between toggle and other hooks
Use toggle when you care about the resulting state, from any source: analytics, saving preferences, lazy loading, updating a label elsewhere on the page. Use click on the summary only when you must intercept the user's action before it takes effect. Use a MutationObserver on the open attribute only if you need to observe changes synchronously with microtask timing, which is rare, and note that it watches the attribute rather than the property.
Exercise
A page has ten details elements inside <div id="docs">. You add document.getElementById('docs').addEventListener('toggle', handler) and it never runs when you open a section. Give two ways to fix it, and say which one still works for sections added to the page after load.
Show answer
The toggle event does not bubble, so the container never sees it during the bubbling phase. Fix 1: attach the listener to each details element, for example with querySelectorAll('details').forEach(...). This misses sections added later. Fix 2: pass true as the third argument to addEventListener on the container, so it listens in the capture phase. Capture works for non-bubbling events and covers sections added later, because the listener is on the container. Inside the handler, check event.target instanceof HTMLDetailsElement.
Exercise
In this code, what is logged and in what order? const d = document.querySelector('details'); d.addEventListener('toggle', () => console.log('A', d.open)); d.open = true; console.log('B', d.open);
Show answer
It logs B true first and A true second. Setting open changes the property immediately, so the synchronous console.log('B', ...) sees true. The toggle event is queued as a task and fires after the current script finishes, so the handler logs A true afterward.
Exercise
Two details elements share name="faq", and the first one is open. The user clicks the summary of the second one. How many toggle events fire, on which elements, and what should you do if you need to know which item is open afterward?
Show answer
Two events fire: one on the first element, which closed, and one on the second element, which opened. Do not rely on the order. To find the open item, query it directly, for example document.querySelector('details[name="faq"][open]'), instead of reconstructing it from events.