Skip to content

Use Less Javascript - Accordion

Published on .
At 324 words, this article should take about 2 minutes to read.

All too often I have seen developers reach for JavaScript to solve a problem when they do not need to. Welcome to Use Less JavaScript - an irregular series on native HTML5 elements you can use instead!

Showing and hiding content on the page has its advantages; think questions and answers on an FAQ page or, as Andy Bell did, showing less webmentions when you're too popular!

Enter our new power couple; details and summary!

The details element contains all of the content that will be hidden.

The summary element sits inside it and is visible whether the details element is expanded or not. The summary element also provides a handy icon to indicate whether the details element is open - and let the user know this is a 'clickable' element - affordance, wooo!

Especially good news in that, because these are well-supported HTML5 elements, we get accessibility out of the box! This means we don't have to write a load of JavaScript to handle keyboard control (for example) or, as is most common, just ignore it!

Your basic structure looks like this;

<strong>Africa</strong> by Toto
<p>I hear the drums echoing tonight</p>
<p>But she hears only whispers of some quiet conversation</p>
<p>She's coming in, 12:30 flight</p>
<p>Her moonlit wings reflect the stars that guide me towards salvation</p>
<p>I stopped an old man along the way</p>
<p>Hoping to find some old forgotten words or ancient melodies</p>
<p>He turned to me as if to say</p>
<p>"Hurry, boy, it's waiting there for you"</p>

Grand! Now we can get styling!

summary::marker {
content: "\2192";
color: red;

details[open] summary::marker {
content: "\2193";

The little triangle/arrow can be styled using the ::marker pseudo-class in much the same way as ::before and ::after can be.

If, however, you want to get super jazzy check out this CodePen

See the Pen Use less JavaScript: Accordions by Thomas Rigby (ツ) (@hryggrbyr) on CodePen.



In almost all cases, the comments section is a vile cesspool of Reply Guys, racists, and bots.

I don't want to have to deal with that kind of hell so I don't have a comments section.

If you want to continue the conversation, you can always hit me up on CalcKey (which is not a vile cesspool of Reply Guys, racists, and bots).