Context Menu
A secondary menu triggered by right-click or long-press that surfaces contextually relevant actions for the focused element.
Plain English
Context menus are powerful but invisible — users who discover them feel rewarded with efficiency shortcuts, but they cannot be the only path to an action. Right-click context menus are desktop-only; on mobile, long-press opens them. The most important rule: only show actions relevant to the right-clicked element. A context menu on an image should offer "Copy image," "Save as," "Open in new tab" — not generic app-level actions. Always support keyboard navigation (arrow keys, Enter to select, Escape to close).
Technical
Listen on contextmenu event (e.preventDefault() to suppress the browser default). Position the menu: position: fixed; top: e.clientY; left: e.clientX — then clamp to viewport: if left + menuWidth > window.innerWidth, shift left by menuWidth. Close on Escape (global keydown listener), click outside (mousedown listener on document), or item selection. Animation: scale(0.95) opacity(0) → scale(1) opacity(1), 150ms ease-out. ARIA: role="menu" on the container, role="menuitem" on items.
Live Demo
Context menu
Context menus reward discovery — but never make them the only path to an important action.
Usage
✓ Good usage
Right-clicking a file in a list opens a menu with "Open," "Rename," "Duplicate," and "Delete" — all contextually relevant to that specific file.
✗ Bad usage
A context menu that is the only way to access "Delete" — a user who does not discover right-click can never delete items.
Recommended values
- Trigger: contextmenu event + preventDefault
- Close: Escape, click-outside, item-select
- Position: clamp to viewport (do not overflow edges)
- Min width: 160–200px
- Item height: 36–44px for comfortable tap/click targets
- Animation: scale 0.95→1 + opacity, 150ms ease-out
Common mistakes
- Missing click-outside handler — the menu stays open indefinitely unless the user deliberately closes it.
- Context menu as the only path to an action — right-click is discoverable only by accident; always provide a visible UI path too.
- No keyboard navigation — a menu with no arrow-key support excludes keyboard users entirely.
AI Prompt Example
Copy this into Claude, Cursor, Bolt, or v0.
Add a custom context menu to the file list. Prevent the default browser context menu. Show a custom menu with "Open", "Rename", "Duplicate", a divider, and "Delete" (destructive red). Position the menu at the cursor, clamped to the viewport. Close on Escape, click-outside, or item selection. Add role="menu" and role="menuitem" ARIA attributes.