Make an HTML element non-focusable
⚡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:
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: Usetabindex="-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 applye.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 negativetabindex
still makes elements focusable for screen readers. - Programmatic focus: To handle advanced interactions, JavaScript methods such as
element.focus()
orelement.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
Linked
Linked
Was this article helpful?