Keyboard Navigation Patterns — UI/UX

Every function must work from the keyboard (WCAG 2.1.1), in an order that makes sense (2.4.3), with visible focus (2.4.7). tabindex="0" joins the Tab order…

You type an email on a laptop, press Tab to move from the To field to the Subject, then Ctrl+Enter to send. Your hand never touches the touchpad once. For some people the keyboard isn't a shortcut. It's the only way.

Keyboard navigation means the whole page works without a mouse: Tab and Shift+Tab move between elements, Enter and Space press, the arrow keys move inside one widget (a component with several parts, such as photo tabs or a radio group), and Escape closes. Its users are screen reader users, people whose hands can't hold a mouse, and people who are simply faster on a keyboard. Think of Mist Homestay's corridor at night. Tab is like walking from door to door along the corridor. Once inside a room, you don't step back into the corridor to go from the wardrobe to a drawer. You move around inside the room (the arrow keys). Escape is like leaving again through the door you came in by. On a web page, each door is one element or one widget, and the wardrobe and the drawer are the parts inside that widget.

Tab, Shift+Tab and focus order

Tab moves focus to the next focusable element in HTML order. Shift+Tab goes back. Enter presses links and buttons. Space presses buttons and ticks a checkbox or radio. Three WCAG criteria cover it:

tabindex decides who joins the Tab order:

Value What it means
tabindex="0" joins the Tab order, at its position in the HTML
tabindex="-1" not in the Tab order, but can take focus from code (element.focus())
tabindex="1" or more jumps ahead of every other element. Avoid it: the Tab order stops matching the page order

One note for testing on a Mac: by default, Tab in Safari only moves focus between form fields. In our WebKit 26.4, Tab skipped links, buttons and radios. Use Option+Tab, or turn on "Press Tab to highlight each item" in Safari's Advanced settings.

One Tab stop per widget

The Terrace Room page has a navigation (Home, Rooms), three photo tabs (Room, Bathroom, Terrace) that can each be reached with Tab, their photo panel, three night buttons, then the "Book the room, pay on arrival" button. Mr. Hadi's focus is on the "Rooms" link. How many times must he press Tab to reach the Book button? Guess first. The answer is at the end of this section.

Photo tabs, a radio group and a toolbar (a row of tool buttons) are called composite widgets: one widget with many parts. The ARIA Authoring Practices Guide (APG, "Developing a Keyboard Interface") suggests one Tab stop (one place where Tab stops) per widget. Inside the widget, you move with the arrow keys. The technique is called roving tabindex: only the active part has tabindex="0", the rest have tabindex="-1", and the arrow keys move that tabindex="0" along with the focus.

The APG Tabs pattern lists the keys:

Key What happens
Tab goes into the active tab; Tab once more goes to its panel
Right arrow the next tab; from the last tab, back to the first
Left arrow the previous tab; from the first tab, to the last
Home, End (optional) the first tab, the last tab

The APG recommends a tab becomes active as soon as it's focused, as long as its panel shows without delay.

The code below runs roving tabindex on the photo tabs. keydown is the event when a key is pressed, and e.key is the key's name. The code finds the target tab, moves tabindex="0" and aria-selected to it, then moves the focus. % (the remainder of a division) makes the right arrow from the last tab go back to the first tab:

const tabs = [...document.querySelectorAll('[role="tab"]')];
document.querySelector('[role="tablist"]').addEventListener('keydown', (e) => {
  const i = tabs.indexOf(document.activeElement);
  const next = { ArrowRight: (i + 1) % tabs.length, ArrowLeft: (i - 1 + tabs.length) % tabs.length,
                 Home: 0, End: tabs.length - 1 }[e.key];
  if (next === undefined) return;      // other keys are left alone
  e.preventDefault();                  // the arrows don't scroll the page
  tabs.forEach((t, j) => {
    t.tabIndex = j === next ? 0 : -1;  // roving: only one is 0
    t.setAttribute('aria-selected', String(j === next));
    document.getElementById(t.getAttribute('aria-controls')).hidden = j !== next;
  });
  tabs[next].focus();
});

Focus on the Room tab, then the right arrow:

Room Bathroom Terrace
Before focus, tabindex="0" tabindex="-1" tabindex="-1"
After tabindex="-1" focus, tabindex="0" tabindex="-1"

We tested it in Chromium 147, WebKit 26.4 and Firefox 146. The right arrow from Terrace goes back to Room, Home goes to Room, End to Terrace, and pressing Tab on the active tab moves focus into its panel.

So the answer to the guess: 8 times. Three tabs, the panel, three night buttons, then Book. With roving tabindex on the photo tabs and radios for the nights (next section), 4 times is enough: the active tab, the panel, the chosen night, then Book.

Night radios: arrow keys for free from the browser

Choosing 1, 2 or 3 nights is really a radio group: one choice out of several. <input type="radio"> sharing one name already has its own roving tabindex, with no extra code.

<fieldset class="nights">
  <legend>Length of stay</legend>
  <label><input type="radio" name="nights" value="1"> 1 night</label>
  <label><input type="radio" name="nights" value="2" checked> 2 nights</label>
  <label><input type="radio" name="nights" value="3"> 3 nights</label>
