Vertical Navigation in Menus
You'll learn how to implement up/down arrow key navigation for dropdown and context menus using keyboard event handling.
What It Is
When users open a dropdown menu or context menu, they should be able to navigate through the options using the Up Arrow and Down Arrow keys, just like they can in native desktop applications. This creates a familiar, efficient interaction pattern for keyboard users who need to move through vertically stacked menu items.
How It Works
You listen for keydown events on menu items and respond to ArrowUp and ArrowDown keys. When pressed, you move focus to the previous or next menu item in the list. This is typically combined with the roving tabindex pattern you learned earlier—only one menu item has tabindex="0" at a time, while others have tabindex="-1".
Think of it like an elevator: pressing Down moves you to the next floor below, Up moves you to the floor above, and you can't skip floors—focus moves one item at a time in order.
Key implementation steps:
- Capture
keydownevents on the menu container or individual items - Check if the key is
ArrowDownorArrowUp - Calculate which item should receive focus next (with wrapping at the ends)
- Update the
tabindexvalues using roving tabindex - Call
.focus()on the target item - Prevent default scrolling behavior with
event.preventDefault()
This pattern is essential for dropdowns, context menus, select-like custom controls, and any vertically arranged interactive list.
Key Takeaway: Vertical menu navigation uses Up/Down arrow keys with keydown event handling to move focus sequentially through menu items, creating an accessible keyboard interface for list-based selections.