Create Custom Context Menus In Vanilla JavaScript – context-menu.js

Category: Javascript , Menu & Navigation | January 30, 2018
Author: mturco
Views Total: 840
Official Page: Go to website
Last Update: January 30, 2018
License: MIT

Preview:

Create Custom Context Menus In Vanilla JavaScript – context-menu.js

Description:

context-menu.js is a JavaScript/LESS plugin that helps you create custom, dynamic, native-looking context menus inside any container element you specify.

How to use it:

Install and import the context-menu.js into your project.

# NPM
$ npm install context-menu --save
// ES 6
import ContextMenu from 'ContextMenu';

// CommonJS:
const ContextMenu = require('ContextMenu');

Include the UMD version of context-menu.js on the web page.

<script src="context-menu.js"></script>

Define the menu items in the JavaScript:

var items = [
    { name: 'Cut', fn: function(target) { console.log('Cut', target); }},
    { name: 'Copy', fn: function(target) { console.log('Copy', target); }},
    { name: 'Paste', fn: function(target) { console.log('Paste', target); }},
    {},
    { name: 'Select All', fn: function(target) { console.log('Select All', target); }},
];

Attach the context menu to an element.

<div class="default" tabindex="0">Default theme</div>
var myMenu = new ContextMenu('.default', items);

Add an additional CSS class to the context menu. Useful for custom menu styles.

var myMenu = new ContextMenu('.default', items,{
    className: 'custom-theme',
    minimalStyling: true
});

Event listeners.

// events: created, shown, hidden, itemselected
instance.on('shown', function);
instance.off('shown', function);

Leave a Reply