Michael McGrorty
Michael's Blog

Michael's Blog

Pure HTML Accordion

Michael McGrorty's photo
Michael McGrorty
·Aug 25, 2020·

3 min read

Accordions

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.

Details Element

We've now been saved from having to use tons of attributes and ids/hrefs to make our accordions work, thanks to the <detail> element!

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.

Events

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!

Example

I've put together a very basic example here.

Support

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.

Further Reading

You can read about the Detail element further at MDN.

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/details

 
Share this