outwest.dev

VueAccessibilityComponent

Building an accessible accordion component with Vue (Part 1)

· Updated · 12 min read

Accordions are a common UI pattern used to manage content in a collapsible and expandable manner. They are especially useful when dealing with a large amount of information that needs to be organized and presented in a structured way. However, when implementing accordions, it's crucial to ensure accessibility for all users, including those who rely on assistive technologies like screen readers or keyboard navigation. In this blog post, we'll walk through the process of creating an accessible accordion component using Vue 3, and in Part 2 we'll write unit tests to verify its functionality.

Gather Requirements

Before we begin, it's essential to gather some information about the accessibility (a11y) requirements for an Accordion component. Fortunately, w3.org provides valuable insights for us. After reviewing the Accordion Pattern guidelines, we can summarize the following key points:

Accordions have two primary sections

  • Accordion Header: Label for or thumbnail representing a section of content that also serves as a control for showing, and in some implementations, hiding the section of content.
  • Accordion Panel: Section of content associated with an accordion header.

A11y Requirements

Looking at the keyboard interactions required we will need to support the following movements:

  • Enter or Space will expand the content (panel) and can also close it
  • Tab moves focus to the next focusable element, including the headers
  • Down Arrow (optional) - Moves focus to the next header
  • Up Arrow (optional) - Moves focus to the previous header
  • Home (optional) - Moves focus to the first header
  • End (optional) - Moves focus to the last header

We will also need to support the following ARIA properties:

  • aria-expanded - set on the button, true/false depending on the state of the panel (open/closed)
  • aria-controls - set on the button to refer to the panel it shows and hides
  • aria-labelledby - set on the panel to refer to the button that controls display of the panel
  • role=region - set on the panel to show panel as a container

At this point, I would like to bring attention to the fact that W3 doesn't recommend using aria-hidden. This is somewhat dependent on the implementation of the component and how we are showing/hiding the panels. The following quote is from MDN, and describes when not to use aria-hidden.

aria-hidden="true" should not be added when:

  • The HTML hidden attribute is present
  • The element or the element's ancestor is hidden with display: none
  • The element or the element's ancestor is hidden with visibility: hidden

You can also view the example directly from the W3C and notice it uses the hidden attribute to hide closed panels, not aria-hidden. We'll do the same.

The Component

When building a component, I usually prefer to begin by defining the API that developers would utilize to configure the component. This practice enables me to identify any potential shortcomings early in the development process.

For an accordion, one option is two components, an AccordionGroup and an Accordion, which favors composition over props. The cost is that every consumer has to learn how the two relate, and we have to document it. Instead, I prefer one component that takes an array of sections and exposes a named slot for each heading and panel. Simple sections stay a one-liner, and complex sections still get full control over their markup.

Define Props and State

We will be using the Vue 3 Composition API via the <script setup> tag for the following code. The useId helper needs Vue 3.5 or later.

import { ref, useId } from 'vue'

const props = defineProps({
  sections: { type: Array, required: true },
  headingAs: { type: String, default: 'h3' },
  initialOpen: { type: String },
})

const uid = useId()
const headingId = (section) => `${uid}-${section.slug}-heading`
const panelId = (section) => `${uid}-${section.slug}-panel`

const buttons = []
const expandedIndex = ref(
  props.sections.findIndex((section) => section.slug === props.initialOpen)
)

So far we have defined the props our component will use. Let's go over these a bit:

  • sections - An array of objects with a slug, heading and content, which define our accordion sections.
  • headingAs - An optional prop that defines the HTML element used for our heading.
  • initialOpen - An optional prop with the slug of a panel to open on initial render.

Next let's talk about the state:

  • uid - A unique id from Vue's useId. We prefix every element id with it, so two accordions on the same page can't produce duplicate ids, even if their sections share slugs. Duplicate ids would point aria-labelledby at the wrong button.
  • buttons - The button elements, in order. We'll fill this from the template, and use it to move focus.
  • expandedIndex - Which panel is open, or -1 for none. We set it straight from initialOpen, so the right panel is open on the first render with no flash.

