Horizontal Navigation in Toolbars
What you'll learn: How to implement left and right arrow key navigation for toolbar buttons, making them keyboard-accessible for power users.
The Core Idea
Toolbars are horizontal groupings of action buttons (like Bold, Italic, Underline in a text editor). Unlike vertical menus, users expect to navigate toolbars using Left Arrow and Right Arrow keys instead of Up and Down. This horizontal navigation pattern matches the visual layout and feels natural.
Think of it like a row of light switches on your wall. You move horizontally across them, not vertically. Your code should mirror this spatial arrangement.
Implementing Horizontal Arrow Navigation
You've already learned about handling keydown events, preventing default behavior, and the roving tabindex pattern. Now apply those specifically to horizontal movement:
toolbar.addEventListener('keydown', (e) => {
const buttons = Array.from(toolbar.querySelectorAll('button'));
const currentIndex = buttons.indexOf(document.activeElement);
let nextIndex;
if (e.key === 'ArrowRight') {
e.preventDefault();
nextIndex = currentIndex + 1;
if (nextIndex >= buttons.length) nextIndex = 0; // wrap to start
} else if (e.key === 'ArrowLeft') {
e.preventDefault();
nextIndex = currentIndex - 1;
if (nextIndex < 0) nextIndex = buttons.length - 1; // wrap to end
} else {
return; // ignore other keys
}
buttons[nextIndex].focus();
});
Only the currently focused button has tabindex="0"; all others have tabindex="-1". When you move focus with arrow keys, update these values accordingly.
Why This Matters
Horizontal navigation respects user expectations based on visual layout. Screen reader users and keyboard-only users navigate more efficiently when controls behave consistently with their orientation.
Key Takeaway: Implement Left/Right arrow navigation for horizontal toolbars using keydown event handling, wrapping focus at boundaries, and coordinating with the roving tabindex pattern.