Skip to main content
Saved

Pattern Accessibility Beginner

Keyboard Navigation

Every interactive element should be focusable and usable with the keyboard, with a logical tab order and the arrow key behavior that users expect.

Examples
native web
Read
6 min

The problem

You might build a beautiful custom dropdown with divs and CSS that works great with a mouse, and then someone presses Tab and nothing happens. The browser skips the dropdown, because divs aren’t focusable by default. Even once it has focus, Enter does nothing without a keydown handler, and the arrow keys scroll the page instead of moving through the list.

The pattern

Every interactive element you build should be focusable with Tab and usable with just the keyboard. Semantic HTML elements like <button>, <a>, and <input> give you this without any extra work.

Problem

I’ve tested interfaces where the only way to close a modal was clicking the X button, because there was no Escape key handler, so keyboard users were stuck inside it. Menus that only appear on hover cause the same kind of problem, because keyboard users can’t hover to make them appear.

Custom components that can get focus often still respond to the wrong keys. Some use Tab to move between the items in a list, where users expect the arrow keys, and many don’t respond to Enter at all. Keyboard users have relied on these conventions for decades, so components that don’t follow them feel broken.

Solution

Custom widgets work best when they follow patterns that users already know, such as the arrow keys moving through lists and menus, and Escape closing overlays. The WAI-ARIA Authoring Practices define the expected keyboard behavior for common widgets. If you invent a new pattern instead, users have to work against habits they’ve built up on other sites.

This page is about which keys operate each widget. Focus Management covers where focus should go after the UI changes, and Focus Trap covers keeping focus inside an open modal.

You can make a custom element focusable with tabindex="0", and make it respond to keys with a keydown handler. Focus indicators need to stay visible so keyboard users know where they are. The :focus-visible pseudo-class helps with this, because it matches when someone is moving around with the keyboard, but not after a mouse click.

If any of your features depend on a mouse-specific interaction like drag-and-drop, you’ll need a keyboard alternative too, such as buttons to move items up or down.

Example

The div below needs a tabindex, a role, and a key handler before a keyboard user can press it, and the <button> comes with all three.

<!-- Tab skips it, and Enter and Space do nothing -->
<div class="button" onclick="save()">Save</div>

<!-- Focusable, announced as a button, and Enter and Space both click it -->
<button onclick="save()">Save</button>

A native <select> does the same for a dropdown, with the arrow keys, Enter, Escape, and type-ahead all built in. The rest of the examples are for the cases where a native element won’t do.

In this custom dropdown, the arrow keys move through the options, Enter selects one, and Escape closes the list. Keyboard focus stays on the outer combobox element the whole time, and aria-activedescendant contains the id of the highlighted option, so the screen reader announces that option as if it had focus. aria-controls tells the screen reader which list belongs to the dropdown, and useId generates the id values that connect them. The other common approach is the roving tabindex in the next example, where focus really does move from item to item.

