Detect mouse right-click with JavaScript

In this tutorial, we will see how we can detect mouse right-clicks with Javascript. Click events have a button property associated with it, that allows us to get the exact mouse button. Mousedown and mouseup handlers may need an event to differentiate the clicks because these events trigger on any button.

APIs in Javascript allow developers to detect the clicks by mouse. It comes in handy on various occasions while doing some projects. A typical mouse has 3 buttons namely:

  1. Primary Button: On the left side of the mouse
  2. Secondary Button: Usually termed as right, or right-click (because it’s present on the right side)
  3. Scroll Wheel: present at the middle of the mouse , allowing us to scroll up and down.

Mouse Click Events

The properties available on mouse clicking events are following:

Event Names:

  • mousedown
  • mouseup
  • click
  • dblclick
  • contextmenu

Example Code for Generic Click:

window.addEventListener('click', (event) => {
  console.log(event.button)
})

The MouseEvent.button returns a number (It’s read-only property). Every number refers to a button on the mouse:

Values returned by MouseEvent.button:

0 - Main button
1 - Wheel button (middle button if present)
2 - Secondary button
3 - Fourth button (Back button)
4 - Fifth button (Forward button)

Detect Right Button Click in JavaScript

JavaScript provides a special event for detecting the right click in browsers – contextmenu to capture the mouse right-click.

Code:

window.addEventListener('contextmenu', (event) => {
  console.log(event.button)
})

This event still has the button property, with the number value of the clicked button. To prevent any further action, we can use this default JS function called event.preventDefault().

Code with Prevent Default:

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

Conclusion

MouseEvent.button detects which button was clicked on our mouse. In back action and forward actions of gaming mouses for an iframe, these detections come in very handy, but the contextmenu is used to detect and react on mouse right-click events specifically.

Hope you have grasped this concept well and are ready to use it in your applications. If you have any doubts, comment below.

Leave a Comment