Skip to content
Tutorials Center
My learning

Topics

Lesson 56 of 61 ยท Projects

Project: An Accessible Mega Menu

Build an accessible Shopify mega menu from a linklist: nested menu data, disclosure buttons with aria-expanded, keyboard support, Escape handling and a mobile drawer.

A mega menu is a navigation bar whose top-level items open large panels with many links, grouped into columns. Stores with big catalogs love them, and they are also one of the easiest components to get wrong. A menu that opens only on mouse hover cannot be used with a keyboard, a menu with the wrong ARIA roles can make a screen reader announce nonsense, and a menu that works on desktop but is unusable on a phone loses half your visitors.

In this project you will build the menu in layers. First you will see how a store's navigation is stored (a linklist) and how Liquid walks it. Then you will pick the right accessible pattern, which is simpler than many people expect. Then you will add keyboard behavior, and finally a mobile drawer. Real Liquid and CSS are shown in read-only blocks; JavaScript stand-ins let you test the logic and use a working menu in the browser. Background lessons: Loops, Sections, Schema settings and Accessibility in Themes.

The Liquid targets current Online Store 2.0 themes. Shopify supports menus nested up to three levels deep (a top link, its children, and their children). The live examples use invented data and never contact Shopify.

Where menu data comes from

Merchants build navigation in the admin under Content, then Menus. Each menu has a handle (for example main-menu) and a tree of links. In Liquid you reach it through the linklists object, or, better in a section, through a link_list setting so the merchant can choose which menu the section shows:

LIQUID
{% schema %}
{
  "name": "Mega menu",
  "settings": [
    { "type": "link_list", "id": "menu", "label": "Menu", "default": "main-menu" }
  ]
}
{% endschema %}
LIQUID
{%- assign menu = section.settings.menu -%}
{%- if menu != blank -%}
  {%- for link in menu.links -%}
    {{ link.title }} -> {{ link.url }}
  {%- endfor -%}
{%- endif -%}

A menu has links. Each link has title, url, links (its children), active (this link is the current page), child_active (a descendant is the current page), current, levels (how deep its subtree goes), and type. The levels value is useful for deciding whether a link needs a dropdown at all: a link with no children has levels of 0 and links.size of 0.

flowchart TD
  M["menu: main-menu"] --> A["Shop"]
  M --> B["Journal"]
  M --> C["About"]
  A --> A1["Kitchen"]
  A --> A2["Living"]
  A1 --> A11["Mugs"]
  A1 --> A12["Tea towels"]
  A2 --> A21["Planters"]

A linklist is a tree: top-level links, children, and grandchildren (the three levels Shopify allows).

Choose the right pattern: disclosure, not menu

ARIA has roles called menubar, menu and menuitem. They look perfect for a website menu, and they are the wrong choice. They describe application menus like the File menu of a desktop program, and they promise screen reader users a special keyboard model (arrow keys everywhere) that you would then have to implement completely. A site navigation is a list of links, and the recommended pattern is a disclosure:

  • the whole thing sits in a <nav> landmark with a label;
  • each top-level item that has children is a <button> with aria-expanded="false" and aria-controls pointing at its panel;
  • the panel contains ordinary links in lists;
  • top-level items without children are plain links.

Pressing the button toggles aria-expanded and shows or hides the panel. Tab moves through the links naturally, and nothing else needs to be learned by the user. This is less code and fewer chances for mistakes.

Here is the Liquid that produces it. Each button needs a unique id for aria-controls; forloop.index combined with the section id provides one:

LIQUID
<nav class="mega" aria-label="Main">
  <ul class="mega__list">
    {%- for link in menu.links -%}
      <li class="mega__item">
        {%- if link.links.size > 0 -%}
          {%- assign panel_id = 'MegaPanel-' | append: section.id | append: '-' | append: forloop.index -%}
          <button type="button" class="mega__trigger"
                  aria-expanded="false" aria-controls="{{ panel_id }}"
                  {% if link.child_active %}data-current="true"{% endif %}>
            {{ link.title | escape }}
          </button>
          <div id="{{ panel_id }}" class="mega__panel" hidden>
            <ul class="mega__columns">
              {%- for child in link.links -%}
                <li>
                  <a href="{{ child.url }}"{% if child.current %} aria-current="page"{% endif %}>
                    {{ child.title | escape }}
                  </a>
                  {%- if child.links.size > 0 -%}
                    <ul>
                      {%- for grandchild in child.links -%}
                        <li><a href="{{ grandchild.url }}">{{ grandchild.title | escape }}</a></li>
                      {%- endfor -%}
                    </ul>
                  {%- endif -%}
                </li>
              {%- endfor -%}
            </ul>
          </div>
        {%- else -%}
          <a href="{{ link.url }}"{% if link.current %} aria-current="page"{% endif %}>
            {{ link.title | escape }}
          </a>
        {%- endif -%}
      </li>
    {%- endfor -%}
  </ul>
