which
is a property of Event
objects. It is defined for key-related and mouse-related events in most browsers, but in both cases is not defined in IE (prior to version 9).
For mouse-related events, which
specifies the mouse button that was involved. For IE < 9, the equivalent value is found in window.event.button
. Just to complicate things, non-IE browsers also support a button
property of mouse events that sometimes reports a different value from which
. Also, browsers sometimes have different values for the same button or combination of buttons. If you stick to using which
in all browsers that support it and button
in IE < 9, the one constant is that a value of 1 always means the left mouse button was involved (though not necessarily alone).
document.onmousedown = function(e) {
e = e || window.event;
var button = (typeof e.which != "undefined") ? e.which : e.button;
if (button == 1) {
alert("Left mouse button down");
}
};
For a full analysis, I recommend Jan Wolter’s article on JavaScript mouse events.
For key-related events, which
relates to the key that has been pressed. For keydown
and keyup
events, this is relatively simple: it’s the key code for the key pressed, and returns the same value as the event’s keyCode
property. Since all browsers support the keyCode
property and IE < 9 does not support which
, you should generally use keyCode
for keydown
and keyup
events.
For keypress
events, the situation is more complicated. For printable character keys, which
is the character code for the key pressed and is supported in more browsers than the charCode
property. In IE < 9 the equivalent is again the keyCode
property. So for detecting the character typed, the following is a cross-browser approach. Be aware that the code below should not be used for non-printable keys such as arrow keys, which you should instead detect in the keydown
event:
document.onkeypress = function(e) {
e = e || window.event;
var charCode = (typeof e.which == "number") ? e.which : e.keyCode;
if (charCode) {
alert("Character typed: " + String.fromCharCode(charCode));
}
};
Again, for more details I recommend Jan Wolter’s article on JavaScript key events