Markup

<template>
  <div
    class="accordion-group"
    data-test-id="accordion-group"
  >
    <div
      class="accordion"
      v-for="(section, index) in sections"
      :key="section.slug"
    >
      <component
        class="accordion-heading"
        :is="headingAs"
      >
        <button
          class="accordion-button"
          type="button"
          :ref="(el) => (buttons[index] = el)"
          :id="headingId(section)"
        >
          <slot :name="`${section.slug}-heading`">
            {{ section.heading }}
          </slot>
        </button>
      </component>

      <div
        class="accordion-panel"
        :id="panelId(section)"
      >
        <slot :name="`${section.slug}-content`">
          {{ section.content }}
        </slot>
      </div>
    </div>
  </div>
</template>

The markup is pretty straightforward. We are building the accordion with a parent wrapper accordion-group, and we give it a data-test-id that we will use in our unit tests in Part 2.

Next is the use of the component element with :is. We are using this here so we can change the element for our heading. By default, this will be an h3, but to maintain semantic markup, we might need to use an h2, h4, etc.

On each button we use a function ref to store the element at its index. Vue does support a plain ref on an element inside v-for, but it doesn't guarantee the array is in the same order as the source. For keyboard navigation the order is the whole point, so we set it ourselves.

In the button and accordion-panel elements, you'll notice we use named slots with the provided slug. This helps us assemble our component in a flexible way, adhering to the composition over props concept. I appreciate this approach because it offers us options. For instance, if we have simple text sections, we can set them up quickly by just using an array of objects. However, if we need more complicated layouts for each section, we can now utilize these slots. We simply use {slug}-heading or {slug}-content depending on our requirements.

Opening and Closing Panels

const togglePanel = (index) => {
  expandedIndex.value = expandedIndex.value === index ? -1 : index
}

If the panel at index is already open, we close it by setting expandedIndex to -1. Otherwise we open it, which also closes whichever panel was open before.

Let's bind it to the button with @click, and use the hidden attribute to show only the open panel:

<button
  class="accordion-button"
  type="button"
  :ref="(el) => (buttons[index] = el)"
  :id="headingId(section)"
  @click="togglePanel(index)"
>
<div
  class="accordion-panel"
  :id="panelId(section)"
  :hidden="expandedIndex !== index"
>

It's worth explaining why this is click and not pointerup or keydown. A native <button> fires click for a mouse click, a tap, Enter, Space, and when a screen reader activates it. Screen readers don't send pointer or key events for that last one, so a pointerup handler leaves those users unable to open a panel. Using click on a real <button> gets us all of those for free, and we don't need any code for the Enter and Space requirements.

By now, your accordion should be working, showing and hiding the panels when you click the buttons or press Enter or Space on them.

Keyboard Events

So back in the a11y requirements, we noted which keyboard events we will need to support. Tab, Enter and Space come from the browser, so we only need to handle the optional focus movement keys:

const focusButton = (index) => {
  const count = props.sections.length
  buttons[(index + count) % count].focus()
}

const handleKeyDown = (event, index) => {
  const targets = {
    Home: 0,
    End: props.sections.length - 1,
    ArrowUp: index - 1,
    ArrowDown: index + 1,
  }
  const target = targets[event.key]
  if (target === undefined) return

  event.preventDefault()
  focusButton(target)
}

The template passes in the index of the button that received the key, so we don't need to track which button has focus. We look up where focus should go for the pressed key, and do nothing for any other key. focusButton wraps around with the remainder operator: from the last button, ArrowDown moves to the first, and from the first, ArrowUp moves to the last.

We only call event.preventDefault() for the keys we handle. You might think we should move it to the top of the method or use .prevent on the event handler, but by doing either of these, we would break Tab, Enter, Space and any other key. This way, we only prevent the default action for the keys we are looking for.

So now let's bind it on the button:

