Multi-level Context Menu In JavaScript – ContextmenuJS

Category: Javascript , Menu & Navigation | July 25, 2018
Author: m-thalmann
Views Total: 1,542
Official Page: Go to website
Last Update: July 25, 2018
License: MIT

Preview:

Multi-level Context Menu In JavaScript – ContextmenuJS

Description:

Yet another small, dynamic, multi-level context menu written in pure JavaScript.

ContextmenuJS enables you to create a right-click context menu from an array of menus object, with support for fade in/out animations, custom icons, disabled menu items, and an unlimited amount of menu levels.

Basic usage:

Link to the necessary JavaScript and CSS files.

<link rel="stylesheet" href="contextmenu.css">
<script src="contextmenu.js"></script>

Load a theme CSS (OPTIONAL)

<link rel="stylesheet" href="theme/contextmenu_dark.min.css">
<link rel="stylesheet" href="theme/contextmenu_light.min.css">

Create the menu data with the following key-value pairs.

var myMenu = [
    {
      "text": "Item 1",
      "sub": [
        {
          "text": "Item 1-1"
        },
        {
          "text": "Item 1-22"
        },
        {
          "type": ContextMenu.DIVIDER
        },
        {
          "text": "Item 1-3",
          "enabled": false,
          "sub": [
            {
              "text": "Item 1-3-1"
            }
          ]
        }
      ]
    },
    {
      "text": "Item 2",
      "icon": '<i class="fas fa-exclamation-circle"></i>', // font awesome icon
      "events": {
        "click": function(e){
          alert(e);
        }
      }
    }
];

Initialize the context menu.

menu = new ContextMenu(myMenu);

Attach the context menu to a specific container.

document.getElementById('YOUR-CONTAINER').addEventListener("contextmenu", function(e){
  menu.display(e);
});

Possible options to customize the context menu.

new ContextMenu(myMenu,{

    // close on window resize
    close_on_resize: true,

    // close on click
    close_on_click: true,

    // default icon or CSS classes
    default_icon: '',

    // default text
    default_text: ''

    // arrow icon for sub menus
    sub_icon: ''

    // mouse offset in pixels
    mouse_offset: 0
    
});

API methods.

// enable the context menu on a specfic container
menu.display(e, target);

// reload the context menu
menu.reload();  

// hide the context menu manually
menu.hide();  

// set new options
menu.setOptions(options); 

// override options
menu.changeOption(option, value);

// return options
menu.getOptions();

Changelog:

07/25/2018

  • Added two themes + minified versions
  • Fixed bug, where you could hover over the place where a submenu would be and it would be displayed

You Might Be Interested In:


Leave a Reply