Accordion

Build an accessible accordion component with smooth animations and keyboard support

Learn to build a simple yet powerful accordion component for collapsible content panels. Perfect for FAQs, settings panels, and content organization.

What We're Building

An accordion that supports:

  • Expand/collapse panels

  • Single or multiple panels open

  • Smooth animations

  • Keyboard navigation

  • Accessible with ARIA attributes

  • Customizable styling

Component Code

accordion.ts

import { bindable } from 'aurelia';

export class Accordion {
  @bindable allowMultiple = false;
  @bindable openPanels: number[] = [];

  togglePanel(index: number) {
    if (this.allowMultiple) {
      // Multiple panels can be open
      const panelIndex = this.openPanels.indexOf(index);
      if (panelIndex > -1) {
        this.openPanels.splice(panelIndex, 1);
      } else {
        this.openPanels.push(index);
      }
    } else {
      // Only one panel can be open
      if (this.isPanelOpen(index)) {
        this.openPanels = [];
      } else {
        this.openPanels = [index];
      }
    }
  }

  isPanelOpen(index: number): boolean {
    return this.openPanels.includes(index);
  }
}

accordion.html

accordion-panel.ts

accordion-panel.html

accordion.css

Usage Examples

Basic Accordion (Single Panel Open)

Multiple Panels Open

Controlled Open Panels

With Rich Content

Testing

Accessibility Features

This accordion implements WCAG 2.1 guidelines:

  • ✅ ARIA Attributes: aria-expanded indicates panel state

  • ✅ Keyboard Support: Enter and Space keys toggle panels

  • ✅ Focus Management: Buttons are focusable with visible focus indicators

  • ✅ Semantic HTML: Uses <button> for interactive headers

Enhancements

1. Add Animation Callbacks

2. Add Icons

3. Add Lazy Loading

Best Practices

  1. Animation Performance: Use max-height instead of height: auto for smooth transitions

  2. Content Height: Set reasonable max-height values or calculate dynamically

  3. Accessibility: Always include aria-expanded for screen readers

  4. Focus Visible: Ensure keyboard focus is clearly visible

  5. Mobile: Test touch interactions and ensure adequate tap targets

Summary

You've built a fully-functional accordion with:

  • ✅ Single and multiple panel modes

  • ✅ Smooth animations

  • ✅ Keyboard support

  • ✅ Accessible markup

  • ✅ Easy customization

This accordion is ready for FAQs, settings panels, and any collapsible content!

Last updated

Was this helpful?