</nav>

Points worth noticing: the hidden attribute keeps the panel out of the tab order and the accessibility tree until it opens; aria-current="page" marks the link for the page the shopper is on; and escape is applied to titles because menu text is merchant-controlled input (see Security in Themes).

A stand-in for walking the tree

Liquid cannot run here, so this stand-in does the same job with a JavaScript tree. It builds the HTML string, marks the current page, and computes the unique ids. It also computes child_active the way Shopify defines it: true when any descendant is the current page.

JS Stand-in: render a linklist as disclosure markup

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The "Shop" button carries data-current="true" because the Planters page sits two levels below it, which lets your CSS highlight the right top-level item.

Keyboard behavior

With the disclosure pattern you only need to add a few things, and each one has a clear reason:

Key or event Behavior
Enter or Space on a trigger Toggle its panel (free from <button>)
Tab Moves through the open panel's links, then on to the next item
Escape Close the open panel and move focus back to its trigger
Focus leaves the whole menu Close any open panel
Click outside the menu Close any open panel
Opening a second panel Close the first one

Two smaller rules: only one panel may be open at a time, and a keyboard user must never lose focus. If a panel closes while focus is inside it, focus would drop to the page start, so the Escape handler moves it to the trigger first.

Hover-to-open is optional. If you add it, it must be an addition and not a replacement: the button still has to work with click and keyboard, and the panel must not vanish while the pointer travels diagonally toward it (give it a short close delay). Many accessible menus skip hover entirely, which is also friendlier on touch screens.

The script uses a custom element so each menu instance manages itself and the section works in the theme editor when merchants reorder sections (see JavaScript in Themes):

JavaScript
class MegaMenu extends HTMLElement {
  connectedCallback() {
    this.addEventListener('click', this.onClick);
    this.addEventListener('keydown', this.onKeydown);
    this.addEventListener('focusout', this.onFocusOut);
    document.addEventListener('click', this.onOutside);
  }
  disconnectedCallback() {
    document.removeEventListener('click', this.onOutside);
  }
  onClick = (event) => {
    const trigger = event.target.closest('[aria-controls]');
    if (!trigger) return;
    const wasOpen = trigger.getAttribute('aria-expanded') === 'true';
    this.closeAll();
    if (!wasOpen) this.open(trigger);
  };
  onKeydown = (event) => {
    if (event.key !== 'Escape') return;
    const open = this.querySelector('[aria-expanded="true"]');
    if (open) { this.closeAll(); open.focus(); }
  };
  onFocusOut = (event) => {
    if (!this.contains(event.relatedTarget)) this.closeAll();
  };
  onOutside = (event) => { if (!this.contains(event.target)) this.closeAll(); };
  open(trigger) {
    trigger.setAttribute('aria-expanded', 'true');
    document.getElementById(trigger.getAttribute('aria-controls')).hidden = false;
  }
  closeAll() {
    this.querySelectorAll('[aria-controls]').forEach((t) => {
      t.setAttribute('aria-expanded', 'false');
      document.getElementById(t.getAttribute('aria-controls')).hidden = true;
    });
  }
}
customElements.define('mega-menu', MegaMenu);

Wrap the <nav> in <mega-menu>...</mega-menu> in the section. The element is registered once even if the section is rendered several times.

The mobile drawer

A wide panel with several columns does not fit a phone. The usual approach keeps the same data and the same markup but changes the presentation below a breakpoint:

  • a single Menu button (also a disclosure with aria-expanded) opens a full-height drawer containing the nav;
  • inside the drawer, top-level triggers become accordions: the panels stack vertically under their button;
  • the page behind should not scroll while the drawer is open, and Escape closes it and returns focus to the Menu button;
  • tap targets are at least 44 by 44 CSS pixels.

