Reputation: 9466
Say that I am not using jQuery, and want to support IE8 along with the other mainstream browsers.
In order to normalize events, I am following this pattern:
document.onkeydown = function(e) {
var code;
if (!e) {
var e = window.event;
}
code = e.which || e.keyCode;
// More stuff here...
};
However, I suspect that if I changed the order of my e.which
vs e.keyCode
check, like so...
code = e.keyCode || e.which;
...then my code might act differently across browsers.
e.charCode
matter?var e = window.event
or just e = window.event
?Upvotes: 0
Views: 410
Reputation: 25081
1. Yes, the order matters.
The order you should use is indeed:
code = e.which || e.keyCode;
This is because most browsers support e.which
(IE<9 excluded, of course). This way, any browser (IE>=9 and FF, Chrome, Opera, Safari, etc.) that supports e.which
will use it, and those that don't will use e.keyCode
.
Should you switch the order to:
code = e.keyCode || e.which;
You'll get e.keyCode
for virtually every browser (instead of e.which
) which will tell you the key that was pressed but not the resulting character (which I suspect is not what you want).
2. No, e.charCode does not matter.
Browser support for e.charCode is spotty at best. Even IE9 documentation states that it's for compatibiity only. Most popular modern browsers return undefined
or 0
(or ASCII, or Extended ASCII, if you're lucky and even then it's only on keypress
).
Additional reading for both 1 and 2 should probably be done at:
Should you wish to play around with key events, I made a fiddle for you to report the [relevant] properties of the event parameter when you type in the sole input field.
3. You should definitely use var e = window.event;
.
If you don't use var
, you're effectively declaring window.e = window.event
which is silly. Use var
to keep e
defined in the scope of your handler.
Upvotes: 1