🧩 HTML5: Fix a details Element Losing Its Open State After a Form Reset
Setting a <details> element’s open property from script works fine until that element lives inside a <form> that gets reset — a type="reset" button, or a browser restoring form state from the back-forward cache, only reliably preserves disclosure state that the USER toggled by clicking the summary, not state a script set programmatically, so a <details> you opened with JavaScript on page load can silently snap back closed the moment the surrounding form resets, even though nothing in your reset handler ever touched it directly.
🔎 The Problem
const panel = document.querySelector('details#advanced-options');
panel.open = true; // set programmatically on page load, not by a user click
// ...later, inside the SAME <form>:
form.addEventListener('reset', () => {
// this handler never touches `panel` at all
});
// Result: clicking the form's reset button also closes `panel`,
// even though the reset handler above never mentions it
✅ Fix: Re-Apply the Open State Explicitly Inside the Reset Handler
- Don’t assume a programmatically-set
openstate survives a form reset the same way a user’s own click on the summary would — explicitly re-set it inside your ownresetevent handler if that panel needs to stay open. - If the disclosure state genuinely shouldn’t be tied to the form’s lifecycle at all, move the
<details>element outside the<form>boundary (visually repositioning it with CSS if needed) so a reset simply can’t touch it. - Test any script-driven disclosure state specifically against the browser’s back-forward cache restore (navigate away and use the back button), not only against an explicit reset button — bfcache restores can trigger the same loss of script-set state without any reset control being clicked at all.
🚨 Why This Is Dangerous
- Building an ‘advanced options’ panel that silently closes and discards the user’s visible context the moment they click an unrelated reset button elsewhere on the form, with nothing in the reset handler’s own code hinting that it was responsible.
A form reset only promises to undo what the user typed — not what your script decided to show them.
