sustainable.dev Menu

Posted to Resource on December 28, 2020


Easy accordions without JavaScript

Did you know you can create an expandable content section with just the <details> HTML element? Did you know that with just one additional HTML element you can make that expandable section into an accordion with a dedicated title?

It’s in the details

The <details> element has been around for a little while now. It is supported across all modern browsers, yet many accordion systems still use JavaScript to create the expand-for-more interaction.

<details>
	<p>This is expandable content!</p>
</details>

 

Summerising the content

To give more context to the hidden content within the dropdown, you can add the <summary> element as the first element within your <details> element. Summerise the content with a short title, and whoila, you have yourself an accordion with a title.

<details>
	<summary>Accordion title</summary>
	<p>This is expandable content!</p>
</details>
<details>
	<summary>Accordion two title</summary>
	<p>This is also expandable content!</p>
</details>

Take a look at the CodePen example here.

 

Other possible uses for details

Another idea to avoid additional JavaScript for common website interactions could be to use <details> to create a simple dropdown navigation structure. This allows you to create a simple menu that also doesn’t need JavaScript to open and close.

<details>
	<summary>Menu</summary>
	<nav role="navigation">
		<ul>
			<li>
				<a href="#" title="Link one">Link one</a>
			</li>
			<li>
				<a href="#" title="Link two">Link two</a>
			</li>
			<li>
				<a href="#" title="Link three">Link three</a>
			</li>
		</ul>
	</nav>
</details>

Take a look at the CodePen example here.

 

Conclusion

So should you use <details>? The short answer is yes, why not? It is well supported semantic HTML designed for creating expandable areas of content. Plus, you can save yourself some JavaScript, albeit a small amount, but every byte counts!