Table of Contents
Creating accessible web components is essential for ensuring that all users, including those with disabilities, can navigate and interact with your website effectively. One common UI pattern is the accordion, which allows users to expand and collapse sections of content. In this article, we’ll explore how to build an accessible accordion component using JavaScript and ARIA roles.
Understanding Accessibility and ARIA Roles
ARIA (Accessible Rich Internet Applications) roles provide additional information to assistive technologies about the purpose of elements on a webpage. For an accordion, proper ARIA roles and attributes ensure screen readers can interpret the component correctly.
Key ARIA Roles and Attributes for Accordion
- button: The element that toggles the visibility of the content.
- region: The container for each accordion panel.
- aria-expanded: Indicates whether the accordion panel is expanded or collapsed.
- aria-controls: Links the button to its associated content panel.
- aria-labelledby: Associates the panel with its label.
Building the HTML Structure
Start by creating the HTML structure for the accordion. Use <button> elements for toggles and <div> for content panels. Assign appropriate ARIA attributes to ensure accessibility.
Here’s a simple example:
<div class="accordion">
<div class="accordion-item">
<button class="accordion-header" aria-expanded="false" aria-controls="panel1" id="label1">Section 1</button>
<div id="panel1" role="region" aria-labelledby="label1" hidden>
<p>Content for section 1.</p>
</div>
</div>
<div class="accordion-item">
<button class="accordion-header" aria-expanded="false" aria-controls="panel2" id="label2">Section 2</button>
<div id="panel2" role="region" aria-labelledby="label2" hidden>
<p>Content for section 2.</p>
</div>
</div>
</div>
Adding JavaScript Functionality
Next, add JavaScript to handle toggle actions. When a button is clicked, update aria-expanded and show or hide the corresponding content panel.
document.querySelectorAll('.accordion-header').forEach(button => {
button.addEventListener('click', () => {
const expanded = button.getAttribute('aria-expanded') === 'true';
button.setAttribute('aria-expanded', String(!expanded));
const panelId = button.getAttribute('aria-controls');
const panel = document.getElementById(panelId);
if (expanded) {
panel.setAttribute('hidden', '');
} else {
panel.removeAttribute('hidden');
}
});
});
Best Practices for Accessibility
To ensure your accordion is fully accessible:
- Use semantic HTML elements like
<button>for toggles. - Properly associate labels and content with ARIA attributes.
- Manage focus states for keyboard navigation.
- Ensure that all interactive elements are reachable via keyboard.
Implementing these practices will make your accordion component accessible and user-friendly for everyone.