Fork me on GitHub

jQuery contextMenu

Register new contextMenu

To register a new contextMenu:

$.contextMenu( options );

options (at registration)

(string) selector

No Default Value - specification is Mandatory

The selector matching the trigger objects.

Example: "span.with-context".

(object) items

No Default Value - specification is Mandatory

Items to be listed in contextMenu. See Items.

Example: { one: {name: "one", callback: function(key, opt){ alert("Clicked on " + key); } }}

(selector | DOMElement) appendTo

default: document.body

Specifies the DOMElement the generated menu is to be appended to

Example: "#context-menus-container".

(string) trigger

default: "right"

Specifies the event to show the contextMenu

Possible values: "right", "left", "hover", "none"

(boolean) reposition

Specifies if a menu should be repositioned (true) or rebuilt (false) if a second trigger event (like a right click) is performed on the same trigger element (or its children) while the menu is still visible.

(int) delay

default: 200

Specifies the time in milliseconds to wait before showing the menu. Only applies to trigger: "hover"

(boolean) autoHide

default: false

Specifies if the menu must be hidden when the mouse pointer is moved out of the trigger and menu elements

(int) zIndex

default: 1

Specifies the offset to add to the calculated zIndex of the trigger element. Set to 0 to prevent zIndex manipulation

(string) className

Specifies additional classNames to add to the menu element

(object) animation

default: {duration: 500, show: "slideDown", hide: "slideUp"}

animation properties take effect on showing and hiding the menu. duration specifies the duration of the animation in milliseconds. show and hide specify jQuery methods to show and hide elements.

Possible show and hide animations: {show: "show", hide: "hide"}, {show: "fadeIn", hide: "fadeOut"}, …

(object) events

The show and hide events are triggered before the menu is shown or hidden.

The event handlers are executed in the context of the triggering object. this will thus reference the jQuery handle of the trigger object.

A reference to the current options object is passed

The event handlers may return false to prevent the show or hide process.

Example: {show: function(opt){ this.addClass('currently-showing-menu'); alert("Selector: " + opt.selector); }}

(function) position

Position the context menu.

The function is executed in the context of the trigger object.

The first argument ist the $menu jQuery object

The second and third arguments are x and y coordinates provided by the showing event

x and y may either be integers denoting the offset from the top left corner, undefined, or the string "maintain". If the string "maintain" is provided, the current position of the $menu must be used. If the coordinates are undefined, appropriate coordinates must be determined. An example of how this can be achieved is provided with determinePosition.

Example: {position: function($menu, x, y){$menu.css({top: 123, left: 123});}}

(function) determinePosition

Determine the position of the menu in respect to the given trigger object.

Hint: jQuery UI's position() may ease things up.

Example: $menu.css('display', 'block').position({ my: "center top", at: "center bottom", of: this, offset: "0 5"}).css('display', 'none');

(function) callback

Specifies the default callback to be used in case an item does not expose its own callback.

The default callback behaves just like item.callback.

Example: {callback: callback: function(key, opt){ alert("Clicked on " + key + " on element " + opt.$trigger.attr("id")); }}

(function) build

Callback that's supposed to return the options object on demand

