Frontend Patterns

Pattern

Focus Management

Control focus flow for modal dialogs, route changes, and dynamic content insertion.

Focus Management

Problem

Keyboard users get lost when focus isn’t managed properly. Opening a modal leaves focus on the trigger button beneath it, forcing users to tab through the entire page to reach modal controls. After navigating to a new route, focus stays at the bottom of the previous page. Screen reader users have no indication that new content appeared.

Solution

Programmatically move keyboard focus to appropriate elements as UI changes, especially when showing or hiding content. This ensures keyboard users can navigate logically without getting lost or trapped.

Example

This example demonstrates moving keyboard focus to a modal dialog when it opens so keyboard users can immediately interact with it.

// Web Component that manages focus when modal state changes
class Modal extends HTMLElement {
  set open(value) {
    this._open = value;
    if (value) {
      this.render();
      // Programmatically move focus to modal dialog for keyboard users
      this.querySelector('[role="dialog"]')?.focus();
    }
  }

  render() {
    if (this._open) {
      // Tabindex="-1" allows programmatic focus but not tab-to-focus
      this.innerHTML = `
        <div role="dialog" tabindex="-1">
          Modal content
        </div>
      `;
    }
  }
}

Benefits

  • Ensures keyboard users can navigate efficiently
  • Required for WCAG compliance and accessibility
  • Prevents users from getting lost after UI changes
  • Improves experience for screen reader users
  • Essential for modal dialogs and dynamic content

Tradeoffs

  • Can be disorienting if focus jumps unexpectedly
  • Requires careful thought about where focus should go
  • Easy to get wrong and create confusing experiences
  • May interfere with user expectations
  • Testing requires actual keyboard and screen reader usage
Stay Updated

Get New Patterns
in Your Inbox

Join thousands of developers receiving weekly insights on frontend architecture patterns

No spam. Unsubscribe anytime.