Friday, May 10, 2024
41
rated 0 times [  44] [ 3]  / answers: 1 / hits: 78692  / 14 Years ago, fri, october 15, 2010, 12:00:00

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?


More From » google-chrome

 Answers
17

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


[#95303] Thursday, October 14, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kareem

Total Points: 733
Total Questions: 110
Total Answers: 102

Location: Bermuda
Member since Thu, Apr 20, 2023
1 Year ago
;