Tabindex and Focus

Tabindex and Focus

Tabindex

tabindex is an HTML attribute. It lets you change whether an element is focusable or not (and in which order). It can be applied to any HTML element (but it shouldn't).

1. tabindex = 0

<div tabindex="0">This div is focusable!</div>

This div is focusable!

A tabindex="0" makes the element focusable with tab and the mouse. (Click before the element you want to focus and then tab, then the element should be focused.) The element can be focused in the document source order. BUT it cannot be interacted with, so we'll need JavaScript to make it behave like a normal focusable element (do sth. on enter or space).

Achtung, die Leertaste triggert auch "Bild runter". Da müsste man vermutlich mit preventDefault() und dem richtigen event.type arbeiten, aber das mach ich jetzt nicht ...

const div = document.querySelector('div[tabindex="0"]');
            
      div.addEventListener('keyup, event => {
        const { key } = event;
        if (key === ' ' || key === 'enter') {
          // do sth.
        };
      };

So IF you want to set a tabindex="0", make sure that the user can interact with this element!

2. Positive tabindex

Don't set a positive tabindex unless you absolutely have no other chance! It dictates the order of the tabable elements, which can be confusing and frustrating. Only exception: Skiplinks to complex navigations in the header.

3. Negative tabindex

An element with a negative tabindex cannot be tabbed to BUT it still can recieve focus with a mouse click. We use a negative tabindex to direct focus with the focus() method.

NEVER set a negative tabindex on "naturally" focusable elements like buttons, links or form elements.
If you don't want these elements be focusable, use disabled instead.
NEVER show focus styles on elements which can't be focused.

Focus

Detecting the focused element

document.activeElement gets the focused element.

Google Chrome: Live Expression
Go to Chrome DevTools > Console > eye icon > type document.activeElement into the input field (instead of »Expression«)

Directing focus

Element.focus() lets you direct focus to focusable elements (such as links, buttons, form elements).