Web Fundamentals · Lesson 8 of 10 · 4 min
Keyboard Accessibility & Focus Management
This is where you prove you can build for everyone, not just mouse users. It’s a common signal for senior-level hires.
After this, you will be able to describe and implement the three critical phases of focus management for any interactive component: moving focus in, trapping it, and restoring it on exit. This is the core of keyboard accessibility.
Use tabindex to control the path
Your main tool for managing focus is the tabindex attribute. It has three modes of operation, and you need to know exactly when to use each.
tabindex="0" puts an element into the natural tab order. Use this for custom interactive controls built from non-interactive elements like <div> or <span> (e.g., a fake button). This makes them reachable via the Tab key.
tabindex="-1" makes an element focusable via JavaScript (element.focus()) but keeps it out of the natural tab order. This is essential for things you need to send focus to directly, like a modal dialog container, an error summary, or a new view in a single-page app.
tabindex with any positive integer (1, 2, 3, ...) is a mistake. It creates a separate, rigid tab order that overrides the natural document flow. This is fragile, confusing for users, and almost always a sign of a poorly structured DOM. If you feel you need it, fix your HTML structure instead.
The interview question: "What's the difference between
tabindex="0"andtabindex="-1"?"Your answer: "
tabindex='0'includes an element in the default tab order, making it accessible to keyboard users navigating sequentially. You use it for custom controls.tabindex='-1'makes an element focusable only with JavaScript, not via the Tab key. You use it to programmatically manage focus, like moving it to a modal when it opens."
The three steps of managing focus
When you show a modal, off-canvas menu, or any other component that overlays the page, you must take control of the keyboard focus. The pattern is always the same.
- Store and move: Before the component appears, store a reference to the currently focused element (
document.activeElement). When the component mounts, move focus to a logical place inside it, usually the component container itself or the first focusable element. - Trap focus: While the component is active, ensure the
TabandShift+Tabkeys cycle through only the focusable elements within it. Focus must not escape to the content underneath. - Restore focus: When the component is closed, return focus to the element you stored in step 1.
Forgetting any of these steps creates a broken experience. Forgetting to restore focus is the most common mistake.
How to implement a focus trap
A focus trap is a keydown event listener on your component that intercepts Tab key presses. The logic is straightforward.
First, get all focusable elements inside your component. The selector is complex but standard: a[href], button, input, textarea, select, details, [tabindex]:not([tabindex="-1"]). Filter out any that are disabled or not visible.
On a keydown event for the Tab key:
- Identify the first and last focusable elements from your list.
- Check if
shiftKeyis pressed. - If
Tabis pressed on the last element,preventDefault()and move focus to the first element. - If
Shift+Tabis pressed on the first element,preventDefault()and move focus to the last element.
This creates a circular navigation loop.
function trapFocus(element) {
const focusableEls = element.querySelectorAll(
'a[href]:not([disabled]), button:not([disabled]), textarea:not([disabled]), input[type="text"]:not([disabled]), input[type="radio"]:not([disabled]), input[type="checkbox"]:not([disabled]), select:not([disabled])'
);
const firstFocusableEl = focusableEls[0];
const lastFocusableEl = focusableEls[focusableEls.length - 1];
const KEYCODE_TAB = 9;
element.addEventListener('keydown', function(e) {
const isTabPressed = (e.key === 'Tab' || e.keyCode === KEYCODE_TAB);
if (!isTabPressed) {
return;
}
if (e.shiftKey) /* shift + tab */ {
if (document.activeElement === firstFocusableEl) {
lastFocusableEl.focus();
e.preventDefault();
}
} else /* tab */ {
if (document.activeElement === lastFocusableEl) {
firstFocusableEl.focus();
e.preventDefault();
}
}
});
}
The trap: Your focus trap logic is useless if the visual order of elements doesn't match the DOM order. CSS properties like flex-direction: row-reverse or grid with order can make the "first" focusable element in the DOM appear last on the screen. The tab order follows the DOM, creating a jarring jump for keyboard users. Always ensure your source order is logical.
Handle standard keyboard patterns
Beyond the tab sequence, users expect interactive controls to respond to specific keys. Not implementing these makes custom components feel broken.
- Activation:
EnterandSpaceshould activate buttons and similar controls. When usingSpaceon a custom control, callevent.preventDefault()to stop the page from scrolling. - Dismissal:
Escapeshould close any temporary view like a modal, dropdown, or tooltip. It's a universal "get me out of here" command. - Navigation within a component: For composite widgets like tab lists, menus, or custom selects,
Tabshould move focus to the component as a whole. Arrow keys (Left/RightorUp/Down) should then navigate between the items inside.Tabagain should move focus to the next element outside the component. This prevents users from having to tab through every single option in a long list.
Try it
Find a modal component in a project you've worked on. Add a keydown listener to implement a focus trap. Store document.activeElement before it opens and restore focus when it closes. See if you can get the core logic working in under 20 minutes.
Next: Advanced Accessibility Patterns & Custom Controls
Lock it in — apply this lesson under interview conditions.