Add Custom Context Menus To Any HTML Element – vanilla-context-menu

Category: Javascript , Menu & Navigation | September 20, 2022
Author:GeorgianStan
Views Total:2 views
Official Page:Go to website
Last Update:September 20, 2022
License:MIT

Preview:

Add Custom Context Menus To Any HTML Element – vanilla-context-menu

Description:

A context menu is a feature of many applications. It’s a listing of options that appears on right-click. That usually provides some additional functions to process the thing that was right-clicked.

vanilla-context-menu is a simple JavaScript library that easily adds custom context menus to any HTML elements. This is a vanilla JS approach that doesn’t depend on other libraries and frameworks.

How to use it:

1. Install and import the vanilla-context-menu.

# NPM
$ npm i vanilla-context-menu
import VanillaContextMenu from 'vanilla-context-menu';
// Browser
<script src="/path/to/dist/vanilla-context-menu.js"></script>

2. Define your menu items in a JS array as follows:

const myMenu = [
      {
      label: 'Copy',
      callback: () => {
        console.log('Option 1 was clicked');
      },
      },
      'hr', // separator
      {
        label: 'Option 2',
        callback: anotherFunction,
        preventCloseOnClick: false,
        iconClass: 'fa fa-scissors', // custom icon
      },
      // ...
],

3. Initialize the library and attach the context menu to the element you specify.

const myContextMenu = new window.VanillaContextMenu({
      scope: document.querySelector('#container'),
      menuItems: myMenu,
});

4. Optional settings:

const myContextMenu = new window.VanillaContextMenu({
      // required
      scope: document.querySelector('#container'),
      menuItems: myMenu,
      // optional
      customClass: '',
      customThemeClass: '',
      preventCloseOnClick: false,
      transitionDuration: 200,
      theme: 'black', // or 'white'
});

5. Update options.

myContextMenu.updateOptions(configurableOptions)

Changelog:

v1.3.0 (09/20/2022)

  • Add a new property for MenuItem to display an icon as an HTML string. The HTML will be sanitized internally using DOMPurify.

You Might Be Interested In:


Leave a Reply