You do not need a second copy of the menu. A media query hides or shows the Menu button, and the same <nav> is positioned as a drawer:

CSS
.mega__toggle { display: none; }

@media (max-width: 749px) {
  .mega__toggle { display: inline-flex; min-height: 44px; }
  .mega__drawer {
    position: fixed; inset: 0 auto 0 0; width: min(88vw, 360px);
    background: var(--color-background); overflow-y: auto;
    transform: translateX(-100%); transition: transform 0.2s;
  }
  .mega__drawer[data-open="true"] { transform: none; }
  .mega__panel { position: static; }   /* stack panels as accordions */
}

@media (min-width: 750px) {
  .mega__panel {
    position: absolute; inset-inline: 0; padding: 1.5rem;
    background: var(--color-background);
  }
  .mega__columns { display: grid; grid-template-columns: repeat(4, 1fr); gap: 1.5rem; }
}

@media (prefers-reduced-motion: reduce) {
  .mega__drawer { transition: none; }
}

A drawer that is off-screen through transform is still reachable by keyboard unless you also hide it: when closed on mobile, set visibility: hidden (after the transition) or the inert attribute so Tab skips it. Forgetting this is the classic mobile menu bug.

The working stand-in

This stand-in is a complete menu with the behavior described above: disclosure buttons, one open panel at a time, Escape returning focus, closing on outside clicks and focus leaving, an aria-current marker, and a mobile drawer. Because the preview frame has a fixed width, the Desktop / Mobile button simulates the breakpoint with a data-view attribute (a real theme uses the media queries above).

Stand-in: accessible mega menu with mobile drawer

Try this: open "Shop", press Tab to walk into the panel, then press Escape. Focus jumps back to the button and the panel closes. Switch to Mobile, open the drawer with the Menu button and see the same panel stack as an accordion. "Planters" is marked as the current page, and its ancestor "Shop" is shown in bold, like child_active styling.

Testing the finished menu

Before you call it done, run through this list:

  1. Unplug the mouse. Can you reach every link, open and close every panel, and always see where focus is (a visible focus ring)?
  2. Does Escape do what a user expects, and does focus end up somewhere sensible?
  3. With a screen reader, does each trigger announce its name, "button", and "collapsed" or "expanded"?
  4. Is the menu usable at 320 px width and at 200% zoom?
  5. Does the section survive the theme editor: adding it, reordering it and changing the menu setting must not duplicate event listeners?
  6. With JavaScript disabled, are the top-level links still reachable? If not, consider a link on each trigger's parent (the "Shop" page) as a fallback.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which pattern is recommended for a site navigation with dropdown panels?

    Application menu roles promise a full arrow-key model that website navigation does not need. A disclosure uses native buttons and links and is much simpler to get right.
  2. 2. What does the child_active property of a menu link tell you?

    active means the link itself is the current page; child_active means a descendant is. It lets you highlight the right top-level item.
  3. 3. A panel closes with Escape while focus is inside it. What must the script do?

    If the focused element disappears, focus falls back to the start of the page. Returning it to the trigger keeps the user's place.
  4. 4. Why do menu titles go through the escape filter in the example?

    Escaping HTML special characters prevents markup in a title from being interpreted as code.
  5. 5. What is a common bug in off-canvas mobile drawers moved away with transform?

    Moving an element off screen does not remove it from the tab order. Use visibility, hidden or inert when the drawer is closed.

Summary

  • Menu data is a tree in linklists (or a link_list setting); each link has links, active, child_active and current.
  • Use a <nav> with disclosure buttons (aria-expanded, aria-controls) and ordinary lists of links, not application menu roles.
  • Add Escape to close and refocus the trigger, close on focus leaving and outside clicks, and allow one open panel at a time.
  • On small screens reuse the same markup in a drawer with accordion panels, 44 px tap targets, and a hidden or inert closed state.
  • Escape merchant-controlled text and test with a keyboard, a screen reader and the theme editor.

Next, add product data that goes beyond the standard fields in Project: A Size Guide with Metaobjects.