Identifying Mouse Buttons
When Javascript recieves a mouse click event, it is generally interesting to know which mouse button was clicked. The event object that is passed to Javascript contains two fields that may be used to check this, event.which and event.button. These will contain numerical values to identify the mouse button.
Sadly, there is little cross browser compatibility as far as which number represents which button. Here's the chart:
Mouse button ID values in various browser
I.E Net4 Gecko1.0orlater
WindowsSafari
Opera9 ecko 0.9 Opera 7 Konqueror MacSafari iCab
LEFT
BUTTON
event.which undefined 1 1 1 1 1 1 1
event.button 1 undefined 0 1 1 1 1 0
MIDDLE
BUTTON
event.which undefined 2 2 2 3 2
event.button 4 undefined 1 2 3 4
RIGHT
BUTTON
event.which undefined 3 3 2 3 3
event.button 2 undefined 2 3 2 2
The event.which value was originally used in Netscape, and the event.button value was originally used in Internet Explorer. Later browers used both, and messed them both up. Old versions of Opera mixed up the left and right button values for event.which. The newer Mozilla browsers entirely rearranged the event.button values. Old version of Opera messed them up a different way, then newer versions duplicated the value sent by Mozilla. Konqueror simply combines the classic Netscape and IE values.
Newer versions of most browsers except IE seem to be converging toward column three of this table. It's encouraging to see increasing standardization.
Some mice now have more buttons than three buttons. I've done a few tests of this on a Linux system with a five button mouse. In Gecko and Opera, the extra buttons have the same values as the left mouse button, event.which=1, and event.button=0. In Konqueror both extra buttons give event.which=65536, and event.button=0, which are at least different from any of the other three buttons, but may well be intended as error codes.
The end result? There is no browser-independent way to recognize which mouse button is which for all browsers. To handle all cases, you have to sense the browser type and use different algorithms for different browsers.
However, the following test comes pretty close. It mixes up the right and middle mouse buttons in Opera 7, but there were only a few versions of Opera 7 where the left and middle buttons even worked, and then only if the user set an obscure option, so maybe we don't care anymore.
if (event.which == null)
/* IE case */
button= (event.button < 2) ? "LEFT" :
((event.button == 4) ? "MIDDLE" : "RIGHT");
else
/* All others */
button= (event.which < 2) ? "LEFT" :
((event.which == 2) ? "MIDDLE" : "RIGHT");
Click here with various mouse buttons to test