JavaScript contextmenu
The contextmenu
event is triggered when the user clicks on the right button of the mouse and opens the context menu. This event is useful when you want to provide additional functionality to the user, such as customizing the context menu for your application.
Syntax
element.addEventListener('contextmenu', function(e) {
// code to execute
});
Example
<body>
<div id="myDiv">Right click me</div>
<script>
const myDiv = document.getElementById('myDiv');
myDiv.addEventListener('contextmenu', function(e) {
e.preventDefault();
console.log('Context menu opened');
});
</script>
</body>
Output
When you right-click on the myDiv
element, the message "Context menu opened" will be logged to the console.
Explanation
In the above example, we use the addEventListener()
method to listen to the contextmenu
event on the myDiv
element. We then prevent the default browser behavior by calling e.preventDefault()
. This is necessary because without it, the browser would open the default context menu instead of our custom context menu.
Use
The contextmenu
event can be used to add custom functionality to the context menu of your application. For example, you can use it to display a custom context menu with options that are specific to your application.
Important Points
- The
contextmenu
event is triggered when the user clicks on the right button of the mouse. - You can use the
e.preventDefault()
method to prevent the browser from opening the default context menu. - The
contextmenu
event can be used to add custom functionality to the context menu of your application.
Summary
The contextmenu
event is a useful event in JavaScript that allows you to add custom functionality to the right-click context menu of your application. You can use it to display a custom context menu with options that are specific to your application. When using the contextmenu
event, be sure to prevent the default browser behavior by calling e.preventDefault()
.