Only One <details>
Open At a Time
I was about to invent a wheel with some JavaScript, but just in case I thought I’d take a look at <details>
specs. A very simple HTML element that I thought I new everything about hid a very useful feature — [name]
attribute that enables to have only one disclosure box open at a time:
<details name="story">
<summary>Title</summary>
<p>Content</p>
</details>
<details name="story">
<summary>Title</summary>
<p>Content</p>
</details>
However, on a smaller screen and/or in case of large quantity of content an upper auto-closing element means the scroll position will be lost when toggling:
You can run you can hide but you cannot escape JavaScript, especially when in comes to improving the usability of UI. We can listen to toggling using toggle
event triggered on <details>
element and correct scroll position with the help of scrollIntoView()
function:
document.querySelectorAll("details").forEach((node) => {
node.addEventListener("toggle", (e) => {
if (e.currentTarget.open) e.currentTarget.scrollIntoView()
})
})
I am not a fan of interfering with user’s interactions too much, so using scrollIntoViewIfNeeded()
would be a wiser choice if the function was also supported by Firefox. However, this could be easily polyfilled;
if ("scrollIntoViewIfNeeded" in e.currentTarget)
e.currentTarget.scrollIntoViewIfNeeded()
else e.currentTarget.scrollIntoView()