Pretty Clean Context Menu In Pure JavaScript – Contextual.js

Category: Javascript , Menu & Navigation | April 28, 2020
Author:LucasReade
Views Total:7,321 views
Official Page:Go to website
Last Update:April 28, 2020
License:MIT

Preview:

Pretty Clean Context Menu In Pure JavaScript – Contextual.js

Description:

Contextual.js is a vanilla JS plugin that attaches a dynamic, customizable, multi-level context/pop-up menu to your element. Without any dependencies.

How to use it:

Download and import the Contextual.js plugin’s files into the html file.

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

Create an array of menu items containing titles, tips, icons, separators, and callback functions as follows:

  • icon
  • cssIcon
  • label
  • type
  • onClick
  • shortcut
  • submenu
  • markup
  • enabled
const menuItems = [
      new ContextualItem({type:'custom', markup: `<span>Custom item - add what you like</span>` }),
      new ContextualItem({type:'multi', items: [
          new ContextualItem({label:'Copy'}),
          new ContextualItem({label:'Cut'}),
          new ContextualItem({label:'Paste'}),
      ]}),
      new ContextualItem({label:'Button', onClick: () => {console.log('Item 1 clicked')}, shortcut:'Ctrl+A' }),
      new ContextualItem({type:'seperator'}),
      new ContextualItem({type:'submenu', label:'Sub menu', submenu:[
          new ContextualItem({label:'Subitem 1'}),
          new ContextualItem({label:'Subitem 2'}),
          new ContextualItem({label:'Subitem 3'}),
      ]}),
      new ContextualItem({label:'Disabled button', shortcut:'Ctrl+B', enabled: false }),
]

Attach the context menu to an element you specify.

const myInstance = document.getElementById('element');
// triggeredd on right click
myInstance.addEventListener('contextmenu',function(ev){
  ev.preventDefault();
  new contextualMenu({
      items: menuItems
  });
});

Set how the menu appears, follow the mouse or sticky.

new contextualMenu({
    items: menuItems,
    isSticky: false
});

Set the width of the menu.

new contextualMenu({
    items: menuItems,
    width: '200px'
});

Changelog:

04/28/2020

  • Update contextual.js

03/14/2020

  • Clean up

03/09/2020

  • Initial floating menu update

03/04/2020

  • minor fixes

10/04/2019

  • added animations for sub-menus

05/10/2019

  • rewrite and fix submenu

04/25/2019

  • Code clean up and restructure

You Might Be Interested In:


Leave a Reply