Did you know you can create an accordion with zero JavaScript? Let’s explore how.
The secret lies in using the HTML <details> element combined with a name attribute. This attribute ensures that when you open one item, any previously open item will automatically close, creating the accordion effect.
Example Code
Below is a simple implementation of a multi-item accordion using only HTML:
<details name="faq">
<summary>Graduation Requirements</summary>
<p>
Requires 40 credits, including a passing grade in health, geography,
history, economics, and wood shop.
</p>
</details>
<details name="faq">
<summary>System Requirements</summary>
<p>
Requires a computer running an operating system. The computer must have some
memory and ideally some kind of long-term storage. An input device as well
as some form of output device is recommended.
</p>
</details>
<details name="faq">
<summary>Job Requirements</summary>
<p>
Requires knowledge of HTML, CSS, JavaScript, accessibility, web performance,
privacy, security, and internationalization, as well as a dislike of
broccoli.
</p>
</details>
How It Works
Each <details> element can be expanded or collapsed by clicking on its <summary> child. Adding a name attribute to each <details> element groups them together, so only one item can be open at a time. This technique enables a fully functional accordion without any JavaScript or external libraries.
Benefits
- Simpler Codebase: No need for JavaScript, making the code easier to read and maintain.
- Accessibility: Native browser support ensures better accessibility out-of-the-box.
- Performance: Eliminates the overhead of running JavaScript for basic UI interactions.
Live Demo
Check out this live demo.
Top comments (2)
Nice tip! I always love simple content with standards as first-class citizen
And there are many more