Stop Writing JavaScript for Accordions: The Native HTML Details Tag Guide
You are over-engineering a solved problem. If you are writing 20 lines of JavaScript just to toggle a dropdown text, you are doing it wrong.
We have all done it. You need an FAQ section where questions expand when clicked. So, you write HTML divs, add CSS classes for `display: none` and `display: block`, and then write a JavaScript function to listen for clicks, toggle classes, and manage state.
This is the old way. It is heavy, it breaks if JavaScript fails, and it is often inaccessible to screen readers unless you carefully manage ARIA labels.
The solution? The Native HTML5 Accordion.
<details> and <summary> tags. These two elements create a fully functional, interactive accordion with zero JavaScript. The browser handles the logic for you.
How It Works
The syntax is incredibly simple. You wrap everything in the `details` tag. The part you want to always be visible (the clickable title) goes inside the `summary` tag. Everything else inside the `details` tag is hidden by default.
That is it. No ID's. No functions. No event listeners. When the user clicks the summary, the browser automatically toggles the `open` attribute on the details element.
Why This Is Better Than JavaScript
Aside from saving you time, there are three major benefits:
- Performance: It requires 0 bytes of script execution. It renders instantly.
- Resilience: It works even if the user has disabled JavaScript or if your main bundle crashes.
- Accessibility (a11y): It is semantic HTML. Screen readers instantly know this is an expandable widget. You get keyboard navigation (Tab and Enter) for free.
Customizing the "Ugly Triangle"
By default, the browser adds a small black triangle marker next to the summary text. Most designers hate this. The good news is, you can remove it or replace it with CSS.
To remove the marker:
To add your own custom icon (like a Plus + or an Arrow ->) that rotates when open, you can target the open state in CSS:
When Should You Still Use JavaScript?
The native tag is perfect for 95% of use cases. However, if you need a "connected" accordion—where opening one item automatically closes all the others—you will need a tiny bit of JavaScript to manage that exclusive state.
But for simple dropdowns, spoilers, or FAQ sections? Native wins every time.

Comments
Post a Comment