What you'll learn: By the end of this lesson you will be able to explain what keyboard focus is and how the browser builds the tab sequence, say why
tabindexis used only as0or-1, build a group of controls with one tab stop (roving tabindex), move focus into a dialog, keep it there and give it back, and describe what a screen reader is given (name, role, state) and what a test in jsdom can and cannot tell you about it.
Think of a dark theatre and one usher with a torch. The audience can only act on what the torch points at, and is lost if it jumps around, goes out, or points at a seat that was just removed. Keyboard focus is that torch: one element at a time receives the keys.
The running example is a product page and cart of the ShopStream grocery marketplace: a text toolbar for reviews, a "Remove" button on each cart item and a confirmation dialog.
The core idea
- Focus is a single position. One element at a time receives keyboard events.
- The tab sequence is derived from your markup. Native controls are in it by default; the best design needs almost no changes: write elements in a logical order.
- Assistive technology is given a tree, not a picture. The browser builds an accessibility tree with a name, a role and states for each element. A control with no name or the wrong role is misleading however it looks.
Figure 1. From markup to what the user meets
How to read this: the top row is what the user is told (markup becomes a tree handed to a screen reader); the bottom row is where the user acts (the keyboard moves focus, your handlers receive key events and may move focus). The accent boxes are what this lesson designs.
The tab sequence
Pressing Tab moves focus to the next element in the sequential focus order. MDN defines how tabindex shapes it:
- Absent on a native control (
button,input,select,textarea,awithhref,summaryof adetails,iframe): the element is focusable and in the sequence, as if it hadtabindex="0". 0: focusable and in the sequence, ordered by its position in the document, after any positive values.- Negative (usually
-1): focusable by script (element.focus()) and by a mouse click, but not reachable by Tab. - Positive: visited first, in ascending order, ties broken by document position (the maximum is 32767).
MDN recommends using only 0 and -1, and avoiding positive values and CSS that reorders focusable elements, because they make navigation hard for keyboard and assistive-technology users. Do not add tabindex="0" to a div to make it act like a button: use a button, which also brings the role and key handling. WCAG 2.4.3 (Focus Order, level A) asks that focusable components receive focus in an order that preserves meaning and operability; the simplest way to meet it is to let document order be focus order.
Illustration 1: the minimal example
The lab models these rules in a pure function (tabOrder) over a list of elements. It is a simplification: it knows tabindex, native focusability, disabled, hidden and inert, and nothing else. For a product page it prints:
Expected output, captured from a real run (Node 26.13.1, 2026-12-01; section 1 of the demo):
=== 1. The tab sequence of a product page (document order)
skip-link reached by: tab
search reached by: tab
cart-icon-div reached by: none
buy-button reached by: tab
sold-out-button reached by: none
tooltip-close reached by: script-only
reviews-tab-panel reached by: tab
footer-link reached by: tab
Tab order: skip-link > search > buy-button > reviews-tab-panel > footer-link
The same page after someone adds tabindex=1 to the footer link:
Tab order: footer-link > skip-link > search > buy-button > reviews-tab-panel
A plain div (cart-icon-div) is reached by nothing: it is not a control. A disabled button is skipped. tooltip-close with tabindex="-1" is "script-only": code can focus it, Tab skips it. And one added tabindex=1 on the footer link makes it the first stop on the page. That is the typical failure of positive values: one change in a corner reorders the whole sequence.
Seeing where focus is
WCAG 2.4.7 (Focus Visible, level AA) requires a mode of operation where the focus indicator is visible, and 2.4.11 (Focus Not Obscured, Minimum, level AA) says a focused component must not be entirely hidden by author-created content, such as a sticky header. The selector :focus-visible matches a focused element when the browser decides focus should be made evident: a mouse-clicked button generally is not matched, tabbing to it is. Style the indicator with it rather than removing it.
A skip link is one way to meet WCAG 2.4.1 (Bypass Blocks, level A); landmarks and headings are others. Semantic HTML and Document Structure builds one.
Groups of controls: one tab stop
A toolbar of 12 buttons would cost a keyboard user 12 Tab presses to cross. The WAI-ARIA Authoring Practices Guide (APG) says the tab sequence should include only one focusable element of a composite UI component, with arrow keys, not Tab, moving among the rest. For a toolbar: Tab and Shift+Tab move into and out of it; Left and Right Arrow move to the previous and next control; Home and End (optional) go to the first and last; wrapping is optional. Two techniques:
- Roving tabindex. The one element in the sequence has
tabindex="0", the others-1. On an arrow key the old one is reset to-1, the new one becomes0and receives DOM focus. aria-activedescendant. The container keeps DOM focus and is the only element in the sequence; the current child is shown by changing the container'saria-activedescendantvalue.
Figure 2. Choosing the keyboard design for a control
do the job?"} A -->|"yes"| N["Use it: button, a, input,
select, details, dialog"] A -->|"no"| B{"A group of related
items?"} B -->|"yes"| R["One tab stop, arrows inside:
roving tabindex or aria-activedescendant"] B -->|"no"| C{"An overlay that takes
over the page?"} C -->|"yes"| D["Dialog: focus in, kept in,
returned on close"] C -->|"no"| S["Single custom control:
role, name, keys, visible focus"]
How to read this: the first question is the cheapest. Every "no" costs more work, because you then own the roles, keys and focus that a native element gives for free.
Illustration 2: the realistic example
The review toolbar has four buttons (Bold, Italic, Underline, Link) and Underline is disabled. moveRoving models the arrow keys and rovingTabindexes says what each tabindex should be:
Expected output, captured from a real run (Node 26.13.1, 2026-12-01; section 2 of the demo):
=== 2. A toolbar of four buttons, the third one disabled (roving tabindex)
start focus on Bold tabindex=[0,-1,-1,-1]
ArrowRight focus on Italic tabindex=[-1,0,-1,-1]
ArrowRight focus on Link tabindex=[-1,-1,-1,0]
ArrowRight focus on Bold tabindex=[0,-1,-1,-1]
End focus on Link tabindex=[-1,-1,-1,0]
Home focus on Bold tabindex=[0,-1,-1,-1]
ArrowLeft focus on Link tabindex=[-1,-1,-1,0]
Exactly one button has 0 at every step, the disabled one is skipped, and End, Home and a wrapping ArrowRight behave as the APG describes. The React component stays thin: it sets tabIndex from rovingTabindexes, handles keydown with moveRoving and then focus(), and updates the state on focus so a click also moves the tab stop. The tests check each button's tabIndex and document.activeElement after each key.
Dialogs: focus in, kept in, given back
The APG modal dialog pattern says: focus moves into the dialog when it opens (generally the first focusable element, though the best target depends on content); Tab and Shift+Tab stay inside and wrap from the last control to the first and back; Escape closes it; and on close focus returns to the invoking element, unless that element no longer exists or the workflow calls for a different target. The container has role="dialog", aria-modal="true" and a name from aria-labelledby (a visible title) or aria-label; the APG says to set aria-modal only when your code really blocks interaction with everything outside.
The platform can do most of this. MDN says opening a native dialog with showModal() makes the rest of the page inert, focuses the first nested focusable element (an autofocus attribute picks a better target) and lets Esc dismiss it. An inert element cannot be focused or clicked and is removed from the tab order and the accessibility tree. Prefer the native element; write the focus handling yourself only when you cannot.
The lab uses a plain div dialog so every step is visible, and marks the page behind it inert while it is open, which is what makes aria-modal honest. It does not exercise the native dialog.
Figure 3. Opening and closing a dialog
How to read this: the page, not the dialog, remembers the opener, because the dialog does not exist yet when the opener is chosen and is gone when focus must return.
Illustration 3: a failure, when the opener disappears
The cart's "Remove Oats" button opens a confirmation. If the shopper confirms, the item and its button are deleted, so there is nothing to return to and focus would fall to the document body. The model's closeLayer takes the ids still in the page and a fallback id:
Expected output, captured from a real run (Node 26.13.1, 2026-12-01; section 3 of the demo):
=== 3. A confirm dialog with two controls
opened by remove-oats; stack=[remove-oats]
open -> focus confirm
Tab -> focus cancel
Tab -> focus confirm
Shift+Tab -> focus cancel
close, opener still on the page -> focus remove-oats
close, opener was removed -> focus cart-heading
The last two lines are the point: with the opener present, focus goes back to it; when it was removed, focus goes to the cart heading (tabindex="-1", so script can focus it but Tab does not stop on it). The component test confirms it in jsdom: after a confirmed removal document.activeElement is the heading, not body.
What a screen reader is given
The browser builds the accessibility tree from the DOM. MDN lists four properties of each object: a name, a description, a role (what kind of thing it is) and a state (checked, expanded and so on). Platform accessibility APIs hand this to assistive technology such as a screen reader. WCAG 4.1.2 (Name, Role, Value, level A) says the name and role of every user-interface component can be programmatically determined, and that changes to states and values are available to assistive technology. The lab models that shape, and only the shape:
Expected output, captured from a real run (Node 26.13.1, 2026-12-01; section 4 of the demo):
=== 4. Name, role, state: the shape of what assistive technology is given
(a model of the information, not the words any screen reader speaks)
Add to basket, button
(no name), button
Close dialog, button
Email address, textbox
Gift wrap, checkbox, checked
An icon-only button has no name until an aria-label gives it one. The lab's naming order (labelled-by text, aria-label, native label, then content) is its own simplification; the real computation has more steps. Screen readers word their speech differently, so these strings are not what any product says.
What you can and cannot test here
A jsdom test can check what decides what a screen reader is given: role, accessible name, tabindex values and document.activeElement after a key event. It cannot say how NVDA, JAWS, VoiceOver or TalkBack speak a page, or whether a real browser moves focus where the model says. That needs a person using the real tools; this lesson did not test with any screen reader.
Trade-offs
| Choice | Gain | Cost |
|---|---|---|
Native button and a |
Role, keys, focus for free | Less styling freedom |
Positive tabindex |
A quick reorder | Fragile, page-wide side effects |
| Roving tabindex | One tab stop, real focus on each item | You handle keys and state |
aria-activedescendant |
Focus stays on the container | The current item is only an attribute |
Native dialog with showModal() |
Inert background, focus and Esc from the platform | Behaviour to verify per browser |
| Hand-built dialog | Full control | You own the trap, the return and aria-modal |
Build it
The lab is examples/frontend/labs/keyboard-focus-model: a pure core (focusModel.ts), thin React (Toolbar, Dialog, CartPage), 31 tests and the demo shown above.
cd examples/frontend/labs/keyboard-focus-model
../../node_modules/.bin/vitest run
node src/demo.ts
Verified. The 31 tests passed (21 on the model, 10 rendering the components in jsdom) with Node 26.13.1, Vitest 5.1.0 and React 19.3.1, and the demo output above is the golden file examples/frontend/golden/keyboard-focus-model.txt. A synthetic Tab key event does not move focus on its own, so the dialog's Tab handling is tested with keydown events and the tab sequence with the pure model. The native dialog element, real browsers and every screen reader were not tested.
In practice: the cart's remove-item dialog
This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.
The situation
The cart lets a shopper remove an item through a confirmation shown as a div above the page. Keyboard users report that after pressing Remove they keep tabbing through the cart behind the overlay, that Escape does nothing, and that after confirming they are "back at the top of the page".
Starting architecture
Figure 4. An overlay with no focus design
How to read this: the warning boxes mark the gap. The overlay looks modal, but focus never moves into it, the page behind stays reachable and nothing sends focus back.
Options considered
| Option | What it fixes | What it costs |
|---|---|---|
Native dialog with showModal() |
Inert background, focus in, Esc | Restyling; browser differences to test |
| A hand-built focus trap | Works with the current markup | The trap, the return and the inert background are your code |
| A tested dialog from a component library | Behaviour maintained by others | A dependency and a different design |
The decision
| Field | Decision record |
|---|---|
| Context | An overlay that keyboard users cannot use. |
| Decision | Use the native dialog with showModal(). Record the opener before opening; on close focus it, or the cart heading if it was removed. |
| Consequences | One Tab loop, Esc works, the page behind is inert, focus is never lost. The look and the fallback target need work and tests. |
| Revisit when | Another overlay type (a drawer or popover) has different focus rules. |
Rollout and verification
- Write the keyboard contract first: where focus starts, how Tab and Shift+Tab behave, what Escape does, where focus goes on close.
- Test the model and the component: order, wrap, return, and the removed-opener case.
- Walk it by keyboard in each supported browser, with the focus indicator visible and a sticky header in place.
- Have someone who uses a screen reader try it. Unit tests cannot say how it sounds.
The 2 a.m. failure
A new "Undo" toast appears after a removal with its own button, and a bug shows it before the dialog has closed. Focus returns to the toast's button, which disappears after a few seconds, and focus drops to the body.
First three checks: (1) which element has focus when the toast disappears; (2) whether the code that restores focus checks the element still exists; (3) whether two layers share one "opener" variable. Mitigation: fall back to the cart heading whenever the target is gone. Follow-up: tests for a removed target and for nested layers.
Architect's notes
- Write the keyboard contract before the code: where focus starts, moves and ends for every interaction.
- Native first. A native control or
dialogis the cheapest accessible design. - Focus is not an announcement tool. Move it when the user must act on something new; the next lesson, on forms and dynamic content, covers status messages.
- Always have a fallback focus target, and test the model without a browser before walking it in one.
Common mistakes
- A
divwith a click handler: not focusable, no role. - Positive
tabindexto fix an order that should have been the document order. outline: nonewith no replacement.- A dialog that does not move focus in, does not trap Tab or ignores Escape.
- Forgetting the opener, so closing a dialog drops focus to the top of the page.
aria-modal="true"while the page behind is still reachable, and icon-only buttons with no name.
Key takeaways
- The tab sequence comes from markup;
0and-1are the onlytabindexvalues you normally need. - A group of related controls is one tab stop, with arrow keys inside it.
- A dialog moves focus in, keeps it in, handles Escape and gives focus back, with a fallback if the opener is gone.
- A screen reader is given a name, a role and states; a missing name is a defect.
- jsdom tests can check roles, names,
tabindexandactiveElement; they cannot hear anything.
Practice exercises
Exercise 1: Starter (30 min). Add a summary, a hidden link and an element inside an inert subtree to the tabOrder demo and predict the order before running it.
Exercise 2: Intermediate (2 hours). Turn wrapping off in the toolbar (moveRoving(state, key, false)), write the tests, and name the APG sentence that allows it.
Exercise 3: Advanced (half day). Replace the lab's div dialog with a native dialog opened by showModal(), try it in two real browsers and list what the jsdom tests could not check.
Related reading
In this course:
- Semantic HTML and Document Structure: landmarks, headings and the skip link.
- Error, Loading and Empty States: announcing state changes without moving focus.
- Client-Side Routing Architecture: navigation inside one page.
Planned in this module, named as plain text: Accessibility Fundamentals and WCAG, Semantic HTML, ARIA and Accessible Names, Accessible Forms and Dynamic Content.
Official documentation
- MDN: the tabindex attribute: values, order and default focusable elements.
- WAI-ARIA APG: Developing a keyboard interface: roving tabindex and aria-activedescendant.
- WAI-ARIA APG: Modal dialog pattern: focus on open and close, Tab and Escape.
- WAI-ARIA APG: Toolbar pattern: the arrow, Home and End keys.
- MDN: the dialog element:
showModal(), inertness andautofocus. - WCAG 2.2: Understanding Name, Role, Value: what must be exposed for every component.