Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect left mouse button press

I hate this mess with the mouse buttons created by W3C an MS! I want to know if the left mouse button is pressed when I get a mousedown event.

I use this code

// Return true if evt carries left mouse button press function detectLeftButton(evt) {   // W3C   if (window.event == null) {     return (evt.button == 0)   }   // IE   else {     return (evt.button == 1);   } } 

However, it does not work in Opera and Chrome, because it so happens that window.event exists there too.

So what do I do? I have some browser detection, but we all know it cannot be relied upon with all the masking some browsers do lately. How do I detect the left mouse button RELIABLY?

like image 638
Boris Hamanov Avatar asked Oct 15 '10 16:10

Boris Hamanov


People also ask

How do I know which mouse button is clicked?

Use MouseEvent. button to detect which button has been clicked on a mouse.

How does HTML detect mouse click?

The button property returns a number that indicates which mouse button was pressed when a mouse event was triggered. This property is mostly used together with the onmousedown event. Note: This property is read-only.

When you press the left mouse button?

The left button on a mouse is the default button used to click, select, drag to highlight a word and/or object and used as a pointer.

What is the difference between Mousedown and click?

Note: This differs from the click event in that click is fired after a full click action occurs; that is, the mouse button is pressed and released while the pointer remains inside the same element. mousedown is fired the moment the button is initially pressed.


2 Answers

Updated answer. The following will detect if the left and only the left mouse button is pressed:

function detectLeftButton(evt) {     evt = evt || window.event;     if ("buttons" in evt) {         return evt.buttons == 1;     }     var button = evt.which || evt.button;     return button == 1; } 

For much more information about handling mouse events in JavaScript, try http://unixpapa.com/js/mouse.html

like image 133
Tim Down Avatar answered Sep 26 '22 14:09

Tim Down


There is now a W3C standard event.buttons property supported by IE9 in standards mode, and Gecko 15+.

The W3C completely stuffed up the event.button property, so for a standards compliant browser event.button is 0, but for browsers created before the standard, event.button is 1.

So code must avoid using event.button except for older browsers. The following code should work:

function detectLeftButton(event) {     if (event.metaKey || event.ctrlKey || event.altKey || event.shiftKey) {         return false;     } else if ('buttons' in event) {         return event.buttons === 1;     } else if ('which' in event) {         return event.which === 1;     } else {         return (event.button == 1 || event.type == 'click');     } } 
like image 31
robocat Avatar answered Sep 23 '22 14:09

robocat