All of the questions I've seen on how to detect a middle mouse click in JavaScript are related to jQuery, but I'm wondering how I can detect middle mouse button clicks with regular JavaScript. I tried using onClick()
, but it only appears to work for the left mouse button.
Is there a JavaScript function that can detect both left and middle mouse button clicks or, if not, that can detect middle mouse button clicks?
The reason I ask is that I want to make a function call when links are clicked, irregardless of whether the left or middle mouse button was used.
Many mice and some touchpads have a middle mouse button. On a mouse with a scroll wheel, you can usually press directly down on the scroll wheel to middle-click. If you don't have a middle mouse button, you can press the left and right mouse buttons at the same time to middle-click.
The scroll wheel that is located in the middle of the mouse is used to scroll up and down on any page without using the vertical scroll bar on the right hand side of a document or webpage. The scroll wheel can also be used as a third button on the mouse.
The middle button on the top of the mouse next to the scroll wheel enables changing the DPI resolution. Clicking it cycles from 400 DPI to 800 to 1600 to the max of 3200, instantly changing with each click of the button.
onclick is not tied to a mouse, but more on the target element itself.
Here's how to detect whether an element is middle clicked:
document.body.onclick = function (e) { if (e && (e.which == 2 || e.button == 4 )) { console.log('middleclicked') } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With