How to detect the middle mouse button?

All the questions I saw about how to detect middle mouse clicks in JavaScript are related to jQuery, but I am wondering how I can detect middle mouse clicks using normal JavaScript. I tried using onClick() , but it only works for the left mouse button.

Is there a JavaScript function that can detect left and middle mouse clicks or, if not, can detect middle mouse clicks?

The reason I'm asking is because I want to make a function call when clicking links, regardless of whether the left or middle mouse button was used.

+7
javascript
source share
4 answers

onclick is not attached to the mouse, but refers more to the target element itself.

Here's how to determine if an element will be clicked in the middle:

 document.body.onclick = function (e) { if (e && (e.which == 2 || e.button == 4 )) { console.log('middleclicked') } } 
+8
source share

You will need to detect event 2

 event = event || window.event; //make sure to pass the event into the function if (event.which == 2) { //do code.. } 
+2
source share

The code below may help you. It can detect which mouse button the user clicked. e.which == 2 for the middle button.

 <script type="text/javascript"> function detect_button(e){ e = e || window.event; if (e.which == null){ button = (e.button < 2) ? 'left' : ((e.button == 4) ? 'middle' : 'right'); } else{ button = (e.which < 2) ? 'left' : ((e.which == 2) ? 'middle' : 'right'); } alert(button); } </script> 
+1
source share

You should use material that is already built into the DOM and Javascript, and then put it in cases where browsers are different (which is why jQuery is commonly used).

 document.getElementById("myBtn").onclick = function(event) { event = event || window.event // Now event is the event object in all browsers. // Note: event.target - the reference to clicked element. IE uses event.srcElement // In W3C there is a button property which works same in all browsers except IE: // 0 - left button, 1 - middle button, 2 - right button // For IE, left button = button & 1 (the 1st bit) is set to 1 // right button = button & 2 (the 2nd bit) is 1 // and middle button = button & 4 (the 3rd bit) var left = event.button == 0 || 1 == event.button&1; var middle = event.button == 1 || 1 == event.button&2; var right = event.button == 2 || 1 == event.button&3; // Put your code here } 
0
source share

All Articles