DEV Community

İnanç Akduvan
İnanç Akduvan

Posted on

How to use Tabindex in a custom sidemenu || HTML attribute

Here is a very short article about TABINDEX which is an useful HTML attribute.

You can specify an order and navigate between HTML elements by pressing “TAB” button, thanks to this cute attribute. Using of tabindex will increase accessibility of your website and keyboard users will love you 💓


Let’s make a quick sidemenu. Here is HTML code:

<div class=”menu”>
   <div class=”item” id=”homepage” tabindex=”1">Homepage</div> 
   <div class=”item” id=”about” tabindex=”2">About</div>
   <div class=”item” id=”news” tabindex=”3">News</div>
   <div class=”item” id=”services” tabindex=”4">Services</div>
   <div class=”item” id=”contact” tabindex=”5">Contact</div>
</div>
Enter fullscreen mode Exit fullscreen mode

As you see, we ordered our divs with using tabindex attribute. Let’s add some very basic style. Here is our CSS:

.menu {
   position: fixed;
   top: 0;
   left: 0;
   width: 10vw;
   height: 100vh;
   background: #eee;
   overflow: auto;
}

.menu .item {
   padding: 18px;
   border-bottom: 2px solid #ddd;
}

.menu .item:focus {
   background: #ddd;
   font-weight: bold;
   outline: none;
}
Enter fullscreen mode Exit fullscreen mode

Now I am pressing “Tab” button. And now you should see something like this:

Alt Text

That is it. Thank you for reading. 🎉


Github repo of these codes:
https://github.com/inancakduvan/tabindex

My github profile:
https://github.com/inancakduvan

My twitter account:
https://twitter.com/InancAkduvan

Top comments (5)

Collapse
 
alvaromontoro profile image
Alvaro Montoro • Edited

A tabindex value greater or equal to 1 is not recommended and it should be avoided. The elements with the tabindex=1 (or higher) will gain focus before elements with no tabindex or a tabindex of 0 (zero) resulting in a navigation order that doesn't match the visual order, which is bad for accessibility. Also, it normally may lead to having to set tabindex for other elements (when no tabindex would have been cleaner and better) which could become a development nightmare.

Collapse
 
inancakduvan profile image
İnanç Akduvan

Thank you so much for enlightening me! I will edit in charge of this information. 😊

Collapse
 
sebconejo profile image
Sébastien Conejo

And how do you manage submenus and sub-submenus?

Do you scroll through all the subitems in a tab before moving on to the next tab? It would be interesting to present this case, as it's more frequent than a simple menu with 5 links and only 1 level.

Collapse
 
manishfoodtechs profile image
manish srivastava

Nice

Collapse
 
inancakduvan profile image
İnanç Akduvan

Thank you!