How to create context menu with jQuery contextMenu plugin

How to create context menu with jQuery contextMenu plugin

INTRODUCTION:

The contextMenu Plugin was designed for web applications in need of menus on a possibly large amount of objects. Unlike other implementations, contextMenu treats the menu as the primary object. That means, that a single menu is defined that can be used by multiple objects. Unlike the mentioned plugins, contextMenu doesn't need to bind itself to triggering objects. This allows injecting and removing triggers without having to re-initialize or update contextMenu.

contextMenu can provide a simple list of clickable commands, or offer an in-menu form. This makes very simple attribute modification possible

HOMEPAGE

Checkout contextMenu homepage: http://medialize.github.io/jQuery-contextMenu/

Github: https://github.com/medialize/jQuery-contextMenu

FEATURES

  • trigger contextMenu with right-click, left-clickhover or own custom trigger events
  • delegated event handling removing the need for re-initialization when trigger objects are added / removed
  • dynamic on-demand menu creation
  • optional icons for commands
  • input elements (text, textarea, checkbox, radio, select) within the menu
  • custom html elements (command free)
  • show/hide callbacks to update the state of commands
  • small memory footprint even with hundreds of trigger objects
  • adjust position of menu to fit in viewport
  • enable / disable commands
  • nested sub-menus
  • full keyboard interaction
  • HTML5 <menu> support
  • CSS is for styling, javascript is not...

USAGE

1. Add CSS, Javascript dependencies:

<link rel='stylesheet prefetch' href='http://medialize.github.io/jQuery-contextMenu/src/jquery.contextMenu.css'>
<script src='//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js'></script>
<script src='http://medialize.github.io/jQuery-contextMenu/src/jquery.contextMenu.js'></script>

2. Add HTML to trigger the menu

<div class="context-menu-one box menu-1">
    <strong>Right click me</strong>
</div>

3. Call javascript to create menu when Document ready

$(function(){
    $.contextMenu({
        selector: '.context-menu-one', 
        callback: function(key, options) {
            var m = "clicked: " + key;
            window.console && console.log(m) || alert(m); 
        },
        items: {
            "edit": {name: "Edit", icon: "edit"},
            "cut": {name: "Cut", icon: "cut"},
            "copy": {name: "Copy", icon: "copy"},
            "paste": {name: "Paste", icon: "paste"},
            "delete": {name: "Delete", icon: "delete"},
            "sep1": "---------",
            "quit": {name: "Quit", icon: "quit"}
        }
    });
    
    $('.context-menu-one').on('click', function(e){
        console.log('clicked', this);
    })
});

DEMO

See the Pen jQuery contextMenu by Thanh Nguyen (@genievn) on CodePen.