The tabindex attribute lets you change whether an element is focusable.
Zero
A positive value
A negative value
You can apply tabindex to any element, even to a <div>.
Zero
If you set an element’s tabindex to zero, you will be able to focus on the element with the tab key and the mouse.
<div tabindex="0">You can focus on me!</div>
Quick tip: If you click before the element you want to focus, the next Tab key should focus the element.
Positive tabindex
The tabindex value dictates the order of elements that can be tabbed. If you set tabindex to zero, the order will be the document source order. (Which means whatever comes first in the document will get tabbed to first).
This positive tabindex first behavior is confusing. We expect to tab through elements in the order we read. (Left to right, top to bottom). So you should never use positive tabindex (unless you have a valid use-case).
Negative tabindex
If you set a negative tabindex value, you prevent users from tabbing onto the element.
<button tabindex="-1">Button with negative tabindex</button>
<button>Normal button</button>
However, you can still focus on the element with a mouse click.
Negative tabindex is used to direct focus. We can do this by using the focus method. You’ll learn about directing focus and the focus method in Shifting Focus.
Focusability and the ability to interact
If you can focus on an element, you should be able to interact with the element. If you cannot focus on an element, you should not be able to interact with an element.
This means a few things:
First, if you set tabindex to zero, you should make sure the user can interact with the element with both Enter and Space.
const div = document.querySelector('div[tabindex="0"]')
div.addEventListener('keydown', event => {
const { key } = event
if (key === ' ' || key === 'enter') {
// Do something
}
})
Second, you should never set negative tabindex to buttons, links, or form elements. Users should be able to interact with these elements.
If you want to disable buttons or form elements, you can use the disabled attribute instead. Disabled buttons and form elements cannot be focused on with the mouse or the keyboard.
Third, you should not show a focus style if you cannot focus on an element. Since users cannot focus on elements with negative tabindex, these elements should NOT have a focus style.