โœฆ StealThis .dev

Context Menu

Right-click context menu with nested sub-menus, keyboard navigation, icons, dividers, and disabled items.

Open in Lab
css vanilla-js
Targets: JS HTML

Code

Context Menu

A right-click context menu with nested sub-menus, icon support, dividers, destructive items, and full keyboard navigation. No dependencies.

Features

  • Opens at cursor position, clamped to viewport bounds
  • Nested sub-menu opens on hover or right-arrow key, closes on left-arrow
  • Disabled items are non-interactive
  • Destructive (Delete) item styled in red
  • Closes on outside click, left-click elsewhere, or Escape

How it works

  1. contextmenu event is intercepted on the demo area; preventDefault() suppresses the browser menu
  2. The menu is positioned with position: fixed at event.clientX / clientY, then clamped so it never overflows the viewport
  3. Sub-menus use position: absolute relative to their parent item, opening to the right
  4. Keyboard: ArrowDown/ArrowUp move focus between items; ArrowRight opens a sub-menu; ArrowLeft closes it; Enter activates the focused item

Accessibility

  • Menu uses role="menu", items use role="menuitem"
  • Disabled items carry aria-disabled="true"
  • Sub-menu trigger items have aria-haspopup="true" and aria-expanded