Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect middle mouse button click?

Tags:

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.

like image 293
Nate Avatar asked Jan 20 '14 00:01

Nate


People also ask

How do I get my middle mouse button to click?

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.

What happens when you click the middle mouse button?

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.

How do you middle-click on a Logitech 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.


1 Answers

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')   } } 
like image 165
Schien Avatar answered Oct 03 '22 00:10

Schien