How to detect middle mouse button click with JavaScript?

Sometimes, we want to detect middle mouse button click with JavaScript.

In this article, we’ll look at how to detect middle mouse button click with JavaScript.

How to detect middle mouse button click with JavaScript?

To detect middle mouse button click with JavaScript, we can check which button is clicked with e.button in the mousedown event handler.

For instance, we write:

window.onmousedown = (e) => {
  if (e.button === 1) {
    console.log('middle clicked')
  }
}

to set window.onmousedown to a function that checks if the middle mouse button is clicked by checking if e.button is 1.

If it is clicked, then 'middle clicked' is logged.

Conclusion

To detect middle mouse button click with JavaScript, we can check which button is clicked with e.button in the mousedown event handler.