Search code examples
htmlaccessibilitywai-aria

Can I add aria-controls to an <a> tag


I have a primary navigation where some items can contain a secondary nav. I would like to make my webiste as accessible as possible so I'm looking for the best solution to show/hide the secondary nav.

What I've come up with is:

  • the user gets to the <a> tag with a secondary nav with TAB & hits enter
  • the secondary nav opens up
    • if they hit enter on the primary <a> tag again, they get redirected to that page
    • if they hit TAB, they go to the first item in the secondary nav

I've already accomplished this using javascript. What I would like to know is whether there is a better approach to this & also:

I've added aria-controls and aria-expanded attributes to the primary navigation <a> tags. Is that semantically correct?

This is what the simplified markup looks like:

<nav>
  <ul>
  
    <li>
      <a href="/">Home</a>
    </li>

    <li>
      <a href="/other-page" aria-expanded="false" aria-controls="secondary-nav">Other page</a>

      <nav>
        <ul id="secondary-nav">
          <li>
            <a></a>
          </li>
          <li>
            <a></a>
          </li>
          <li>
            <a></a>
          </li>
        </ul>
      </nav>
    </li>

  </ul>
</nav>


Solution

  • Interestingly, the ARIA standard supports aria-expanded (and consequently aria-controls) on the link role. But it does have this to say as well:

    If pressing the link triggers an action but does not change browser focus or page location, authors are advised to consider using the button role instead of the link role.

    Since at first press the <a> will neither change focus, nor page location, it should be a button at the start. You could achieve that by adding role="button".

    It might become a link when pressed, but changing role and behaviour of an element is disorienting for a lot of people and I’d expect especially for users with cognitive disabilities.

    Disclosure Navigation Menu Pattern

    So I would recommend sticking to established patterns, like the Disclosure Navigation Menu

    It clearly separates the disclosure button from the links, which is way easier to understand.

    What to do with index pages

    I am assuming that your solution comes from a menu design that originally did not take into account keyboard and touch interactions, but only mouse, where hovering opens the submenu, and clicking the link.

    The pattern that I used most of the time to solve that issue is adding a link to the index page in the submenu, and name it the same as the button, or “Overview”, as they did in the example posted above.

    For you, that would result in

    • Other page
      • Overview