Basic usage
This page walks through the minimal steps to show a context menu and then how to open it from code or close it.
Step 1: Create the menu
Call createContextMenu with at least a menu array. Each entry is an item (action), separator, or submenu.
import { createContextMenu } from "@enegalan/contextmenu.js";
import "@enegalan/contextmenu.js/dist/style.css";
const menu = createContextMenu({
menu: [
{ label: "Copy", shortcut: "Ctrl+C", onClick: () => copy() },
{ label: "Paste", shortcut: "Ctrl+V", onClick: ({ close }) => { paste(); close(); } },
{ type: "separator" },
{ type: "submenu", label: "More", children: [
{ label: "Rename", onClick: () => rename() },
{ label: "Delete", onClick: () => remove() },
]},
],
});Step 2: Define the menu tree
The menu option is an array of menu items. You can use:
- Actions —
label,onClick, optionalshortcut,icon,disabled,loading. - Separators —
{ type: "separator" }. - Submenus —
{ type: "submenu", label: "...", children: [...] }. - Links, checkboxes, radio groups, and labels — see API reference.
The example above uses actions, one separator, and one submenu with two actions.
Step 3: Attach to an element (open on right-click / long-press)
Call menu.bind(element) so the menu opens on right-click (desktop) or long-press (touch) on that element:
menu.bind(document.getElementById("my-area"));After this, right-clicking or long-pressing the element opens the menu at the pointer.
Opening from your own event
To open the menu from a custom handler (e.g. a button click or a specific contextmenu listener), prevent the default context menu and call open with the event:
element.addEventListener("contextmenu", (e) => {
e.preventDefault();
menu.open(e);
});The menu appears at the event coordinates.
Opening and closing from code
- Open at coordinates —
menu.open(x, y)ormenu.open(). With no arguments, the library uses thegetAnchorconfig. Returns a Promise that resolves with the selected item when the menu closes (orundefinedif closed without selection). - Open next to an element —
menu.open(button, { placement: "bottom-start", offset: { x: 0, y: 4 } }). See API reference for placement values. - Close —
menu.close(). Returns a Promise that resolves when the close animation finishes. - State —
menu.getState()returns{ isOpen, anchor, menu, rootElement }.
const selected = await menu.open(200, 100);
menu.close();
menu.open(button, { placement: "bottom-start" });
const { isOpen } = menu.getState();Summary: what to use when
For full API details see the API reference. For how the menu tree and positioning work see Concepts. For runnable demos see Basic menu and Programmatic control.