Sub topic 6
Controlling the state from JavaScript
This chapter assumes you can build a basic details and summary widget, and that you know what the open attribute does. It also assumes you can select elements with querySelector and add event listeners. Here you will read and change the open state from a script, and you will see which pitfalls to avoid.
The open property mirrors the open attribute
Every details element has an open property. Its value is true when the widget is expanded and false when it is collapsed. The property is a reflection of the open attribute: the two always agree, and changing one changes the other.
const details = document.querySelector('details');
console.log(details.open); // false if the attribute is absent
details.open = true;
console.log(details.hasAttribute('open')); // true, updated immediately
details.open = false;
console.log(details.hasAttribute('open')); // falseThe browser does the work in both directions:
- When the user clicks the summary, the browser adds or removes the attribute, so
details.openchanges with it. - When your script sets
details.open, the browser adds or removes the attribute and shows or hides the content.
You never need to track the state in a separate variable. Read the property whenever you need the current state.
Ways to change the state
You can reach the same result in several ways. They differ in readability and in the events they produce.
| Approach | Effect | Notes |
|---|---|---|
| `details.open = true` | Expands the widget | The usual choice. |
| `details.open = !details.open` | Flips the state | Use it for a custom toggle button. |
| `details.setAttribute('open', '')` | Expands the widget | Any value works, because only the attribute's presence counts. |
| `details.removeAttribute('open')` | Collapses the widget | Equivalent to `open = false`. |
| `details.toggleAttribute('open')` | Flips the state | Equivalent to `open = !open`. |
| `summary.click()` | Flips the state | Simulates a user click. It also fires click listeners on the summary. |
Prefer the property in your own code. It reads clearly and it returns a real boolean.
Truthiness pitfalls
The property is a boolean, so JavaScript's usual conversion rules apply when you assign to it. Strings are the common trap:
const details = document.querySelector('details');
details.open = 'false'; // a non-empty string is truthy, so the widget OPENS
details.open = ''; // an empty string is falsy, so the widget closes
details.open = 0; // closes
details.open = 1; // opensThe same rule applies to values from localStorage, dataset, and form fields, which are always strings. Convert them explicitly before assigning, for example details.open = value === 'true'.
What happens when you set the property
Setting open is synchronous for the attribute and for what the user sees on the next render. The toggle event is not synchronous. The browser queues it and fires it after your current code finishes.
The sequence diagram shows the order.
Two practical consequences follow:
- Code right after
details.open = truecan already rely ondetails.open === true. You do not need to wait for the event. - A
togglelistener never runs in the middle of your own code. If you change the state several times in one block of code, the browser may coalesce the changes into fewer events than you expect. Do not count events to track how often the state changed. Readdetails.openwhen the listener runs.
The next chapter covers the toggle event in detail. Here you only need to know that it is the signal for "the state changed, whoever changed it".
Example: expand all and collapse all
A page with many details elements, such as a FAQ or a long reference, often needs bulk controls. This page is complete and runs as shown.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Expand and collapse all</title>
</head>
<body>
<p>
<button type="button" id="expand-all">Expand all</button>
<button type="button" id="collapse-all">Collapse all</button>
</p>
<details>
<summary>Shipping</summary>
<p>Orders ship within two business days.</p>
</details>
<details>
<summary>Returns</summary>
<p>You can return items within 30 days of delivery.</p>
</details>
<details>
<summary>Payment</summary>
<p>We accept cards and bank transfers.</p>
</details>
<script>
const items = document.querySelectorAll('details');
function setAll(state) {
items.forEach((item) => {
item.open = state;
});
}
document.getElementById('expand-all').addEventListener('click', () => setAll(true));
document.getElementById('collapse-all').addEventListener('click', () => setAll(false));
</script>
</body>
</html>querySelectorAll returns every matching element, so you can loop over all of them. A plain querySelector returns only the first, which is a frequent source of "only the first item opens" bugs.
The loop also reaches nested details elements, because querySelectorAll('details') searches the whole document. If you want only top-level widgets, narrow the selector, for example :scope > details inside a container.
Bulk changes and exclusive groups
Bulk expansion does not work on a group of details elements that share a name attribute. Only one member of such a group can be open at a time, so opening a second one closes the first. If you loop over a group and set open = true on each member, only the last one stays open. Exclusive groups are the subject of a later chapter. For now, exclude them from "expand all" logic, for example with details:not([name]).
Example: a custom toggle button
Sometimes the control that opens a section is not its summary. A toolbar button, a keyboard shortcut, or a link elsewhere on the page can all do it. In that case, keep the control's accessible state in sync with the widget.
<button type="button" id="faq-button" aria-controls="faq-1" aria-expanded="false">
Show return policy
</button>
<details id="faq-1">
<summary>Return policy</summary>
<p>You can return items within 30 days of delivery.</p>
</details>
<script>
const faq = document.getElementById('faq-1');
const faqButton = document.getElementById('faq-button');
faqButton.addEventListener('click', () => {
faq.open = !faq.open;
});
faq.addEventListener('toggle', () => {
faqButton.setAttribute('aria-expanded', String(faq.open));
});
</script>The button flips the property. The toggle listener then updates aria-expanded. Because the listener reacts to every change, the button stays correct when the user opens the widget by clicking its summary instead. If you updated aria-expanded only inside the click handler, the two controls would drift apart.
The native summary needs no aria-expanded of its own. Browsers expose the expanded state of details to assistive technology. You add the attribute only to the extra button you created.
Example: opening the right section for a URL fragment
A link such as page.html#returns should show the content it points to. If that content sits inside a closed details, the user would see nothing. Some browsers open ancestors for fragment navigation or find-in-page, but support differs. A small script makes the behavior reliable.
function openAncestors(element) {
let current = element.closest('details');
while (current) {
current.open = true;
current = current.parentElement ? current.parentElement.closest('details') : null;
}
}
function revealFragmentTarget() {
if (!location.hash) return;
const id = decodeURIComponent(location.hash.slice(1));
const target = document.getElementById(id);
if (!target) return;
openAncestors(target);
target.scrollIntoView();
}
revealFragmentTarget();
window.addEventListener('hashchange', revealFragmentTarget);Two details matter here:
element.closest('details')returns the element itself when it is adetails. A link straight to adetailselement opens it.- The loop walks upward through nested widgets, so a deep target opens every section that contains it.
Call scrollIntoView after you open the ancestors. If the target is still hidden, it has no position to scroll to.
Example: remembering state between visits
You can store the state of each widget and restore it on the next visit. Give each widget a stable data-id and store booleans in localStorage.
<details data-id="shipping"><summary>Shipping</summary><p>Orders ship within two business days.</p></details>
<details data-id="returns"><summary>Returns</summary><p>You can return items within 30 days of delivery.</p></details>
<script>
const STORAGE_KEY = 'disclosure-state';
function loadState() {
try {
return JSON.parse(localStorage.getItem(STORAGE_KEY)) || {};
} catch {
return {};
}
}
const saved = loadState();
document.querySelectorAll('details[data-id]').forEach((item) => {
const id = item.dataset.id;
if (id in saved) {
item.open = saved[id] === true;
}
item.addEventListener('toggle', () => {
saved[id] = item.open;
localStorage.setItem(STORAGE_KEY, JSON.stringify(saved));
});
});
</script>This script goes at the end of body, or in a script with the defer attribute, so the elements exist when it runs.
Notes on the design:
- The code stores real booleans in JSON. It compares with
=== trueso a corrupted value never opens a widget by accident. - Restoring a state by setting
openqueues atoggleevent, so the listener also runs for restored widgets. It writes back the value it just read, which does no harm. Browsers may also firetogglefor widgets that start with theopenattribute. Write listeners so that they are safe to run once on load. - The
tryandcatchguard against unavailable storage and invalid JSON. Private browsing modes and storage quotas can both cause failures. - Restoring after the first paint can cause a visible jump. If that matters, run the script early, before the content appears, or accept a short flicker.
Edge cases and gotchas
- Hidden content is not part of the layout. While a widget is closed, its body is not rendered. Measuring elements inside it, for example with
offsetHeight, can return0. Open the widget first, then measure. - Focus is not moved for you. Setting
open = trueshows the content but leaves keyboard focus where it was. If you open a section in response to a user action and the user needs to work inside it, callfocus()on the right element yourself. - Closing hides focused content. If focus is inside the body and you set
open = false, the focused element disappears. Move focus to the summary first withsummary.focus()when you close a widget on the user's behalf. - Closing does not animate by default. The content appears and disappears at once. Setting the property does not run any transition. Smooth animation needs extra CSS or script and is a design choice, not a property of
open. - Frameworks may fight you. If a UI library renders
detailsand also controlsopen, let it own the state. Pick one source of truth. Two systems writing to the same attribute produce flicker or lost updates. - Missing summary. If the first child is not a
summary, the browser supplies a default label. Theopenproperty still works, but the widget gives the user no meaningful label. Always include asummary.
Choosing property or attribute access
Use the property for logic and the attribute for markup:
- In HTML, write
openas a bare attribute to start expanded. - In JavaScript, use
details.opento read and write. - Use
hasAttribute('open')only in code that must work with raw attribute operations, such as aMutationObserverthat watches for changes. That observer sees changes made by users and scripts alike, but thetoggleevent is simpler and is the better default.
Summary
details.openis a boolean property that reflects theopenattribute in both directions.- Setting it changes the visible state at once and queues a
toggleevent for later. - Use
querySelectorAllfor bulk operations, and keep exclusive groups out of "expand all". - External controls should update
aria-expandedfrom thetogglelistener, so they stay correct however the state changes. - Convert strings to booleans before assigning, and manage focus yourself when you open or close a widget programmatically.
Exercise
A page has a closed details element with id "notes" and a button with id "go". The button's click handler runs const stored = 'false'; notes.open = stored; and then logs notes.hasAttribute('open') on the next line. What does it log, and how do you fix the code so that the widget stays closed?
Show answer
It logs true. The string 'false' is non-empty, so it is truthy and the property setter adds the open attribute at once. The fix is to compare the string and assign a real boolean: notes.open = stored === 'true';. With that change the assignment is false, and hasAttribute('open') logs false.
Exercise
You wrote a button that sets details.open = true and then immediately reads details.open to decide what to do next. A colleague says you must wait for the toggle event before reading it. Is your colleague right? What is the toggle event useful for here?
Show answer
The colleague is wrong about the property. The attribute and the property update synchronously, so reading details.open right after the assignment returns true. Only the toggle event is delayed, because the browser queues it until your current code finishes. The event is useful for reacting to every change, including those the user makes by clicking the summary, for example to keep an external button's aria-expanded attribute correct.