Roving Tabindex Keyboard Navigation

Keep one list item tabbable while arrow keys move focus between options, wrapping at the ends, the standard roving tabindex pattern.

TypescriptData Integrity

Code

typescriptsnippet
40 lines
// Roving tabindex pattern for keyboard navigation: exactly one item is
// tabbable, arrow keys move focus between options, the rest stay at -1
const items = ['Cut', 'Copy', 'Paste', 'Delete'];

const list = document.createElement('ul');
list.setAttribute('role', 'listbox');
document.body.append(list);

const options: HTMLLIElement[] = items.map((label, index) => {
  const li = document.createElement('li');
  li.setAttribute('role', 'option');
  li.textContent = label;
  li.tabIndex = index === 0 ? 0 : -1;
  list.append(li);
  return li;
});

function focusAt(index: number): void {
  const next = (index + options.length) % options.length; // wrap at ends
  for (const [i, item] of options.entries()) {
    item.tabIndex = i === next ? 0 : -1;
  }
  options[next].focus();
}

list.addEventListener('keydown', (event) => {
  const current = options.indexOf(document.activeElement as HTMLLIElement);
  if (event.key === 'ArrowDown') focusAt(current + 1);
  else if (event.key === 'ArrowUp') focusAt(current - 1);
  else if (event.key === 'Home') focusAt(0);
  else if (event.key === 'End') focusAt(options.length - 1);
  else return;
  event.preventDefault();
});

console.log('tabbable option:', items[options.findIndex((item) => item.tabIndex === 0)]);

focusAt(2);
list.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowDown', bubbles: true }));
console.log('after arrow down, focused:', document.activeElement?.textContent);

What the code does

Roving Tabindex Keyboard Navigation comes down to the functions next and focusAt.

The loop for (const [i, item] of options.entries()) is the only repeated construct.

Points of care

  • The snippet leans on document — browser-only surfaces a bare Node process cannot provide.

Applying it

Signature: const next = (index + options.length)

Output lines are prefixed (tabbable option:, after arrow down, focused:), making each step’s effect easy to spot.

Statements that matter

const options: HTMLLIElement[] = items.map((label, index) => {
  const li = document.createElement('li');
  li.setAttribute('role', 'option');
  li.textContent = label;
  li.tabIndex = index === 0 ? 0 : -1;
  list.append(li);
  return li;
});

Interactive Tools for This Topic

FAQ

Does Roving Tabindex Keyboard Navigation run in plain Node.js?
No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.