JavaScript

How to Capture the Right-Click Event in JavaScript

When a user right-clicks on a web page, a context menu or right-clicks menu appears. Developers often need to take some action when a user performs a right-click on a web application element. Therefore, they must track/capture the right-click on the website.

This tutorial will illustrate the procedure for capturing the right-click event in JavaScript.

How to Capture the Right-Click Event in JavaScript?

Use the “window.addEventListener()” method by passing the event “contextmenu”. Whenever the user attempts to initiate a context menu by clicking the right mouse button, the contextmenu event is triggered.

Example 1: Capture the Right-Click Event Using the addEventListener() Method With the alert() Method

For capturing a right-click on a web page, use the “window.addEventListener()” method to attach/add an event handler to an element. Then, show the result that the user right-clicks on the page using the “alert()” method. It will display the message in a dialog box that will pop up on the screen with the “OK” button:

window.addEventListener('contextmenu', (event) => {

alert('mouse right-clicked');

});

The output displays an alert message when we right-click on the page and then opens the default context menu:

Example 2: Capture the Right-Click Event Using addEventListener() Method With console.log() Method

Here, we will capture the right-click event and output a message to the console:

window.addEventListener('contextmenu', (event) => {

console.log('mouse right-clicked');

});

Output

Example 3: Restrict the Right-Click to Display Default Menu

In this example, we will see restrict the default context menu to open on the right click using the “preventDefault()” method:

window.addEventListener('contextmenu', (event) => {

event.preventDefault();

alert('mouse right-click is prevented');

});

As you can see in the output, the default context menu does not appear on the mouse right-click:

Example 4: Open Custom Context Menu on Mouse Right-Click

Here, the output shows a custom context menu on the mouse right-click event. More specifically, follow the link to create a custom context menu:

That’s all about capturing the right-click event in JavaScript.

Conclusion

To Capture the right-click event in JavaScript, use the“window.addEventListener()” method by passing the event “contextmenu”. The contextmenu event is triggered when a user attempts to initiate a context menu by clicking the right mouse button. In this tutorial, we illustrated the procedure for capturing the right-click event in JavaScript.

About the author

Farah Batool

I completed my master's degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.