Skip to content

Context menu ​

A menu of actions for an element, opened with a right-click, Shift+F10 or the Menu key.

Installation ​

bash
npx bootcn add context-menu
bash
pnpm dlx bootcn add context-menu
bash
yarn dlx bootcn add context-menu
bash
bunx --bun bootcn add context-menu

The CLI also installs the design tokens and these components: dropdown. It prints the <link> and <script> tags to add to your layout.

Usage ​

Attach a menu to any focusable element (a file, a row, a card). Right-click opens it at the pointer; Shift+F10 or the Menu key opens it under the element. Offer the same actions somewhere visible too: touch devices and many users never right-click.

JavaScript API ​

  • data-bootcn-context-menu="<menu id>" on the element that owns the menu.
  • The menu is a role="menu" list of role="menuitem" buttons (with the Dropdown component's classes).
  • Event bootcn:context-menu:select on the trigger (bubbles), detail.value and detail.item.
  • Bootcn.contextMenu.show(trigger, x, y) / hide(returnFocus); init() / destroy().

Accessibility ​

  • The trigger is focusable and announces aria-haspopup="menu"; a visible hint (linked with aria-describedby) explains the keyboard shortcut.
  • Inside the menu: Up/Down, Home/End and first-letter typeahead move focus; Enter activates; Escape or Tab closes and returns focus to the trigger.
  • The menu stays inside the viewport and closes on scroll or resize.

Dependencies ​

  • Bootstrap 5.3+ CSS.
  • themes/tokens/tokens.css.
  • The dropdown component.

Source ​

The exact files the CLI installs (context-menu@1.0.0). View on GitHub · Report an issue

html
<button
  type="button"
  class="bootcn-context-menu__target"
  data-bootcn-context-menu="bootcn-context-menu-file"
  aria-haspopup="menu"
  aria-describedby="bootcn-context-menu-hint"
>
  <svg
    class="bootcn-icon"
    width="16"
    height="16"
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    stroke-width="2"
    stroke-linecap="round"
    stroke-linejoin="round"
    aria-hidden="true"
    focusable="false"
  >
    <path d="M14 3H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z" />
    <path d="M14 3v6h6" />
  </svg>
  <span>report.pdf</span>
</button>
<p class="bootcn-context-menu__hint" id="bootcn-context-menu-hint">
  Right-click the file, or focus it and press Shift+F10, for actions.
</p>

<ul
  class="dropdown-menu bootcn-dropdown__menu bootcn-context-menu"
  id="bootcn-context-menu-file"
  role="menu"
  aria-label="File actions"
>
  <li role="none">
    <button
      class="dropdown-item bootcn-dropdown__item"
      type="button"
      role="menuitem"
      tabindex="-1"
      data-value="open"
    >
      Open <span class="bootcn-dropdown__shortcut" aria-hidden="true">⌘O</span>
    </button>
  </li>
  <li role="none">
    <button
      class="dropdown-item bootcn-dropdown__item"
      type="button"
      role="menuitem"
      tabindex="-1"
      data-value="rename"
    >
      Rename <span class="bootcn-dropdown__shortcut" aria-hidden="true">⌘R</span>
    </button>
  </li>
  <li role="none">
    <button
      class="dropdown-item bootcn-dropdown__item"
      type="button"
      role="menuitem"
      tabindex="-1"
      data-value="duplicate"
    >
      Duplicate <span class="bootcn-dropdown__shortcut" aria-hidden="true">⌘D</span>
    </button>
  </li>
  <li role="separator"><hr class="dropdown-divider bootcn-dropdown__divider" /></li>
  <li role="none">
    <button
      class="dropdown-item bootcn-dropdown__item bootcn-dropdown__item--destructive"
      type="button"
      role="menuitem"
      tabindex="-1"
      data-value="delete"
    >
      Delete
    </button>
  </li>
</ul>
css
.bootcn-context-menu__target {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
  width: 100%;
  max-width: 20rem;
  height: 9rem;
  border: var(--bootcn-border-width) dashed var(--bootcn-border-color);
  border-radius: var(--bootcn-radius-lg);
  background: transparent;
  color: var(--bootcn-foreground);
  font-size: 0.875rem;
}

.bootcn-context-menu__target .bootcn-icon {
  width: 1.5rem;
  height: 1.5rem;
  color: var(--bootcn-muted-foreground);
}

.bootcn-context-menu__target:focus-visible {
  outline: 0;
  box-shadow: var(--bootcn-focus-ring);
}

.bootcn-context-menu__hint {
  margin: 0.5rem 0 0;
  color: var(--bootcn-muted-foreground);
  font-size: 0.8125rem;
}

/* Positioned at the pointer by context-menu.js. */
.bootcn-context-menu.show {
  position: fixed;
  z-index: 1060;
  margin: 0;
}
js
(function () {
  'use strict';

  const ns = (window.Bootcn = window.Bootcn || {});
  if (ns.contextMenu) return; // already loaded: idempotent

  const TRIGGER = '[data-bootcn-context-menu]';
  let open = null; // { menu, trigger }
  let listening = false;

  function menuItems(menu) {
    return Array.from(
      menu.querySelectorAll('[role="menuitem"], [role="menuitemcheckbox"], [role="menuitemradio"]'),
    ).filter((item) => !item.disabled && item.getAttribute('aria-disabled') !== 'true');
  }

  // Up/Down/Home/End and typeahead inside an open menu. Returns true if handled.
  function navigateMenu(menu, event) {
    const items = menuItems(menu);
    const index = items.indexOf(document.activeElement);
    let next = null;
    if (event.key === 'ArrowDown') next = items[(index + 1) % items.length];
    else if (event.key === 'ArrowUp') next = items[(index - 1 + items.length) % items.length];
    else if (event.key === 'Home') next = items[0];
    else if (event.key === 'End') next = items[items.length - 1];
    else if (event.key.length === 1 && /\S/.test(event.key)) {
      const key = event.key.toLowerCase();
      const rotated = items.slice(index + 1).concat(items.slice(0, index + 1));
      next = rotated.find((item) => item.textContent.trim().toLowerCase().startsWith(key)) || null;
    }
    if (!next) return false;
    event.preventDefault();
    next.focus();
    return true;
  }

  function place(menu, x, y) {
    menu.classList.add('show');
    menu.style.left = '0px';
    menu.style.top = '0px';
    const rect = menu.getBoundingClientRect();
    const left = Math.max(8, Math.min(x, window.innerWidth - rect.width - 8));
    const top = Math.max(8, Math.min(y, window.innerHeight - rect.height - 8));
    menu.style.left = left + 'px';
    menu.style.top = top + 'px';
  }

  function show(trigger, x, y) {
    const menu = document.getElementById(trigger.getAttribute('data-bootcn-context-menu'));
    if (!menu) return;
    hide(false);
    place(menu, x, y);
    trigger.setAttribute('aria-expanded', 'true');
    open = { menu: menu, trigger: trigger };
    const first = menuItems(menu)[0];
    if (first) first.focus();
  }

  function hide(returnFocus) {
    if (!open) return;
    const { menu, trigger } = open;
    open = null;
    menu.classList.remove('show');
    trigger.setAttribute('aria-expanded', 'false');
    if (returnFocus) trigger.focus();
  }

  function onContextMenu(event) {
    const trigger = event.target.closest(TRIGGER);
    if (!trigger) return;
    event.preventDefault();
    show(trigger, event.clientX, event.clientY);
  }

  function onKeydown(event) {
    if (open) {
      if (event.key === 'Escape') {
        event.preventDefault();
        hide(true);
        return;
      }
      if (event.key === 'Tab') {
        hide(true);
        return;
      }
      if (open.menu.contains(document.activeElement)) navigateMenu(open.menu, event);
      return;
    }
    const trigger = event.target.closest && event.target.closest(TRIGGER);
    if (!trigger) return;
    if ((event.shiftKey && event.key === 'F10') || event.key === 'ContextMenu') {
      event.preventDefault();
      const rect = trigger.getBoundingClientRect();
      show(trigger, rect.left, rect.bottom);
    }
  }

  function onClick(event) {
    if (!open) return;
    const item = event.target.closest('[role="menuitem"]');
    if (item && open.menu.contains(item)) {
      const trigger = open.trigger;
      hide(true);
      trigger.dispatchEvent(
        new CustomEvent('bootcn:context-menu:select', {
          bubbles: true,
          detail: { value: item.getAttribute('data-value'), item: item },
        }),
      );
      return;
    }
    if (!open.menu.contains(event.target)) hide(false);
  }

  function onScrollOrResize() {
    hide(false);
  }

  function init() {
    document.querySelectorAll(TRIGGER).forEach((trigger) => {
      if (!trigger.hasAttribute('aria-expanded')) trigger.setAttribute('aria-expanded', 'false');
    });
    if (listening) return;
    document.addEventListener('contextmenu', onContextMenu);
    document.addEventListener('keydown', onKeydown);
    document.addEventListener('click', onClick);
    window.addEventListener('resize', onScrollOrResize);
    window.addEventListener('scroll', onScrollOrResize, true);
    listening = true;
  }

  function destroy() {
    hide(false);
    if (!listening) return;
    document.removeEventListener('contextmenu', onContextMenu);
    document.removeEventListener('keydown', onKeydown);
    document.removeEventListener('click', onClick);
    window.removeEventListener('resize', onScrollOrResize);
    window.removeEventListener('scroll', onScrollOrResize, true);
    listening = false;
  }

  ns.contextMenu = { init: init, destroy: destroy, show: show, hide: hide };

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
  } else {
    init();
  }
})();

Released under the MIT License. Not affiliated with Bootstrap or shadcn/ui.