Sometimes, we want to do something when a user right-clicks on an element in our web app.
In this article, we’ll look at how to handle right-clicks with JavaScript.
Set the window.oncontextmenu Property to a Function
We can set the window.contextmenu
property to an event handler function to listen for right clicks on the page.
To do this, we write:
window.oncontextmenu = (e) => {
e.preventDefault()
console.log('right clicked')
}
We have the e
parameter that has the right-click event object.
We call e.preventDefault
to stop the default behavior for right clicks, which is to show the context menu on the page.
Once we called that, we can do anything we want in the rest of the function when the user right-clicks on the page.
Call the window.addEventListener Method to Add an Event Listener Function
Another way to do something when we right-click on the page is to call the window.addEventListener
method to add an event listener function for listening to right clicks.
For instance, we can write:
window.addEventListener('contextmenu', (ev) => {
ev.preventDefault();
console.log('right clicked')
});
We pass in the 'contextmenu'
string to listen for context menu click events.
Then in the event listener, we call preventDefault
the same way to stop the default right-click menu from displaying.
And then we can do what we want when the user right-clicks on the page.
Conclusion
We can listen for the contextmenu
event and call preventDefault
in the event handler function to run our own JavaScript when we right-click on the page.