Responsive, accessible and animated FAQ using native HTML elements
Design comparison
Solution retrospective
Making accordions is now very simple using built in HTML elements such as and
.
š This approach offers several advantages:
- built-in semantic elements
- natively accessible so it does not require additional ARIA attributes)
- does not require any JavaScript to handle user interaction
It is however a little bit more challenging to animate the accordion's state transition (expanded/collapsed), which requires some JavaScript trick š
What challenges did you encounter, and how did you overcome them?The main challenge was to animate the accordion's state transition (expanded/collapsed).
The reason is that interacting with the accordion automatically toggles an open
attribute which cannot be animated (same problem as trying to animate to/from a display: none
property).
One solution consists in delaying the default behavior to first apply the desired animation or transition.
In this implementation, I use JavaScript to add a custom expanded
attribute on the accordion's panel styled with CSS transition. This serves as an intermediate transient state.
When transitioning from the collapsed to the expanded state, I simply used a setTimeout()
function to asynchronously add the expanded
attribute. This ensures the open
attribute is set first prior to running the animation. This seems to be enough to do the trick.
Transitioning from the expanded to the collapsed state requires a bit more fiddling. The default behavior is to remove the open
attribute from the `` HTML element, which removes the accordion's panel from the DOM thus skipping any animation. The hack consists in:
- preventing this default behavior using:
e.preventDefault()
- removing the custom
expanded
attribute which runs the CSS animation - waiting for the animation to end prior to resuming to the default behavior:
addEventListener('transitionend', () => { ... }, { once: true })
Community feedback
Please log in to post a comment
Log in with GitHubJoin our Discord community
Join thousands of Frontend Mentor community members taking the challenges, sharing resources, helping each other, and chatting about all things front-end!
Join our Discord