Search code examples
htmltabindex

tabindex="-1" on <ul> doesn't work


I have a mega dropdown menu like this from bootstrap (code simplified) :

<li class="dropdown mega-dropdown">
   <a href="#">Menu Button</a>
   <ul tabindex="-1">
      <li>1st Link</li>
      <li>2nd Link</li>
      <!-- many other links -->
   </ul>
   <!-- many other menu buttons -->
</li>

Small fiddle here : https://jsfiddle.net/48m2ppzc/

I want to simplify the navigation with the tab key :

  • At the beginning the element <ul> has a max-heightof 0px so I shoudn't be able to navigate inside it with the tab key (because the menu is hidden).
  • When I click on the "Menu Button" link, the menu should show up (I set max-height to 500px), and I need to change the tabindex to '0' (I can do it with JQuery so that's not a problem)

The problem is at the first point : tabindex="-1" doesn't work, I can still navigate inside the menu with the tab key.

How can I fix this problem? I use HTML5 so tabindex should work on all HTML elements, I also tried with tabindex="0".


Solution

  • tabindex is not inherited by the children of an element, so you need to set it manually on all items:

    <li class="dropdown mega-dropdown">
       <a href="#">Menu Button</a>
       <ul>
          <li><a href="#" tabindex="-1">1st Link</a></li>
          <li><a href="#" tabindex="-1">2nd Link</a></li>
          <!-- many other links -->
       </ul>
       <!-- many other menu buttons -->
    </li>
    

    Since this is probably accessibility related, it might help semantically to use the aria-hidden attribute as well (and toggle it, once it is visible):

    <li class="dropdown mega-dropdown">
       <a href="#">Menu Button</a>
       <ul aria-hidden="true">
          <li><a href="#" tabindex="-1">1st Link</a></li>
          <li><a href="#" tabindex="-1">2nd Link</a></li>
          <!-- many other links -->
       </ul>
       <!-- many other menu buttons -->
    </li>