Explain Codes LogoExplain Codes Logo

Make an HTML element non-focusable

html
web-development
accessibility
best-practices
Anton ShumikhinbyAnton Shumikhin·Sep 2, 2024
TLDR

Apply the tabindex="-1" property to an HTML element to make it non-focusable in the keyboard navigation. Furthermore, form elements can become non-focusable through the disabled attribute.

Example:

<span tabindex="-1">My Tab key is on a strict diet, it can't focus me.</span> <input type="text" disabled>

Focusability and its significance

Properly setting up the focusability of elements is a cornerstone of web accessibility. While tabindex="-1" effectively excludes the elements from keyboard focus, there are scenarios such as form controls or interactive elements where a more nuanced approach is needed.

  • Non-Interactive elements: Use readonly to permit view access and restrict them from keyboard focus.
  • JavaScript to handle focus: Scripting can be used for assigning or removing tabindex dynamically as per user interaction or application state

Taming the interactive elements

Interactive elements like <a> tags and <button> tags can be rendered non-focusable by the keyboard.

  • <a> tags & <button> tags: Use tabindex="-1" to exclude them from the tab order while retaining programmatic focusability.
  • Dynamic content handling: When handling dynamic content, JavaScript can be applied to set tabindex.
  • Event handling: Use the focusin event listeners to apply e.target.blur() to unsubscribe elements from gaining focus.

Unlocking custom widgets and controls

Ensuring accessibility in custom components requires a slightly different approach:

  • Screen readers: For screen readers and assistive technologies to behave aptly, tabindex values should be managed sensibly. Remember, a negative tabindex still makes elements focusable for screen readers.
  • Programmatic focus: To handle advanced interactions, JavaScript methods such as element.focus() or element.blur() can be used.
  • Preventing focus traps: Use event.relatedTarget within the focus event to verify and alter the new focus target - crucial for avoiding focus traps