Specifying the tab order of HTML elements using the tabindex attribute

As you probably know you can use the TAB key to go through certain elements (most commonly forms fields) on a web page. By default, each HTML page has a tabbing order that matches the order of the elements in your markup. So if an element on the page gets focus and you press the TAB key, the next element that receives focus will be the one that is next to it in the markup and is considered tabbable by default by the browser.

The tabindex attribute can be used to change this order. In HTML5 it can be specified on any element, however it is not necessarily useful in all cases. Let’s see a simple exampale where the tabindex attribute is used to change the order of tabbing on a simple form:

<form>
    First name:<br>
    <input type="text" name="firstname" tabindex="1">
    <br>
    Last name:<br>
    <input type="text" name="lastname" tabindex="-1">
    <br>
    Email:<br>
    <input type="text" name="email" tabindex="3">
    <br>
    Password:<br>
    <input type="text" name="password" tabindex="2">
</form>

By default, tabbing would take you through the input fields in the order they are defined. We changed this order by specifying the tabindex attribute. At first the “First name” field will be focused, then the “Password”, and lastly the “Email”. The “Last name” field won’t be focused. To understand the reason for this behaviour, lets see how the tabindex is taken into account.

If you specify the tabindex attribute on at least one element on the page, the tabbing will occur in the following manner:

  1. The elements that have a positive tabindex specified will be selected in increasing tabindex order.
  2. If we reach the last element that has a tabindex, then next the elements without tabindex will be focused in the order they are defined in the markup.
  3. The elements that are not tabbable by default (e.g. a div) or have a tabindex of -1 will not be selected at all.

A lot of HTML elements are not tabbable by default, but by specifying a tabindex for them they will get included in the tabbing order.

When you are specifying tabindex for your elements it’s a good idea to leave some room between each index. This way, if you have to insert some new elements in the tab order, you don’t have to adjust the tabindex of other elements. So from this perspective the tabindexes 10,20,30,40 are better than 1,2,3,4.