Fork me on GitHub

jQuery contextMenu (fork)

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"

(boolean) ignoreRightClick

default: false

Specifies if the regular right click context menu trigger should be ignored. Only applies to "left" and "hover" triggers

(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.id); }}

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).

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. 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);}} }}

(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.

(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

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();

Register HTML5 context <menu>s

$.contextMenu("html5");

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");

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!

$.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…