Skip to main content
Saved

Pattern Accessibility Beginner

Focus Management

You can move focus from JavaScript after route changes and other UI updates, so keyboard users always know where they are on the page.

Examples
React and Vue
Read
4 min

The problem

If a user opens a modal dialog and focus stays on the button behind the overlay, a screen reader user hears nothing about the dialog, and a keyboard user has to Tab through the rest of the page before they get to anything inside it.

The pattern

If a change in your UI means the user’s next step is somewhere else on the page, focus should move there. Focus management is about moving focus at those moments. Keeping focus inside a modal once it’s there is a separate job, covered in Focus Trap, and the keys that operate each widget are covered in Keyboard Navigation.

Problem

I’ve tested applications where navigating to a new page left focus on the navigation link that was clicked, so keyboard users had to Tab through thirty elements just to get to the new content, which is maddening.

If a user deletes a list item, the element that had focus is gone, and focus often drops back to the document body, so the next Tab starts from the top of the page.

Solution

Once a modal opens, focus should move into it, and when it closes, focus should go back to the element that opened it. After the user navigates to a new page in a single-page app (SPA), focus should move to the page heading, so screen reader users start at the new content instead of tabbing through navigation they’ve already passed.

After a list item is deleted, focus should move to the next item, or to the previous one if the deleted item was the last in the list. A notification only needs focus if the user has to act on it, such as a session timeout warning with a button to stay signed in. A message that users only need to hear can go in a live region, which screen readers announce without moving focus.

element.focus() moves focus programmatically. Non-interactive elements like headings or containers need tabindex="-1", which lets JavaScript focus them without adding them to the Tab order.

Before an overlay opens, your code should store a reference to the element that had focus, so it can put focus back there when the overlay closes.

An element can only be focused once it’s in the DOM. Frameworks render after your state change, so the focus() call has to run after that render, in a useEffect in React or after nextTick in Vue.

Some changes don’t need focus to move. When an accordion expands, for example, focus should stay on the accordion’s trigger, because the content that it reveals is next in the Tab order.

Example

Each version below saves document.activeElement before the modal opens, focuses the dialog once it has rendered, and puts focus back on the saved element when the modal closes. They don’t stop Tab from leaving the modal, which needs a native <dialog> or a Focus Trap.

class Modal extends HTMLElement {
  constructor() {
    super();
    this.previouslyFocusedElement = null;
  }

  set open(value) {
    this._open = value;
    if (value) {
      this.previouslyFocusedElement = document.activeElement;
      this.render(); // innerHTML is synchronous, so the dialog exists on the next line
      this.querySelector('[role="dialog"]')?.focus();
    } else {
      this.innerHTML = '';
      this.previouslyFocusedElement?.focus();
      this.previouslyFocusedElement = null;
    }
  }

  render() {
    if (this._open) {
      this.innerHTML = `
        <div role="dialog" aria-modal="true" tabindex="-1">
          <h2>Modal Title</h2>
          <button class="close">Close</button>
        </div>
      `;
      this.querySelector('.close').addEventListener('click', () => {
        this.open = false;
      });
    }
  }
}
customElements.define('modal-dialog', Modal);

Route Change Focus Management

If focus moves to the main heading after navigation, screen reader users can find the new content right away:

import { useEffect, useRef } from 'react';
import { Routes, useLocation } from 'react-router-dom';
import { getPageTitle } from './routes';

// Rendered inside <BrowserRouter>, so useLocation() has a router to get the location from
function App() {
  const location = useLocation();
  const mainContentRef = useRef(null);
  const isFirstRender = useRef(true);

  useEffect(() => {
    // Leave focus alone on the initial page load; only move it on navigation
    if (isFirstRender.current) {
      isFirstRender.current = false;
      return;
    }
    mainContentRef.current?.focus();
  }, [location.pathname]);

  return (
    <main>
      <h1 ref={mainContentRef} tabIndex={-1}>
        {getPageTitle(location.pathname)}
      </h1>
      <Routes>{/* routes */}</Routes>
    </main>
  );
}

List Item Deletion

After an item is deleted, focus moves to the next item, so users don’t lose their place. The setTimeout runs the focus() call after React has removed the deleted item:

function TodoList({ items, onDelete }) {
  const itemRefs = useRef({});

  const handleDelete = (id, index) => {
    onDelete(id);
    // The item after the deleted one, or the one before if it was last
    const nextItem = items[index + 1] ?? items[index - 1];
    if (nextItem) {
      setTimeout(() => itemRefs.current[nextItem.id]?.focus(), 0);
    }
  };

  return (
    <ul>
      {items.map((item, index) => (
        <li key={item.id} ref={el => itemRefs.current[item.id] = el} tabIndex={-1}>
          {item.text}
          <button onClick={() => handleDelete(item.id, index)}>Delete</button>
        </li>
      ))}
    </ul>
  );
}

Benefits

  • Keyboard users know where they are, because focus moves to a sensible place each time the UI changes.
  • You need proper focus management to meet WCAG 2.4.3, the Focus Order success criterion.
  • Screen readers announce content when focus moves to it, so users know when things change.
  • Modal dialogs become usable for keyboard users, who otherwise couldn’t get to the content inside them.
  • If focus behaves the same way throughout your app, users learn what to expect, and they can move through it faster the longer they use it.

Tradeoffs

  • Moving focus to the wrong place, or moving it when users don’t expect it, can confuse them more than not moving it at all.
  • You have to think carefully about where focus should go in each situation, because it isn’t always obvious.
  • The focus() call has to be timed to run after the framework has rendered, which adds setTimeout or nextTick calls that are easy to leave out.
  • Developers who haven’t seen the pattern before might be confused by tabindex="-1" on headings, but the headings need it so JavaScript can focus them.
  • Screen readers such as NVDA, JAWS, and VoiceOver announce focus changes differently, so it’s worth testing in more than one.
  • Moving focus only helps if users can see where it went, so you also need the visible focus indicators described in Keyboard Navigation.
  • The browser’s back and forward buttons shouldn’t move focus if the content hasn’t really changed, but a lot of apps get this wrong.
  • Moving focus on every small change makes it jump around the page, and users can lose their place.

Summary

Each time the page changes, such as when the route changes or a modal opens, your code should move keyboard focus somewhere sensible. Focus should move to the new content, and when a dialog closes, focus should go back to the button that opened it. If you get it right, focus management can make a single-page app feel as natural to keyboard users as a traditional multi-page site.

See also

Next in Accessibility Focus Trap A focus trap keeps keyboard focus inside a modal dialog or overlay, so pressing Tab can't move focus to the page behind it.

A monthly email
from Den Odell.

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

No spam. Unsubscribe anytime.