Usage
How it works
Firstly, you need to get the idea of how a context menu
is created, there are two elements involved when creating a context menu
:
- An menu element as the
context menu
- An target element that the
context menu
applies to, you would mostly right click on it.
Example
typescript
import { createContextMenu } from '@contextmenu/core'
// the element as the `contextmenu`
const menu = document.getElementById('menu')
// the above `contextmenu` applies to
const target = document.getElementById('target')
// now you're all set,
// right click on the `target`
// then you'll see the `menu` pops up.
const ctxMenu = createContextMenu(menu, { target })
The default target
element is window
if not specified.
typescript
import { createContextMenu } from '@contextmenu/core'
const menu = document.getElementById('menu')
// the default `target` is the global `window`.
const ctxMenu = createContextMenu(menu)
Demo
right click on me
Nested Menu
The ContextMenu
caries an element as the menu that pops up while triggering contextmenu
event (mostly by right clicking), the element could be your custom DOM, or, the built-in nested menu MenuGroup
.
The structure may look like:
shell
ContextMenu => A custom DOM element
# or
ContextMenu => MenuGroup{ rootElement, MenuItems }
You can use createNestedMenu
function to do that, just provide a valid descriptor
that describes what your menu looks like.
DEMO
HTML structure
html
<div id="group">
<div id="item1">Item1</div>
<div id="item2">Item2</div>
<div id="item3">
<p>Item3</p>
<div id="nestedGroup">
<div id="item1">Nested1</div>
<div id="item2">Nested2</div>
</div>
</div>
</div>
JavaScript code
js
import { createNestedMenu } from '@contextmenu/core'
const subMenu = document.createElement('div')
subMenu1.innerHTML = '<li>Nested1</li>'
+ '<li>Nested2</li>'
+ '<li>Nested3</li>'
const ctx = createNestedMenu({
// `el` could be a CSS selector or a real DOM.
// You must ensure the DOM of the selector exists if providing a selector.
el: '#group',
items: [
{ el: '#item1' },
{ el: '#item2', subMenu: { el: subMenu } },
{ el: '#item3', subMenu: { el: '#nestedGroup' } },
],
})
Type Definition
ts
export function createNestedMenu(
descriptor: NestedMenu,
options?: ContextMenuOptions
): ContextMenu
export type NestedMenuElement = string | StylableElement
export interface NestedMenu {
el: NestedMenuElement
items?: {
el: NestedMenuElement
subMenu?: NestedMenu
}[]
}
Framework support
The description introduces the basic idea and it's used in native javascript, we also provide high level framework preset: