In the past when building accordion components, I'll usually reach for Bootstrap's accordion implementation. Most of the projects I work on use Bootstrap so it's always seemed like the obvious choice. It's a wee bit complicated though.
<p> <a data-toggle="collapse" href="#collapseExample" role="button" aria-expanded="false" aria-controls="collapseExample"> Click me please! </a> </p> <div class="collapse" id="collapseExample"> <div> Ooh, you clicked! </div> </div>
You need a lot of attributes to make it work, and it's easy to forget them or mismatch the
id and the
href. The type of problem that's sitting right in front of you but for some reason takes you absolutely ages to see.
We've now been saved from having to use tons of attributes and ids/hrefs to make our accordions work, thanks to the
I'm not sure how long it's been around, but a colleague has just shown it to me and it's magical. It works like this.
<details> <summary>Accordion title</summary> Content you want to show/hide. </details>
It starts with a
<detail> element, which has a
<summary> element nested within it, as well as whatever content you want to show/hide. Whatever is inside the
<summary> element shows as the accordion title, and anything else is shown/hidden when the title is clicked. You'll probably want to do some styling, but the opening/closing is all handled for you.
Another cool feature of this element is that is supports the
toggle event whenever the element is opened or closed. Perhaps you'd like to show a cool animation? The world is your oyster!
I've put together a very basic example here.
The Detail element currently has around 95% browser support, with only IE11 being the only major browser not supporting it. More detailed information on the level of support can be found here.
You can read about the Detail element further at MDN.