To make an HTML element focusable, you can use the tabindex
attribute. The tabindex
attribute can be applied to any HTML element to include it in the tab order or make it focusable using JavaScript.
Focusable elements
A focusable element is any element that can receive keyboard input focus. When an element is focusable, it can be navigated to using the Tab key. This is crucial for accessibility and usability, allowing users to interact with web content using the keyboard.
Making an element focusable with tabindex
Default focusable elements
By default, certain elements (like form elements, links with href
, etc.) are inherently focusable and do not need a tabindex
attribute.
- Form Elements
<input>
(all types excepttype="hidden"
)<textarea>
<button>
<select>
<option>
(focusable within a<select>
element)
- Interactive Elements
<a>
(only if it has anhref
attribute)<area>
(within a<map>
, and only if it has an href attribute)<details>
<summary>
Trigger elements
Even though the <label>
element isn’t typically focusable, clicking it will focus on the associated input field.
Non-focusable elements
For elements that are not focusable by default (like <div>
, <span>
, etc.), you can make them focusable by adding the tabindex
attribute.
Should all elements be focusable?
You do not need to make all elements focusable. Only make elements focusable if:
- They have interactive content that the user needs to access (e.g., buttons, links, form inputs).
- They need to be part of the keyboard navigation flow for accessibility reasons.
- You want to enable specific interactivity, like JavaScript event handling on keyboard focus.
Interactive Elements with ARIA Roles
You can also use ARIA (Accessible Rich Internet Applications) roles to enhance custom interactive elements (https://www.w3.org/WAI/standards-guidelines/aria/).
Conclusion
Focusable elements are essential for providing an accessible and navigable user experience. By default, many interactive and form elements are focusable. You can make other elements focusable using the tabindex
attribute and enhance accessibility with ARIA roles and properties. This allows users to interact with your web content using the keyboard.