function Dropdown({ items, onSelect }) {
  const [isOpen, setIsOpen] = useState(false);
  const [selectedIndex, setSelectedIndex] = useState(0);

  const handleKeyDown = (e) => {
    if (!isOpen && (e.key === ' ' || e.key === 'Enter')) {
      setIsOpen(true);
      e.preventDefault();
      return;
    }
    if (isOpen) {
      if (e.key === 'ArrowDown') {
        setSelectedIndex((prev) => Math.min(prev + 1, items.length - 1));
      } else if (e.key === 'ArrowUp') {
        setSelectedIndex((prev) => Math.max(prev - 1, 0));
      } else if (e.key === 'Enter' || e.key === ' ') {
        onSelect(items[selectedIndex]);
        setIsOpen(false);
      } else if (e.key === 'Escape') {
        setIsOpen(false);
      } else {
        return; // let Tab and other keys behave normally
      }
      e.preventDefault();
    }
  };

  const listboxId = useId();

  return (
    <div
      role="combobox"
      aria-expanded={isOpen}
      aria-haspopup="listbox"
      aria-controls={listboxId}
      aria-activedescendant={isOpen ? `${listboxId}-${selectedIndex}` : undefined}
      tabIndex={0}
      onKeyDown={handleKeyDown}
    >
      <div className="dropdown-trigger">{items[selectedIndex].label}</div>
      {isOpen && (
        <ul role="listbox" id={listboxId}>
          {items.map((item, index) => (
            <li
              key={item.id}
              id={`${listboxId}-${index}`}
              role="option"
              aria-selected={index === selectedIndex}
            >
              {item.label}
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}

Tab Panel with Roving Tabindex

Tabs use a technique called “roving tabindex”, where only the active tab has tabIndex={0} and the others have -1. Pressing Tab moves focus to the active tab, and the arrow keys move between the tabs.

function TabPanel({ tabs }) {
  const [activeTab, setActiveTab] = useState(0);
  const tabRefs = useRef([]);

  // Roving tabindex only works if focus moves along with the active tab
  const selectTab = (index) => {
    setActiveTab(index);
    tabRefs.current[index]?.focus();
  };

  const handleKeyDown = (e) => {
    if (e.key === 'ArrowRight') selectTab((activeTab + 1) % tabs.length);
    else if (e.key === 'ArrowLeft') selectTab((activeTab - 1 + tabs.length) % tabs.length);
    else if (e.key === 'Home') selectTab(0);
    else if (e.key === 'End') selectTab(tabs.length - 1);
    else return;
    e.preventDefault();
  };

  return (
    <div>
      <div role="tablist">
        {tabs.map((tab, index) => (
          <button
            key={tab.id}
            ref={(el) => (tabRefs.current[index] = el)}
            role="tab"
            aria-selected={activeTab === index}
            tabIndex={activeTab === index ? 0 : -1}
            onClick={() => setActiveTab(index)}
            onKeyDown={handleKeyDown}
          >
            {tab.label}
          </button>
        ))}
      </div>
      {tabs.map((tab, index) => (
        <div key={tab.id} role="tabpanel" hidden={activeTab !== index} tabIndex={0}>
          {tab.content}
        </div>
      ))}
    </div>
  );
}

A native <dialog> opened with showModal() gives you most of a modal’s keyboard behavior without any extra code. The browser moves focus into the dialog when it opens, stops Tab from moving focus to the rest of the page, and closes the dialog when the user presses Escape. In current browsers, it also sends focus back to the element that opened it.

function Modal({ isOpen, onClose, children }) {
  const dialogRef = useRef(null);
  const titleId = useId();

  useEffect(() => {
    const dialog = dialogRef.current;
    if (isOpen && !dialog.open) dialog.showModal();
    if (!isOpen && dialog.open) dialog.close();
  }, [isOpen]);

  return (
    <dialog ref={dialogRef} onClose={onClose} aria-labelledby={titleId}>
      <h2 id={titleId}>Modal Title</h2>
      <div>{children}</div>
      <button onClick={() => dialogRef.current.close()}>Close</button>
    </dialog>
  );
}

Pressing Escape and clicking the Close button both fire the dialog’s close event, so onClose is the one place the parent needs to update its state. If you can’t use <dialog>, the Focus Trap pattern covers moving focus into a custom modal and keeping it there yourself.

Focus Indicators

Browsers draw a focus outline by default, and they already show it only when :focus-visible matches. If you restyle the outline, :focus-visible gives keyboard users your outline without showing one to mouse users after a click. A rule like :focus { outline: none; } removes the indicator for everyone, so it’s best left out.

:focus-visible { outline: 2px solid #0066cc; outline-offset: 2px; }

@media (prefers-contrast: more) {
  :focus-visible { outline: 3px solid currentColor; }
}

On most sites, a skip link also helps keyboard users, because it lets them jump past the navigation to the main content, and Skip Links covers it. Application shortcuts, such as Ctrl+S to save, work best when they match the ones users already know from other apps, and each one needs preventDefault() to stop the browser’s own shortcut from running.

Benefits

  • Screen readers and other assistive technologies rely on keyboard interfaces, so working keyboard navigation is a large part of supporting them.
  • Power users can work faster with keyboard shortcuts than with a mouse and small click targets.
  • Keyboard operability is a WCAG Level A requirement, success criterion 2.1.1. Regulations such as Section 508 in the US, the DOJ’s ADA Title II rule, and the European Accessibility Act, through EN 301 549, require WCAG Level AA, which includes that criterion, so for many organizations, keyboard support is a legal obligation.
  • People with motor disabilities or temporary injuries who can’t use a mouse can still use your application.
  • Users can keep working without switching between the keyboard and the mouse, which helps most when they’re filling in forms or entering data.

Tradeoffs

  • Custom widgets take a lot of work. Semantic HTML gives you keyboard support without extra code, but a div styled as a button needs its own event handlers to copy the same behavior.
  • ARIA keyboard patterns can be complex. A full listbox can need Home, End, PageUp, PageDown, type-ahead search, and multiple selection modes, and each one has its own expected behavior.
  • Your keyboard shortcuts might conflict with browser shortcuts. To use Ctrl+S for save, you have to call preventDefault(), and that stops the browser’s own save-page shortcut from working.
  • Arrow keys normally scroll the page, so intercepting them for widget navigation can confuse users who expect the page to scroll. You need to decide carefully when to capture key events and when to let them propagate.
  • Roving tabindex is hard to maintain in lists where items change often, because you have to keep track of which element has tabindex="0" and which ones have -1.
  • Users can’t see keyboard shortcuts, so without a help modal or visible hints, they probably won’t know the shortcuts exist.
  • International keyboard layouts differ from QWERTY. Bracket keys are in different positions on AZERTY and other layouts, so some shortcuts can be awkward or impossible to press.
  • Focus indicators can clash with the visual design, because an indicator that’s visible enough for keyboard users is often more prominent than designers would like.
  • To test keyboard navigation, you have to actually use a keyboard, because automated scanners can’t tell whether the tab order and key behavior make sense to a person.

Summary

With keyboard navigation, people can use your application without a mouse, because all the interactive elements are focusable in a logical order and respond to the keys that users expect. Semantic HTML gives you most of this without extra code, and custom widgets are easiest to use when they follow the keyboard behavior in the WAI-ARIA Authoring Practices. People who can’t use a mouse depend on keyboard navigation, and power users can work faster with it too.

See also

Next in Accessibility Live Regions ARIA live regions let screen readers announce content that changes on the page, without moving the user's focus.

A monthly email
from Den Odell.

What I'm thinking about frontend patterns, plus news when the site changes.

No spam. Unsubscribe anytime.