Using <details>
tags for HTML-only UI toggles
If you usually reach for JavaScript when trying to create show/hide toggle on elements, this post is for you.
This post is a reply to
:Github tip: you can use <detail></detail> tags in @github markdown to add collabsible/expandable content: pic.twitter.com/Pco0KRx2De
— Jake VanderPlas (@jakevdp) May 4, 2018
As the comments in the tweet mention, this is actually built into the HTML5.1 spec, not something that was specific to GitHub.
The other plus for this is that I would assume it's more accessible to users as it's built into the Browser / User Agent, so it'd be supported by accessibility tools.
But how do you actually use it? Let's say that we have a large list that only needs to be shown when necessary i.e a table of contents. All we need to do is wrap it in a <details>
element:
<details>
<ul>
<li>Lorem ipsum dolor sit amet, consectetur adipisicing elit</li>
<li>sed do eiusmod tempor incididunt ut labore et dolore magna aliqua</li>
<li>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat</li>
<li>Duis aute irure dolor in reprehenderit in voluptate velit esse cillum </li>
<li>dolore eu fugiat nulla pariatur</li>
</ul>
</details>
Which then renders as:
- Lorem ipsum dolor sit amet, consectetur adipisicing elit
- sed do eiusmod tempor incididunt ut labore et dolore magna aliqua
- Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat
- Duis aute irure dolor in reprehenderit in voluptate velit esse cillum
- dolore eu fugiat nulla pariatur
However, we may want to specify a title rather than the one that the browser decides for us, so we can add the <summary
element inside our <details
>:
<details>
<summary>lorem ipsum</summary>
<ul>
<li>Lorem ipsum dolor sit amet, consectetur adipisicing elit</li>
<li>sed do eiusmod tempor incididunt ut labore et dolore magna aliqua</li>
<li>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat</li>
<li>Duis aute irure dolor in reprehenderit in voluptate velit esse cillum </li>
<li>dolore eu fugiat nulla pariatur</li>
</ul>
</details>
Which renders as:
lorem ipsum
- Lorem ipsum dolor sit amet, consectetur adipisicing elit
- sed do eiusmod tempor incididunt ut labore et dolore magna aliqua
- Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat
- Duis aute irure dolor in reprehenderit in voluptate velit esse cillum
- dolore eu fugiat nulla pariatur
You can read more on the Mozilla Developer Network article <details>: The Details disclosure element
To commemorate this finding, I'm now over-using these toggles all over my website! This makes table of contents nicer, as well as the metadata about the post.