Component Deep Dive #27: Context Menu
The context menu is a desktop interaction legacy. Replicating it on the web means dealing with browser defaults, boundary overflow, and focus traps - each one a pitfall.
Boundary Detection - 90% of Implementations Skip This
if (x + menuWidth > window.innerWidth) {
x = window.innerWidth - menuWidth - 8;
}
if (y + menuHeight > window.innerHeight) {
y = window.innerHeight - menuHeight - 8;
}
If a user right-clicks at the bottom-right corner, the menu overflows the viewport. You must render the menu first to get its dimensions, then check boundaries, then position.
Keyboard Navigation
A proper context menu must support: ArrowDown/ArrowUp for navigation, Home/End for jumping to first/last item, Enter/Space for activation. Each menuitem needs tabindex="-1" (programmatically focusable, but not in the tab sequence).
Focus Management
When the menu opens, focus moves to the first item. When it closes, focus returns to the trigger element. Without focus restoration, keyboard users get "lost" after closing the menu.
Touch Device Adaptation
Touch devices have no right-click. Use a 500ms long-press instead, with navigator.vibrate for haptic feedback on supported devices.
Common Pitfalls
- No boundary detection - menu overflows viewport
- No focus restoration - keyboard users lost after closing
- Using
pageX/pageY- breaks after scrolling, useclientX/clientY - No touch adaptation - mobile users can't trigger it
- Menu items as
<div>- not focusable, use<button>+role="menuitem" - Insufficient z-index - menu covered by other elements
The difficulty of a context menu isn't in opening it - it's in the cleanup after closing: focus restoration, keyboard navigation, boundary detection. Every detail matters.
This article was first published on Deskless Daily. Follow for more AI-driven tech content.
Top comments (0)