The callback is executed with two arguments given: the jQuery reference to the triggering element and the original contextemnu event. It is executed without context (so this won't refer to anything useful).

If the build callback is found at registration, the menu is not built right away. The menu creation is delayed to the point where the menu is actually called to show. Dynamic menus don't stay in the DOM. After a menu created with build is hidden, its DOM-footprint is destroyed.

With build, only the options selector and trigger may be specified in the options object. All other options need to be returned from the build callback.

the build callback may return a boolean false to signal contextMenu to not display a context menu

{selector: ".awesome-menu",
build: function($trigger, e){
  return {
    callback: function(){},
    items: {
        foo: {name: "Foo"}
    }
  };
}};

options.items

The items map contains the commands to list in the menu. Each command has a unique key identifying an item object. The value may either be an item (properties explained below), or a string (which will insert a separator, disregarding the string's content).

var items = {
  command1: commandOptions,
  separator1: "-----",
  command2: commandOptions
}
(string) name

Specified the human readable name of the command in the menu

This is a mandatory property

(function) callback

Specifies the callback to execute if clicked on

The Callback is executed in the context of the triggering object. The first argument is the key of the command. The second argument is the options object. The Callback may return false to prevent the menu from being hidden.

Example: { command1: {name: "Foobar", callback: function(key, opt){ alert("Clicked on " + key + " on element " + opt.$trigger.id); } }}

If no callback and no default callback is specified, the item will not have an action

(string) className

Specifies additional classNames to add to the item element

(string) icon

Specifies the icon class to set for the item.

Icons must be defined in CSS with selectors like .context-menu-item.icon-edit, where edit is the icon class.

(function|boolean) disabled

Specifies if the command is disabled (true) or enabled (false).

May be a callback returning a boolean. The Callback is executed in the context of the triggering object (so this inside the function refers to the element the context menu was shown for). The first argument is the key of the command. The second argument is the options object.

Example: { command1: {name: "Foobar", callback: function(key, opt){ return true; } }}

(string) type

Specifies the type of the command.

null, undefined and the empty-string make the command a simple clickable item.

"text" makes the command an <input> of type text. The name followed by the <input> are encapsulated in a <label>.

"textarea" makes the command a <textarea>. The name followed by the <input> are encapsulated in a <label>.

"checkbox" makes the command an <input> of type checkbox. The name preceeded by the <input> are encapsulated in a <label>. The checkbox-element is moved to the icon space

"radio" makes the command an <input> of type radio. The name preceeded by the <input> are encapsulated in a <label>. The radio-element is moved to the icon space

"select" makes the command a <select>. The name followed by the <select> are encapsulated in a <label>.

"html" makes an non-command element.

(object) events

Events to register on <input> elements

Only used with types "text", "textarea", "radio", "checkbox" and "select".

Example: { command1: {name: "Foobar", type: "text", events: {keyup: function(e){alert(e.keyCode);}} }}

The contents of the options object are passed to jQuery event.data.

Example: { command1: {name: "Foobar", type: "text", events: {keyup: function(e){alert(e.data.$trigger.attr("id"));}} }}

(string) value

The value of the <input> element.

Only used with types "text", "textarea" and "radio".

(string|boolean) selected

The selected option of a <select> element and the checked property for "checkbox" and "radio" types.

Expecting a boolean when used with types "checkbox" and "radio".

Expecting a string when used with type "select"

(string) radio

Specifies the group of the radio elements.

Only used with type "radio".

(object) options

Specifies the <option>s for the <select> element.

Only used with type "select".

Example: {name: "select box", selected: "two", options: {one: "red", two: "blue", three: "green"}}

(int) height

The height in pixel <textarea> element. If not specified, the height is defined by CSS.

Only used with type "textarea".

(object) items

Commands to show in a sub-menu.

(string) accesskey

Character(s) to be used as accesskey.

Considering »a b c« $.contextMenu will first try to use »a« as the accesskey, if already taken, it'll fall through to »b«. Words are reduced to the first character, so »hello world« is treated as »h w«.

Note: Accesskeys are treated unique throughout one menu. This means an item in a sub-menu can't occupy the same accesskey as an item in the main menu.

(jQuery) $node

Reference to the <li> command element

created by contextMenu on registration

(jQuery) $input

Reference to the <input> or <select> of the command element.

Only available with type "text", "textarea", "checkbox", "radio" and "select".

created by contextMenu on registration

(jQuery) $label

Reference to the <label> of the command element

Only available with type "text", "textarea", "checkbox", "radio" and "select".

created by contextMenu on registration

(jQuery) $menu

Reference to the <ul> sub-menu element

created by contextMenu on registration

opt (options at runtime)

opt is a reference to the options object passed at contextMenu registration

(jQuery) $trigger

The element triggering the menu

(jQuery) $menu

The menu element

(object) callbacks

Registered callbacks of all commands (including those of sub-menus)

(object) commands

Registered commands (including those of sub-menus)

(object) inputs

Registered commands of input-type (including those of sub-menus)

Access a specific <input>: opt.inputs[key].$input

(boolean) hasTypes

flag denoting if the menu contains input elements

(string) ns

The namespace (including leading dot) all events for this contextMenu instance were registered under

Custom Command Types

Besides the built-in command types custom handlers can be defined. The command generator must be placed in $.contextMenu.types. It is identified by the key given in that object. The generator function is executed in the context of the new command's <li> within the menu. item is the object passed at creation. Use this to pass values from your definition to the generator. opt is the current menu level, root is the menu's root-level opt (relevant for sub-menus only).

A custom command type can be whatever you like it to be, it can behave how ever you want it to behave. Besides the keyboard interaction paradigm (up, down, tab, escape) key-events are passed on to the <li> which can be accessed via $(this).on('keydown', …);

Note that you'll probably want to disable default action handling (click, pressing enter) in favor of the custom command's behavior.

$.contextMenu.types.myType = function(item, opt, root) {
    $('<span>' + item.customName + '</span>').appendTo(this);
    this.on('contextmenu:focus', function(e) {
        // setup some awesome stuff
    }).on('contextmenu:blur', function(e) {
        // tear down whatever you did
    }).on('keydown', function(e) {
        // some funky key handling, maybe?
    });
};
$.contextMenu({
    selector: '.context-menu-custom', 
    items: {
        label: {type: "myType", customName: "Foo Bar"}
    }
});

Disable a contextMenu trigger

disable contextMenu to be shown on specified trigger elements

$(".some-selector").contextMenu(false);

Enable a contextMenu trigger

enable contextMenu to be shown on specified trigger elements

$(".some-selector").contextMenu(true);

Manually show a contextMenu

show the contextMenu of the first element of the selector (position determined by determinePosition):

$(".some-selector").contextMenu();
$(".some-selector").contextMenu({x: 123, y: 123});

Manually hide a contextMenu

hide the contextMenu of the first element of the selector:

$(".some-selector").contextMenu("hide");

Unregister contextMenu

To unregister / destroy a specific contextMenu:

$.contextMenu( 'destroy', selector );

selector expects the (string) selector that the contextMenu was registered to

Unregister all contextMenus

To unregister / destroy all contextMenus:

$.contextMenu( 'destroy' );

Helper: Import values for <input>

To fill input commands with values from a map:

{events: {
    hide: function(opt){ 
      $.contextMenu.getInputValues(opt, {command1: "foo", command2: "bar"}); 
    }
  }
}

To fill input commands with values from data-attributes:

{events: {
  hide: function(opt){ 
    $.contextMenu.getInputValues(opt, this.data());
    }
  }
}

Helper: Export values from <input>

To fetch values from input commands:

{events: {
  hide: function(opt){ 
    var values = $.contextMenu.setInputValues(opt}
  }
}

To save values from input commands to data-attributes:

{events: {
  hide: function(opt){ 
    $.contextMenu.setInputValues(opt, this.data()); }
  }
}

Events

contextmenu

Trigger context menu to be shown for a trigger object.

Available on trigger object. The Event must be supplied with coordinates for the menu: {pageX: 123, pageY:123}

$('.context-menu-one').first().trigger(
  $.Event('contextmenu', {pageX: 123, pageY: 123})
);
$('.context-menu-one').first().trigger("contextmenu");

will invoke determinePosition to position the menu

prevcommand

Select / highlight the previous possible command

Available on context menu.

opt.$menu.trigger("prevcommand");
nextcommand

Select / highlight the next possible command

Available on context menu.

opt.$menu.trigger("nextcommand");
contextmenu:hide

Hide the menu

Available on context menu.

opt.$menu.trigger("contextmenu:hide");
contextmenu:focus

React to a command item being focused

Triggered on context menu item when mouse or keyboard interaction lead to a "hover state" for that command item.

$(document.body).on("contextmenu:focus", ".context-menu-item", 
    function(e){ console.log("focus:", this); });
contextmenu:blur

Available on each context menu item.

Triggered on context menu item when mouse or keyboard interaction lead from a "hover state" to "default state" for that command item.

$(document.body).on("contextmenu:blur", ".context-menu-item",
    function(e){ console.log("blur:", this); });
keydown

Available on each context menu item.

Triggered on context menu item when keyboard interaction could not be handled by jQuery.contextMenu.

$(document.body).on("keydown", ".context-menu-item",
    function(e){ console.log("key:", e.keyCode); });

HTML5 <menu> import

considering the following HTML $.contextMenu.fromMenu($('#html5menu')) will return a proper items object

<menu id="html5menu" type="context" style="display:none">
  <command label="rotate" onclick="alert('rotate')">
  <command label="resize" onclick="alert('resize')">
  <menu label="share">
    <command label="twitter" onclick="alert('twitter')">
    <hr>
    <command label="facebook" onclick="alert('facebook')">
  </menu>
</menu>

$.contextMenu.fromMenu() will properly import (and thus handle) the following elements. Everything else is imported as {type: "html"}

The <menu> must be hidden but not removed, as all command events (clicks) are passed-thru to the original command element!

Note: While the specs note <option>s to be renderd as regular commands, $.contextMenu will render an actual <select>.

HTML5 <menu> shiv/polyfill

Engaging the HTML5 polyfill (ignoring $.contextMenu if context menus are available natively):

$(function(){ $.contextMenu("html5"); });

Engaging the HTML5 polyfill (ignoring browser native implementation):

$(function(){ $.contextMenu("html5", true); });

$.ui.position

The position utility of jQuery UI makes relative positioning very simple. But the real beauty is collision detection, allowing the contextMenu to be shown to the left side of the pointer, if there's not enough space to the right. Its use is optional, if you want to shape off some more bytes by sacrificing usability: go ahead…