views:

35

answers:

2

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?

A: 

oncontextmenu

epascarello
How does this relate to detecting a left button on mousedown?
jball
It does not relate at all. Please, I cannot lower the answer rating, if somebody can, please, do.
avok00
+3  A: 

Here you go:

function detectLeftButton(evt) {
    evt = evt || window.event;
    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

Tim Down
This does not work. Left button is 0 in all browsers except IE
avok00
This does work. `which` returns 1 for the left button in all browsers except IE, where it will be undefined. In IE only, my `button` variable will therefore use the value for the event's `button` property instead of `which`, which is 1 for the left button.
Tim Down
@avok00, did you try it?
jball
Sorry, I did not pay attention to the which part. I tried it. It does work! Thanks Tim!
avok00
While this does work - and I'd go as far as saying it is a very good solution - it still uses the non-standardised event.which property. So, ironically, you use a non-standardised property to distinguish the standards-compliant browsers from that other one. ;)
hallvors
@hallvors: Indeed. Unfortunately, identifying mouse buttons (along with identifying keypresses) is one area where standards and the reality of browser implementations are quite far apart.
Tim Down