views:

28

answers:

2

What is the best way to go about detecting what button has been pressed in a DIV in FireFox using javascript?

+2  A: 

There are two properties for finding out which mouse button has been clicked: which and button. Please note that these properties don’t always work on a click event. To safely detect a mouse button you have to use the mousedown or mouseup events.

which is an old Netscape property. Left button gives a value of 1, middle button (mouse wheel) gives 2, right button gives 3. No problems, except its meager support (and the fact that it’s also used for key detection).

Now button has been fouled up beyond all recognition. According to W3C its values should be:

* Left button – 0
* Middle button – 1
* Right button – 2

According to Microsoft its values should be:

* Left button – 1
* Middle button – 4
* Right button – 2

No doubt the Microsoft model is better than W3C’s. 0 should mean “no button pressed”, anything else is illogical.

Besides, only in the Microsoft model button values can be combined, so that 5 would mean “left and middle button”. Not even Explorer 6 actually supports this yet, but in the W3C model such a combination is theoretically impossible: you can never know whether the left button was also clicked.

In my opinion W3C has made some serious mistakes in defining button. Right click

Fortunately you most often want to know if the right button has been clicked. Since W3C and Microsoft happen to agree on this one and give button a value of 2, you can still detect a right click.

function doSomething(e) {
    var rightclick;
    if (!e) var e = window.event;
    if (e.which) rightclick = (e.which == 3);
    else if (e.button) rightclick = (e.button == 2);
    alert('Rightclick: ' + rightclick); // true or false
}

Please note that, although Macs have only one mouse button, Mozilla gives a Ctrl–Click a button value of 2, since Ctrl–Click also brings up the context menu. iCab doesn’t yet support mouse button properties at all and you cannot yet detect a right–click in Opera.

Multiplexer
Formatted your code.
Tim Down
+1. Decent write-up. A longer discusssion can be found here: http://unixpapa.com/js/mouse.html
Tim Down
A: 

[jquery][1] mentions how you can detect the mouse button here: http://api.jquery.com/mousedown/

The mousedown event is sent when any mouse button is clicked. To act only on specific buttons, we can use the event object's which property. Not all browsers support this property (Internet Explorer uses button instead), but jQuery normalizes the property so that it is safe to use in any browser. The value of which will be 1 for the left button, 2 for the middle button, or 3 for the right button.

TJB