Focus Management in Dropdowns
You'll learn how to properly move, trap, and restore focus when users interact with dropdown menus.
When a user opens a dropdown menu, their keyboard focus needs to go somewhere useful—otherwise they're left stranded, pressing Tab into the void. Managing focus properly means making sure focus moves into the menu when it opens, stays within the menu while it's active, and returns to the trigger button when it closes.
Opening the Menu
When a user clicks a menu button or presses Enter/Space, focus should move to either:
- The first menu item, or
- The previously selected item (if applicable)
This ensures keyboard users can immediately navigate menu items with arrow keys (as covered in your vertical navigation lessons).
function openMenu(menuButton, menu) {
menu.classList.add('open');
const firstItem = menu.querySelector('[role="menuitem"]');
firstItem.focus();
}
Trapping Focus Inside
While the menu is open, focus must stay inside it—users shouldn't accidentally Tab out into background content. Use the focus trap pattern you learned earlier: intercept Tab keypresses and cycle focus between the first and last menu items.
Returning Focus on Close
When the menu closes (via Escape, clicking outside, or selecting an item), focus must return to the trigger button. This is critical for keyboard users to maintain their place on the page.
function closeMenu(menuButton, menu) {
menu.classList.remove('open');
menuButton.focus(); // Return focus to trigger
}
Think of it like a phone conversation: you call someone (open menu), talk (navigate items), then hang up and return to what you were doing (focus back to button).
Key Takeaway: Focus management in dropdowns requires three steps—move focus into the menu on open, trap it while active, and return it to the trigger on close.