Course contentsShow
← Web Development
Lesson 1074 of 2,98219. Keyboard Navigation and FocusFree lesson

Roving tabindex Pattern

Managing tabindex dynamically so only one element in a group is tabbable.

Roving tabindex Pattern

You'll learn how to dynamically update tabindex values so that only one interactive element in a group can receive focus via the Tab key, while still allowing arrow-key navigation between all items.

What Problem Does This Solve?

Imagine a toolbar with 10 buttons. If all 10 are tabbable (tabindex="0"), keyboard users must press Tab 10 times just to move past the toolbar. That's exhausting!

The roving tabindex pattern solves this by making only the active element in a group tabbable, while setting all others to tabindex="-1" (programmatically focusable, but not in the tab sequence).

How It Works

  1. Initially: The first item in the group gets tabindex="0", all others get tabindex="-1"
  2. When arrow keys navigate: The currently focused item's tabindex becomes "-1", and the newly focused item's tabindex becomes "0", then you programmatically focus it
  3. Result: Tab enters the group once, lands on the active item. Arrow keys move within the group. Tab again exits the group entirely.

Think of it like a spotlight that follows the action—only one performer is "tabbable" at any moment, but you can still move the spotlight around with arrow keys.

Quick Pattern

function moveRovingTabindex(currentItem, nextItem) {
  currentItem.setAttribute('tabindex', '-1');
  nextItem.setAttribute('tabindex', '0');
  nextItem.focus();
}

This pattern is essential for toolbars, tab panels, radio groups, menus, and grid navigation—anywhere you have a collection of related interactive elements.

Key Takeaway: The roving tabindex pattern dynamically moves tabindex="0" to whichever element in a group is currently active, keeping only one item in the tab sequence while preserving arrow-key navigation.