W3cubDocs

/jQuery

.contextmenu()

.contextmenu( handler )Returns: jQuery

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

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

Additional Notes:

  • As the .contextmenu() method is just a shorthand for .on( "contextmenu", handler ), detaching is possible using .off( "contextmenu" ).

Examples:

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

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

Right click to toggle background color.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>contextmenu demo</title>
  <style>
  div {
    background: blue;
    color: white;
    height: 100px;
    width: 150px;
 }
  div.contextmenu {
    background: yellow;
    color: black;
  }
  </style>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
 
<div></div>
<span>Right click the block</span>
 
<script>
var div = $( "div:first" );
div.contextmenu(function() {
  div.toggleClass( "contextmenu" );
});
</script>
 
</body>
</html>

Demo:

© The jQuery Foundation and other contributors
Licensed under the MIT License.
https://api.jquery.com/contextmenu