Categories
JavaScript Answers

How to detect middle mouse button click with JavaScript?

Spread the love

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.

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 *