Blog

Expanding Menu with jQuery and CSS: Accessible Accordion Navigation

jQuery expanding navigation accordion with plus and minus indicators and a visible focus ring

Expanding Menu with jQuery and CSS: Accessible Accordion Navigation

Create an expanding menu with jQuery by toggling a submenu’s hidden state and its heading button’s aria-expanded value together. Use native buttons to open sections and real links for navigation. This example allows one open section at a time and lets the open section collapse when selected again.

The responsive accordion includes keyboard controls, visible focus, decorative plus/minus indicators, a reduced-motion fallback and readable navigation without JavaScript. The complete source ZIP runs offline with local jQuery.

Try the expanding menu live demo

Expanding navigation playground

Open a topic to reveal its links. Opening another topic closes the previous one; selecting the open heading again collapses it. Try Enter, Space and Tab. Escape closes the current section and returns focus to its heading.

One section can be open, and all sections may be closed. Collapsed links are removed from normal keyboard navigation. If JavaScript or jQuery is unavailable, every topic and link stays visible.

Choose an accordion for grouped navigation

An accordion is a stack of headings that reveal or hide related content. In this menu, each panel contains a short list of destinations. The heading button changes visibility; the links navigate. Keeping these two purposes separate avoids a control that unpredictably both opens a panel and changes pages.

The WAI-ARIA accordion pattern describes heading buttons connected to panels with expanded states. This example uses ordinary link lists inside those panels, rather than an ARIA menu widget.

1. Add heading buttons and real submenu links

<nav aria-label="Tutorial topic navigation">
  <h3>
    <button type="button" id="topic-css"
            aria-expanded="false" aria-controls="panel-css">
      CSS tutorials <span aria-hidden="true">+</span>
    </button>
  </h3>
  <ul id="panel-css" hidden>
    <li><a href="/css-tutorial/">CSS tutorial</a></li>
    <li><a href="/button-tutorial/">Button tutorial</a></li>
  </ul>
</nav>

This short excerpt shows the enhanced relationship. Use destinations that exist in your project. In the complete source, the initial HTML starts with readable panels, hidden buttons and visible plain titles; the script creates the collapsed state only after it can attach the controls successfully.

Match every aria-controls value to exactly one panel ID. Use a heading level that fits the surrounding page. The published demo uses headings below its own title, while a standalone sidebar may need a different level.

2. Style the headings, links and focus indicators

