Sub topic 6
Controlling the state from JavaScript
This chapter assumes you can write basic HTML, select elements with document.querySelector, and add event listeners. You should also know how the open attribute sets the starting state of a details element, which an earlier chapter covered.
The open property mirrors the open attribute
The details element exposes a boolean DOM property named open. It reflects the open attribute. If the attribute is present, details.open is true. If it is absent, details.open is false.
Reflection works in both directions:
- Setting
details.open = trueadds theopenattribute to the element. - Setting
details.open = falseremoves it. - When the user clicks the summary, the browser adds or removes the attribute, and
details.openchanges with it.
Because the property and the attribute stay in sync, you can read the state at any time without tracking it yourself.
<details id="policy">
<summary>What is your return policy?</summary>
<p>You can return items within 30 days of delivery.</p>
</details>
<button id="show">Show policy</button>
<button id="hide">Hide policy</button>
<button id="flip">Toggle policy</button>
<script>
const policy = document.querySelector('#policy');
document.querySelector('#show').addEventListener('click', () => {
policy.open = true;
});
document.querySelector('#hide').addEventListener('click', () => {
policy.open = false;
});
document.querySelector('#flip').addEventListener('click', () => {
policy.open = !policy.open;
});
</script>The third button shows the usual idiom for flipping the state: assign the negation of the current value.
Use the property, not getAttribute
open is a boolean attribute, so its value is not the string "true" or "false". The attribute is either present or absent. For that reason, avoid code like this:
// Unreliable: the value is an empty string when open, null when closed
if (details.getAttribute('open') === 'true') {
// never runs
}Both of the following work, but the property is simpler and is the normal choice:
details.open; // true or false
details.hasAttribute('open'); // true or falseOpening and closing many widgets at once
Since open is an ordinary property, you can loop over a list of elements. A common use is an "Expand all" and "Collapse all" control for a long FAQ.
const items = document.querySelectorAll('details');
function setAll(state) {
items.forEach((item) => {
item.open = state;
});
}
// setAll(true) expands every item, setAll(false) collapses them.If the items share a name attribute to form an exclusive group, this behaves differently. Only one member of a group can be open at a time, so opening them all in a loop leaves a single item open. The exclusive accordion is covered in a later chapter.
Changes happen when the state flips
Setting open to the value it already has does nothing. The browser only acts when the state actually changes. This matters when you write code that reacts to changes, which is the subject of the next chapter. Assigning details.open = true to an element that is already open produces no change.
The following diagram shows how the property, the attribute, and the user relate.
Common errors
- Setting a string.
details.open = 'false'sets the property totrue, because any non-empty string converts totrue. Assign real booleans. - Selecting the wrong element.
document.querySelector('summary').openisundefined. Theopenproperty belongs todetails, notsummary. Usesummary.parentElementorsummary.closest('details')to reach it. - Running before the element exists. If your script sits in the
headand runs immediately,querySelectorreturnsnull. Place the script after the markup, or adddeferto an external script. - Assuming a click handler on summary reports the new state. Reading
details.openinside aclicklistener on the summary gives the state before the browser applies the toggle. Use thetoggleevent for that, as the next chapter explains.
const summary = document.querySelector('summary');
const details = summary.closest('details');
summary.addEventListener('click', () => {
// Still the old value here.
console.log('before toggle:', details.open);
});A practical pattern: close on outside action
You can use the property to close a widget when something else happens, such as pressing Escape while focus is inside it.
<details id="help">
<summary>Help</summary>
<p>Press Escape to close this panel.</p>
<input type="text" aria-label="Search help">
</details>
<script>
const help = document.querySelector('#help');
help.addEventListener('keydown', (event) => {
if (event.key === 'Escape' && help.open) {
help.open = false;
help.querySelector('summary').focus();
}
});
</script>The script returns focus to the summary after closing. Without that step, focus would sit on a hidden input, and keyboard users would lose their place.
Exercise
A page has <details id="d">. You run d.open = 'false' and the widget expands. Why, and what is the correct way to close it?
Show answer
A non-empty string such as 'false' converts to the boolean true when assigned to a boolean property, so the widget opens. Assign the boolean false instead: d.open = false.
Exercise
Inside a click listener on a summary element, you log details.open. The widget was closed before the click. What value is logged, and which event should you use to see the new state?
Show answer
It logs false, the state before the browser applies the toggle. Use the toggle event on the details element, which fires after the state has changed.