contextmenu event


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

.on( handler )Returns: jQuery

Description: Bind an event handler to the "contextmenu" event.

This page describes the contextmenu event. For the deprecated .contextmenu() method, see .contextmenu().

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:

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

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

1
2
3
$( "#target" ).on( "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, use .trigger( "contextmenu" ):

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

Examples:

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

1
2
3
$( "p" ).on( "contextmenu", function() {
alert( "Hello World!" );
} );

Right click to toggle background color.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>on 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-3.7.0.js"></script>
</head>
<body>
<div></div>
<span>Right click the block</span>
<script>
var div = $( "div" ).first();
div.on( "contextmenu", function() {
div.toggleClass( "contextmenu" );
} );
</script>
</body>
</html>

Demo: