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.