Categories
JavaScript Answers

How to capture the right-click event in JavaScript?

Spread the love

Sometimes, we want to capture the right-click event in JavaScript.

In this article, we’ll look at how to capture the right-click event in JavaScript.

How to capture the right-click event in JavaScript?

To capture the right-click event in JavaScript, we can listen for the contextmenu event.

For instance, we write

el.addEventListener(
  "contextmenu",
  (ev) => {
    ev.preventDefault();
    //...
  },
  false
);

to call el.addEventListener with 'contextmenu' and an event handler to listen for right clicks with the event handler.

We call ev.preventDefault in the event handler to stop the default behavior for right clicks, which is to show the context menu.

Then we can do what we want with right clicks in the event handler since the rest of the event handler will run after preventDefault is called.

Conclusion

To capture the right-click event in JavaScript, we can listen for the contextmenu event.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *