Skip to content

Context Menu

The Context Menu component provides a customizable right-click menu for elements on your page. It allows you to create hierarchical menus with icons, links, and custom actions.

The Context Menu component depends on the following components:

  • D-Menu
  • Dropdown (for sub-menus)
<script>
Metro.contextMenu([
{
text: "Home",
href: "index.html",
icon: "<span class='mif-home'>"
},
{
text: "About",
href: "about.html",
icon: "<span class='mif-person'>"
},
{
type: "divider"
},
{
text: "Click",
onclick: "alert('Click!')"
}
]);
</script>
<div id="myElement">Right-click on me</div>
<script>
Metro.contextMenu([
{
text: "Element Menu",
href: "index.html",
icon: "<span class='mif-home'>"
}
], document.getElementById("myElement"));
</script>
<script>
Metro.contextMenu([
{
text: "Menu",
icon: "<span class='mif-menu'>",
items: [
{
text: "Sub-Item 1",
onclick: "alert('Sub-Item 1')"
},
{
text: "Sub-Item 2",
onclick: "alert('Sub-Item 2')"
}
]
}
]);
</script>

The Metro.contextMenu() function accepts the following parameters:

ParameterTypeDefaultDescription
itemsArray[]Array of menu item objects
elementDOM ElementdocumentThe element to attach the context menu to
PropertyTypeDescription
textStringThe text to display in the menu item
hrefStringOptional URL for the menu item
iconStringOptional HTML for an icon
onclickFunction/StringFunction or string to execute when the item is clicked
itemsArrayOptional array of sub-menu items
typeStringSet to “divider” to create a divider line
disabledBooleanSet to true to disable the menu item
attributesObjectAdditional HTML attributes to add to the menu item

The Context Menu component doesn’t expose specific API methods beyond its initialization function.

The Context Menu component doesn’t have specific events, but you can define custom click handlers for each menu item using the onclick property.

The Context Menu component inherits styling from the D-Menu component and uses the following z-index variable:

VariableDefault (Light)Dark ModeDescription
—zindex-fixed10301030Base z-index for fixed elements

The context menu’s z-index is set to var(--zindex-fixed) + 1 to ensure it appears above other fixed elements.

  • .context-menu - The main context menu class
  • .d-menu - Inherited from the D-Menu component
  • .divider - Class for menu dividers
  • .dropdown-toggle - Class for items with sub-menus
  • The context menu appears at the cursor position when right-clicking on the target element
  • The menu automatically hides when clicking anywhere else on the page
  • Sub-menus are displayed as dropdown menus
  • Menu items can be disabled by setting the disabled property to true