</fieldset>

That is the first rule of ARIA again: the native element gives you the keyboard behaviour without one line of JavaScript.

Focus trap only in a modal

A focus trap is focus that loops inside one part of the page. Only a modal may do it, because the page behind the modal really can't be used at that moment. A <dialog> opened with showModal() does it on its own. We tested again in all three browsers: Enter on the Book button moves focus to the Back button in the modal, Tab never lands on the page behind, Escape closes the modal, and focus goes back to the Book button.

For a modal built from a <div>, you have to write the trap yourself, for example with this trapFocus function:

function trapFocus(modal, closeModal) {
  const focusable = modal.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');
  const first = focusable[0];
  const last = focusable[focusable.length - 1];
  modal.addEventListener('keydown', (e) => {
    if (e.key === 'Escape') return closeModal();      // the way out
    if (e.key !== 'Tab') return;
    if (e.shiftKey && document.activeElement === first) { e.preventDefault(); last.focus(); }
    else if (!e.shiftKey && document.activeElement === last) { e.preventDefault(); first.focus(); }
  });
}

first and last are the first and last focusable elements inside the modal. e.shiftKey is true when Shift is held down too. Shift+Tab on the first element jumps to the last element in the modal, and Tab on the last element goes back to the first.

Another option for a <div>: put the inert attribute (Chrome 102, Firefox 112, Safari 15.5) on the part of the page behind the modal, for example <main inert>, and remove it when the modal closes. Then nothing inside <main> can be clicked or focused, so you don't need to find first and last. We tried it in Chromium, Firefox and WebKit: Tab never landed on a button inside <main inert>. You still have to write Escape yourself.

WCAG 2.1.2 (No Keyboard Trap, level A) asks that people can always leave, by keyboard, any part they entered. A modal meets this criterion because Escape and the Back button close it. A trap anywhere else fails, for example a date picker that swallows Tab, so that Tab can't leave it.

Escape

The APG uses Escape to close whatever is open on top of the page: a dialog, a menu, a popover (a small box of information or choices). Once it's closed, focus goes back to the button that opened it, so Mr. Hadi doesn't start again from the top of the page. <dialog> does this itself. For a box like that of your own, write code like the code below. In this code, popup is the box, and trigger is the button that opens it:

popup.addEventListener('keydown', (e) => {
  if (e.key === 'Escape') {
    popup.hidden = true;
    trigger.setAttribute('aria-expanded', 'false');
    trigger.focus();                                // focus goes back to its opener
  }
});

⚠️ Tab that wanders, focus that gets stuck

TL;DR: Every function must work from the keyboard (WCAG 2.1.1), in an order that makes sense (2.4.3), with visible focus (2.4.7). tabindex="0" joins the Tab order, "-1" can only take focus from code, and positive values are avoided because they scramble the order. One widget (a component with several parts, such as photo tabs) needs only one Tab stop (one place where Tab stops). Roving tabindex keeps only the active part at tabindex="0". The right and left arrows move between tabs and go round from the last to the first, and Home and End go to the ends (APG Tabs pattern). After the right arrow, the new tab gets focus and tabindex="0", and the old one becomes -1. Radios sharing one name give that behaviour for free (Tab to the chosen one, the arrows choose). A focus trap (focus that loops inside one part) is only for a modal: showModal() does it, and a hand-made trap sends Shift+Tab from the first element to the last. Escape closes and returns focus to the button that opened it, because WCAG 2.1.2 asks that there's always a way out. In Safari, test with Option+Tab, because plain Tab stops only at form fields.

⚡ The Tab order follows the HTML order

Guess first: a friend puts tabindex="1" (a number that sets the Tab order) on the Sign up button, so it takes focus first. What do you think?

Better avoided. A positive value scrambles the page's natural Tab order: that button takes focus first, then Tab jumps back to the top of the page.

Meaning: tabindex="0" joins the Tab order at its place in the HTML, and tabindex="-1" can only take focus from code. Set the order through the HTML order.

⚡ One widget, one Tab stop

Meaning: A widget (a component with several parts) such as photo tabs, a radio group or a toolbar (a row of tool buttons) needs only one Tab stop, one place where Tab stops. Roving tabindex keeps only the active part at tabindex="0", the rest at tabindex="-1". The arrow keys move that tabindex="0" along with focus, and from the last tab back to the first tab.

⚡ Night radios: arrow keys for free from the browser

Write:

<fieldset class="nights">
  <legend>Length of stay</legend>
  <label><input type="radio" name="nights" value="1"> 1 night</label>
  <label><input type="radio" name="nights" value="2" checked> 2 nights</label>
  <label><input type="radio" name="nights" value="3"> 3 nights</label>
</fieldset>

Meaning: Radios (round choice buttons) with the same name already have a roving tabindex of their own. Tab lands on the checked radio (2 nights), an arrow moves focus and checks it at the same time, and the next Tab leaves the group.

⚡ Escape closes, focus comes back

Meaning: A focus trap (focus that loops inside one part of the page) is allowed only in a modal. A <dialog> opened with showModal() keeps focus inside by itself, Escape closes it, and focus goes back to the button that opened it.

What you will learn