Search code examples
javascriptaccessibility

Why am I not able to focus on this menu item when using tab and arrow keys?


I have menu options like below:

<li class="item1" role="menuitem" tabIndex="-1">
  <svg>...</svg>
  <span>Item #1</span>
</li>

<li class="item2" role="menuitem" tabIndex="-1">
  <svg>...</svg>
  <span>Item #2</span>
</li>

<li class="item3" role="menuitem" tabIndex="-1">
  <svg>...</svg>
  <span>Item #3</span>
</li>

<li class="item4" role="menuitem" tabIndex="-1" aria-disabled="true">
  <svg>...</svg>
  <span>Item #4</span>
</li>

From everything that I've read about aria-disabled, it seems like it should still allow the user to reach the element via tab and arrow keys (that the element is still focusable). However, when I try to navigate to the fourth menu item via tabs and arrow keys, it doesn't focus on it and it skips it entirely instead. I tried removing the aria-disabled just to see if that would change anything and that made it reachable via the keyboard. I can navigate fine through the rest of the menu items, but for some reason I can't reach the fourth...


Solution

  • It doesn't focus for me if tabindex=-1. If you want to make an element focusable just add tabindex=0 to it. Read more on tabindex

    ul {
      list-style: none;
    }
    <button>focus me</button> then click [tab]
    <ul>
      <li class="item1" role="menuitem" tabIndex="0">
        <svg width="50" height="50"><circle cx="25" cy="25" r="20" stroke="green" stroke-width="4" fill="yellow" /></svg>
        <span>Item #1</span>
      </li>
    
      <li class="item2" role="menuitem" tabIndex="-1">
        <svg width="50" height="50"><circle cx="25" cy="25" r="20" stroke="green" stroke-width="4" fill="red" /></svg>
        <span>Item #2 with tabindex=-1</span>
      </li>
    
      <li class="item3" role="menuitem" tabIndex="0">
        <svg width="50" height="50"><circle cx="25" cy="25" r="20" stroke="green" stroke-width="4" fill="yellow" /></svg>
        <span>Item #3</span>
      </li>
    
      <li class="item4" role="menuitem" tabIndex="0" aria-disabled="true">
        <svg width="50" height="50"><circle cx="25" cy="25" r="20" stroke="green" stroke-width="4" fill="yellow" /></svg>
        <span>Item #4</span>
      </li>
    </ul>
    <button>focus me</button>