.topic-button {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  min-height: 62px;
  padding: 18px 22px;
  border: 0;
  background: #183154;
  color: white;
  text-align: left;
  cursor: pointer;
}
.topic-button[aria-expanded="true"] { background: #2455d9; }
.topic-button:focus-visible {
  outline: 3px solid #cfbaff;
  outline-offset: -5px;
}
.submenu a { display: block; min-height: 48px; padding: 12px 22px; }
[hidden] { display: none !important; }

The expanded color is an additional cue, not the only state indicator. A decorative plus changes to a minus, and the button exposes its state programmatically. The source scopes every style to the component so a generic hidden rule or button selector does not alter unrelated content.

An inset focus outline avoids clipping at the rounded container’s edge. Give submenu links their own focus style as well. Keep labels large enough to read, allow them to wrap and avoid fixed heights that cut off longer translated names.

3. Synchronize expanded state and panel visibility

Use one function to update both sides of the relationship. A panel that looks closed must not leave its links in the keyboard order. If focus is inside a panel when it closes, return focus to its controlling button first.

function setSection(button, panel, open) {
  if (!open) {
    if (panel.contains(document.activeElement)) button.focus();
  }
  $(button).attr('aria-expanded', open ? 'true' : 'false');
  $(panel).prop('hidden', !open).toggleClass('is-open', open);
}

The jQuery prop() reference describes reading or setting DOM properties. Here, hidden is set as a Boolean property. The aria-expanded attribute is updated with the strings true or false. Do not treat the presence of a string such as hidden=”false” as meaning visible.

4. Toggle the clicked section and close the others

$buttons.on('click', function () {
  var index = $buttons.index(this);
  var open = $(this).attr('aria-expanded') !== 'true';
  $buttons.each(function (i) {
    if (i !== index) setSection(this, $panels[i], false);
  });
  setSection(this, $panels[index], open);
});

Read the clicked button’s state before closing any sections. This preserves the important second-click behavior: selecting an open heading closes it, leaving all sections collapsed. Selecting a different heading closes the previous panel and opens the chosen one.

The event handler uses the current component’s button and panel collections. Keep their order consistent, or use an explicit ID lookup when adapting the structure. The complete source also guards against initializing the same component twice.

5. Support the keyboard with native controls

Enter and Space activate a focused heading button. Tab and Shift+Tab traverse the headings and links in the page’s normal order. Closed links are hidden, so they are skipped. No custom arrow-key behavior is required for this basic implementation.

The demo adds Escape as a convenience: from an open section’s heading or one of its links, it closes that section and focuses its heading. It does not intercept Escape elsewhere in the page or close unrelated components.

// Inside the component keydown handler:
if (event.key === 'Escape') {
  // Find the current section and confirm it is expanded.
  // Then close it through the same state function.
  setSection(button, panel, false);
  button.focus();
}

The full source supplies the section lookup and checks before handling Escape. Avoid hiding a focused link without moving focus to a visible control. Also avoid changing the open section just because a user tabs onto a heading; focus and activation are separate actions.

6. Use a short opening effect and reduced-motion fallback

The menu opens with a small opacity and three-pixel entry effect. Closing takes effect immediately, so links do not remain interactive during a queued closing animation. There are no height-animation timers to compete during rapid clicks.

@keyframes panel-enter {
  from { opacity: .45; transform: translateY(-3px); }
  to { opacity: 1; transform: none; }
}
.submenu.is-open { animation: panel-enter .18s ease-out; }
@media (prefers-reduced-motion: reduce) {
  .submenu.is-open { animation: none; }
}

Reduced motion removes the visual movement while preserving all navigation. The source uses system colors in forced-colors mode and retains visible focus. Test these behaviors with the browser and assistive technology combinations relevant to your visitors.

7. Keep navigation available when scripts fail

Progressive enhancement starts with all destinations visible. The HTML has plain topic titles and link lists. The enhancement buttons are initially hidden. Once jQuery is available, the script configures the relationships, attaches handlers, reveals the buttons and opens the first section.

If jQuery is missing or the component script never runs, the navigation remains a readable list rather than an unusable closed accordion. The ZIP includes no-script.html, which deliberately omits both scripts for checking this fallback.

Download and customize the complete example

Extract the ZIP and open index.html. It contains HTML, CSS, JavaScript, the fallback page, a README and a local copy of jQuery 3.7.1 with its MIT license. The pinned dependency is for this teaching example and is not a claim about the latest release.

The standalone submenu links navigate to real local example sections. Replace them with your own URLs. The published article links to related live tutorials instead. Rename all component, header and panel IDs when adding another instance, and keep the heading hierarchy suitable for its new context.

On WordPress, use the site’s existing jQuery instance instead of loading a duplicate. A maintained theme or plugin should enqueue the component’s assets and follow the site’s content policy. There is no storage, account change or server action in this navigation example.

Common expanding menu problems

  • The open heading cannot collapse: capture its original expanded state before closing sibling sections.
  • Keyboard users cannot open a topic: use a native button instead of a click handler attached only to a heading or div.
  • Closed links still receive focus: hide the panel properly rather than making it transparent.
  • The wrong panel opens: check unique IDs, aria-controls and the mapping between headings and panels.
  • Repeated clicks produce delayed changes: avoid unmanaged animation queues and update state in one place.

Frequently asked questions

Can every section be collapsed?

Yes. Selecting the currently open heading closes it. The demo allows zero or one open section.

Does an accordion navigation need role menu?

No. These are ordinary navigation links grouped under disclosure buttons. Their native link and button semantics are appropriate.

Can I use native details and summary instead?

Yes, native disclosures can suit simpler requirements. This tutorial uses jQuery to demonstrate coordinated single-open behavior and explicit state and focus management.

Does the menu remember the open section after reload?

No application persistence is implemented. Initialization opens the first section; the demo does not save a preference to a server or browser storage.

Related tutorials

Try the CSS expanding vertical rail or sliding tabs with CSS and jQuery to compare navigation patterns.