
context-menu.js is a zero-dependency JavaScript library that creates a pretty clean, highly customizable context menu as you right-click on the page.
How to use it:
1. Insert the JavaScript context-menu.js and Stylesheet context-menu.js into the document.
<link href="context-menu.css" rel="stylesheet"> <script src="context-menu.js"></script>
2. Code your menu structure in the JavaScript. The menu structure consists of a theme and a list of items. Each item consists of an icon (requires Font Awesome), a name and an action to perform on click.
const menu = new ContextMenu({
'theme': 'default', // or 'blue'
'items': [
{'icon': 'envelope', 'name': 'jQuery', action: () => console.log('jQuery') },
{'icon': 'download', 'name': 'Script', action: () => console.log('Script') },
{'icon': 'trash', 'name': 'Net', action: () => console.log('Net') },
]
});3. Code the context menu open function.
function openContextMenu(evt){
// prevent default event
evt.preventDefault();
// open the menu with a delay
const time = menu.isOpen() ? 100 : 0;
// hide the current menu (if any)
menu.hide();
// display menu at mouse click position
setTimeout(() => { menu.show(evt.pageX, evt.pageY) }, time);
// close the menu if the user clicks anywhere on the screen
document.addEventListener('click', hideContextMenu, false);
}4. Code the context menu close function.
function hideContextMenu(evt){
// hide the menu
menu.hide();
// remove the listener from the document
document.removeEventListener('click', hideContextMenu);
}5. Attach the context menu to your document or a container element you specify.
document.addEventListener('contextmenu', openContextMenu, false);






