Sub topic 3
Reacting to Changes with the `toggle` Event
Assume you know basic HTML, CSS selectors, and JavaScript event listeners. A disclosure widget uses <details> for the state and <summary> for the control. The toggle event runs after the widget changes between open and closed.
Reacting to Changes with the `toggle` Event
Read the current state with the Boolean open property. Set it to open or close the widget from JavaScript.
<details id="account-help">
<summary>Account help</summary>
<p id="status">More information is hidden.</p>
</details>
<script>
const details = document.querySelector("#account-help");
const status = document.querySelector("#status");
details.addEventListener("toggle", () => {
status.textContent = details.open
? "More information is visible."
: "More information is hidden.";
});
details.open = true;
</script>A toggle listener is useful when other interface content must follow the disclosure state. For example, it can update analytics, load expensive content, or change a status message. Do not use it when CSS alone can express the change.
Exclusive Accordions with `name`
Give related <details> elements the same name value to create an exclusive group. Opening one closes the other items in that group without JavaScript.
<details name="support">
<summary>Reset a password</summary>
<p>Use the reset link on the sign-in page.</p>
</details>
<details name="support">
<summary>Change an email address</summary>
<p>Open account settings and edit the email field.</p>
</details>The name value groups only details elements that share that exact value.
Keyboard Use and Accessibility
Browsers make <summary> keyboard-focusable and activate it with Enter or Space. Keep the summary text clear and meaningful. Do not replace it with a generic button role or add another interactive element inside it.
The hidden content remains in the document but is unavailable while its details element is closed. Use the native structure instead of hiding content with CSS when the content should be revealed by the control.
When Native `details` Is Enough
Use native disclosure when you need simple show-and-hide content, FAQ sections, or an accordion. It provides state management, keyboard behavior, and a semantic relationship with little code.
Choose a custom component when you need complex animation, coordinated state across unrelated elements, or behavior that native grouping cannot express. Test the result with keyboard navigation and assistive technology before replacing the native element.
Exercise
How can you update a message whenever a disclosure opens or closes?
Show answer
Add a toggle event listener and read the element's Boolean open property.