<button
  class="accordion-button"
  type="button"
  :ref="(el) => (buttons[index] = el)"
  :id="headingId(section)"
  @click="togglePanel(index)"
  @keydown="handleKeyDown($event, index)"
>

I've opted to use keydown rather than keyup in this scenario. The rationale behind this choice is to prevent inadvertent scrolling of the page when the Home, End or arrow keys are pressed. If we were to bind to keyup, the browser would already have scrolled the page, potentially shifting the accordion out of view while maintaining focus. By using keydown, we intercept these key events before the default action (scrolling) occurs, ensuring that the accordion remains in view and focused.

ARIA Support

Finally, we need to add the ARIA attributes from the a11y requirements. These play a crucial role for users who rely on assistive technologies: they announce whether each section is expanded, and link each button to the panel it controls.

<button
  class="accordion-button"
  type="button"
  :ref="(el) => (buttons[index] = el)"
  :id="headingId(section)"
  :aria-expanded="expandedIndex === index"
  :aria-controls="panelId(section)"
  @click="togglePanel(index)"
  @keydown="handleKeyDown($event, index)"
>
  <slot :name="`${section.slug}-heading`">
    {{ section.heading }}
  </slot>
</button>

<!-- other markup -->

<div
  class="accordion-panel"
  role="region"
  :id="panelId(section)"
  :aria-labelledby="headingId(section)"
  :hidden="expandedIndex !== index"
>
  <slot :name="`${section.slug}-content`">
    {{ section.content }}
  </slot>
</div>

Here's the finished component:

TheAccordion.vue
<template>
  <div
    class="accordion-group"
    data-test-id="accordion-group"
  >
    <div
      class="accordion"
      v-for="(section, index) in sections"
      :key="section.slug"
    >
      <component
        class="accordion-heading"
        :is="headingAs"
      >
        <button
          class="accordion-button"
          type="button"
          :ref="(el) => (buttons[index] = el)"
          :id="headingId(section)"
          :aria-expanded="expandedIndex === index"
          :aria-controls="panelId(section)"
          @click="togglePanel(index)"
          @keydown="handleKeyDown($event, index)"
        >
          <slot :name="`${section.slug}-heading`">
            {{ section.heading }}
          </slot>
        </button>
      </component>

      <div
        class="accordion-panel"
        role="region"
        :id="panelId(section)"
        :aria-labelledby="headingId(section)"
        :hidden="expandedIndex !== index"
      >
        <slot :name="`${section.slug}-content`">
          {{ section.content }}
        </slot>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, useId } from 'vue'

const props = defineProps({
  sections: { type: Array, required: true },
  headingAs: { type: String, default: 'h3' },
  initialOpen: { type: String },
})

const uid = useId()
const headingId = (section) => `${uid}-${section.slug}-heading`
const panelId = (section) => `${uid}-${section.slug}-panel`

const buttons = []
const expandedIndex = ref(
  props.sections.findIndex((section) => section.slug === props.initialOpen)
)

const togglePanel = (index) => {
  expandedIndex.value = expandedIndex.value === index ? -1 : index
}

const focusButton = (index) => {
  const count = props.sections.length
  buttons[(index + count) % count].focus()
}

const handleKeyDown = (event, index) => {
  const targets = {
    Home: 0,
    End: props.sections.length - 1,
    ArrowUp: index - 1,
    ArrowDown: index + 1,
  }
  const target = targets[event.key]
  if (target === undefined) return

  event.preventDefault()
  focusButton(target)
}
</script>

What I'd Change Next

  • Allow several panels open at once. The W3C pattern allows it, and some content reads better that way. That means swapping expandedIndex for a Set of open indexes, and is a good reason to keep the toggle logic in one function.
  • Make initialOpen reactive. It's read once on setup, which is right for most pages. If a parent needs to open a panel later, a v-model would be the cleaner API.
  • Test it with a real screen reader. Unit tests can check attributes, but only VoiceOver or NVDA will tell you how it actually sounds.

In Part 2, we will cover writing unit tests for the accordion component.

View Demo on Vue SFC Playground

View Repo With Source