Skip to content
Tutorials Center
My learning

Topics

Lesson 48 of 56 ยท Projects

Project: Tabs and Accordion Components

Build two reusable jQuery plugins, an accessible tabs widget and a slide accordion, with ARIA roles, keyboard support and configuration through data attributes.

Tabs and accordions are the two most copied widgets on the web, and also two of the most often broken ones. Many versions work with a mouse and fail for everyone else: you cannot reach them with the keyboard, a screen reader announces a pile of unrelated links, and the markup does nothing without JavaScript. In this project you will build both widgets as small jQuery plugins that fix those problems, and you will practise most of what the plugin lesson taught.

Each plugin follows the same recipe: plain, meaningful HTML as the starting point; a $.fn method that enhances it; settings that come from defaults, data-* attributes and an options object; and event handlers that live in a namespace so the widget can be taken apart again. By the end you will have roughly 60 lines of code per widget that you could drop into a real page.

What a tabs widget must expose

Roles tablist, tab and tabpanel tell assistive tech what each piece is.
Relationships aria-controls links a tab to its panel; aria-labelledby links back.
State aria-selected marks the active tab.

Roles name the parts, relationships connect them, state says what is current.

1 / 3

Step 1: the tabs markup

Start with the HTML, because everything else enhances it. The tab list holds buttons (not links, since they do not navigate anywhere), and each button points to its panel by id.

HTML
<div class="tabs" data-active="0">
  <div role="tablist" aria-label="Product details">
    <button role="tab" id="t-overview" aria-controls="p-overview">Overview</button>
    <button role="tab" id="t-specs" aria-controls="p-specs">Specs</button>
  </div>
  <div role="tabpanel" id="p-overview" aria-labelledby="t-overview">...</div>
  <div role="tabpanel" id="p-specs" aria-labelledby="t-specs">...</div>
</div>

The roles and the aria-controls / aria-labelledby pairs are written in the HTML on purpose. The plugin only has to manage the changing parts: which tab is selected, which panel is hidden and which tab is in the Tab order. Keeping the static facts in markup also makes the widget easy to read and to test.

Step 2: the tabs plugin

The plugin follows the standard shape: a function on $.fn that returns this.each(...), so it can be chained and works on several widgets at once. The heart of it is one function, select(index), that puts the widget into the right state. Everything else (clicks, keys, the initial state) just calls it.

Settings are merged with $.extend in order of increasing priority: defaults, then the element's data-* attributes ($root.data() reads them all and converts "1" to the number 1), then the options passed in code.

The keyboard handler uses the arrow keys with wrap-around. After moving the selection we also call .trigger("focus") on the new tab, because focus must follow the selection for keyboard users.

A tabs plugin with ARIA and arrow keys

A few details are worth pausing on.

  • Roving tabindex. Only the selected tab has tabindex="0"; the others get -1. Pressing Tab from outside moves into the tab list once and then straight on to the panel, instead of stopping at every tab. The arrow keys do the navigating inside the list.
  • .attr("aria-selected", isActive) receives a boolean and writes the string "true" or "false", which is exactly what ARIA expects. Compare this with attributes versus properties: aria-* values are attributes, so .attr() is the right tool, while hidden is a real boolean property and gets .prop().
  • Delegated handlers. The handlers hang on the widget root and filter by [role="tab"], so tabs added later would also work, and a single .off(".tabs") removes everything. See event delegation.
  • Priority of settings. Because $.extend copies from left to right, data-active="1" beats the default, and an active option in code beats the attribute. That is the usual contract for configurable widgets.

Always put data- attributes in the HTML, but read them with .data() only for initial configuration. After the widget starts, keep its changing state in ARIA attributes or in your own closure variables, so the page and the widget never disagree.

Step 3: the accordion markup

An accordion is a stack of sections, each with a heading and a panel. The heading contains a button; that button carries aria-expanded and points at its panel with aria-controls.

HTML
<div class="accordion" data-single="true">
  <h3><button aria-expanded="false" aria-controls="a1">Shipping</button></h3>
  <div id="a1">...</div>
</div>

Using real headings keeps the document outline meaningful, and a real <button> gives you Enter and Space for free. You do not need to write any keyboard code for it, which is the main reason accordions are easier than tabs.

Step 4: the accordion plugin

The open or closed state lives in aria-expanded, and the panel follows it. The function toggle($button, open) does both and animates with .slideDown() and .slideUp(). The option single (read from data-single) closes the other sections when one opens, which turns the widget into an exclusive accordion.

One subtle point is rapid clicking. If someone clicks a header five times quickly, five animations queue up and the panel keeps wobbling after the clicks stop. Calling .stop(true, true) first finishes the current animation and clears the queue; the animation queue lesson explains why.

An accordion plugin with slide animation

Notice that the markup says data-single="true", but the code asks $root.data() for it and gets the real boolean true, not the string. That is jQuery's data type conversion at work. It also means data-single="false" really gives false, whereas a plain .attr("data-single") would give the truthy string "false", a classic bug.

The small public object stored with $root.data("accordion", {...}) shows the usual way for a plugin to expose a few methods without polluting $.fn with more names. The checkbox in the demo uses it to switch mode at runtime.

Step 5: making the widgets robust

Before you put plugins like these into production, run through a short review.

  1. Progressive enhancement. The tabs markup shows every panel if JavaScript fails, which is acceptable. The accordion hides panels from script, so without JavaScript every section stays readable. If you hid them with CSS instead, a script failure would lock content away.
  2. Cleanup. Both plugins use the .tabs and .accordion event namespaces. A destroy method would call $root.off(".tabs"), remove the generated tabindex and aria-selected attributes and unhide the panels. Add it whenever widgets can be removed from a page while it stays open.
  3. Unique ids. The markup repeats id values by hand. If you create widgets from templates, generate ids from a counter so two widgets never clash.
  4. Several instances. Because all state is inside the .each() closure, two tab widgets on one page cannot interfere. Test that with two instances whenever you write a plugin.
  5. Reduced motion. Users who ask their system to reduce motion should not get slide animations. You can read window.matchMedia("(prefers-reduced-motion: reduce)").matches and set settings.speed to 0 when it is true.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why do only the selected tab and no other tab have tabindex="0" in the tabs widget?

    This is the roving tabindex pattern. The Tab key stops once in the list, and the arrow keys move the selection (and focus) inside it.
  2. 2. In the plugin, which order of priority does $.extend({ active: 0 }, $root.data(), options) give?

    $.extend copies from left to right, so later sources overwrite earlier ones. The options passed in code have the final say.
  3. 3. Why does the accordion call .stop(true, true) before sliding a panel?

    Without it, repeated clicks queue several slide animations and the panel keeps moving after the clicks have stopped.
  4. 4. Which method is the right one for toggling aria-expanded on a button?

    aria-* are attributes without a matching DOM property, so .attr() is correct. Passing a boolean writes the string "true" or "false".

Summary

  • Start from meaningful HTML with roles and relationships written in the markup; let the plugin manage only the changing state.
  • Tabs need role values, aria-selected, aria-controls, a roving tabindex and arrow, Home and End keys that also move focus.
  • Accordions need real headings, real buttons and aria-expanded; Enter and Space then work for free.
  • Merge settings as defaults, then data-* attributes, then options, and expose a small object through .data() if the widget needs methods.
  • Use a delegated, namespaced handler on the root so the widget can be cleaned up with one .off(".namespace").
  • Stop running animations with .stop(true, true) before starting new ones.

Next, build a filtering and sorting data table in Project: Live Search and Sortable Table.