A jQuery plugin that provides a context menu (based on the standard jQueryUI menu widget).
- themable
- supports delegation (i.e. can be bound to elements that don't exist at the time the context menu is initialized)
- exposes events from jQueryUI menu:
blur
,create
,focus
,select
Beta: not ready for production.
Say we have some HTML elements that we want to attach a popup menu to:
<div id="container">
<div class="hasmenu">AAA</div>
<div class="hasmenu">BBB</div>
<div class="hasmenu">CCC</div>
</div>
now we can enable a contextmenu like so:
$("#container").contextmenu({
delegate: ".hasmenu",
menu: "#options",
select: function(event, ui) {
var menuId = ui.item.find(">a").attr("href"),
target = event.relatedTarget;
alert("select " + menuId + " on " + $(target).text());
}
});
To apply the selector globally, pass document
as context:
$(document).contextmenu({
delegate: ".hasmenu",
[...]
});
Of course we also have to provide some HTML markup that defines the context menu structure (see jQueryUI menu for details):
<ul id="options" class="ui-helper-hidden">
<li><a href="#action1">Action 1</a>
<li><a href="#action2">Action 2</a>
<li class="ui-state-disabled"><a href="#action3">Action 3</a>
<li>----
<li><a>Extra</a>
<ul>
<li><a href="#action4">sub4</a>
<li><a href="#action5">sub5</a>
</ul>
</ul>
- delegate
- `{String}` jQuery selector describing the elements that trigger the context menu.
- menu
- `{String | jQuery | function}` jQuery object or selector (or function returning such) describing the menu definition.
- open(target)
- Open context menu on a specific target (must match options.delegate).
jquery-contextmenu exposes events from jQueryUI menu: blur
, create
, focus
, select
.
However, since the event.target
parameter contains the menu item, we additionally pass the element
that was right-clicked in event.relatedTarget
.
Events may be handled by defining a handler option:
$("#container").contextmenu({
[...]
select: function(event, ui) {
var menuId = ui.item.find(">a").attr("href"),
target = event.relatedTarget;
alert("select " + menuId + " on " + $(target).text());
}
});
Alternatively a handler may be bound, so this is equivaent:
$("#container").bind("contextmenuselect", function(event, ui) {
var menuId = ui.item.find(">a").attr("href"),
target = event.relatedTarget;
alert("select " + menuId + " on " + $(target).text());
}
- beforeopen(event)
- Menu about to open; return `false` to prevent opening.
- blur(event, ui)
- menu option lost focus
- close(event, ui)
- menu was closed
- create(event, ui)
- menu was initialized
- focus(event, ui)
- menu option got focus
- init(event, ui)
- ui-contextmenu was initialized
- open(event, ui)
- menu was opened
- select(event, ui)
- menu option was selected; return `false` to prevent closing.