.contextmenu()

Bind an event handler to the "contextmenu" JavaScript event, or trigger that event on an element.

.contextmenu(function(eventObjectEvent))🡢 jQuery

function(eventObjectEvent) FunctionA function to execute each time the event is triggered.

.contextmenu(eventData, function(eventObjectEvent))🡢 jQuery

eventData AnythingAn object containing data that will be passed to the event handler.
function(eventObjectEvent) FunctionA function to execute each time the event is triggered.

.contextmenu()🡢 jQuery

This method is a shortcut for .on( "contextmenu", handler ) in the first two variations, and .trigger( "contextmenu" ) in the third. The contextmenu event is sent to an element when the right button of the mouse is clicked on it, but before the context menu is displayed. In case the context menu key is pressed, the event is triggered on the html element or the currently focused element. Any HTML element can receive this event. For example, consider the HTML:

<div id="target">Right-click here</div>

The event handler can be bound to the <div> as follows:

$("#target").contextmenu(function () {
  alert("Handler for .contextmenu() called.");
});

Now right-clicking on this element displays the alert:

Handler for .contextmenu() called.

To trigger the event manually, call .contextmenu() without an argument:

$("#target").contextmenu();

To show a "Hello World!" alert box when the contextmenu event is triggered on a paragraph on the page:

HTML
$("p").contextmenu(function () {
  alert("Hello World!");
});
DEMO

Right click to toggle background color.

JS
<div></div>
<span>Right click the block</span>
CSS
div {
  background: blue;
  color: white;
  height: 100px;
  width: 150px;
}
div.contextmenu {
  background: yellow;
  color: black;
}
HTML
var div = $("div").first();
div.contextmenu(function () {
  div.toggleClass("contextmenu");
});
DEMO

Looking for a Web Developer?

👋

Hi! I'm Basti, author of this site. If you are looking for a web developer with 15+ years of experience, holla at me!

Be it the good 'ol jQuery, vanilla JS or modern frameworks like Vue and Svelte, front- or backend, I can help you.

Just write me at jobs@jqapi.com :)