Reputation: 1554
Ok, capturing key codes from special symbols produces different results on keyboards with different layouts. But how about the 'common' characters, like a-z? If you have a QWERTY-keyboard, you'd get key code 81
when you type q
. When you have an AZERTY-keyboard, do you get code 81
when you press a
, since a
is where q
'should' be? Or is the mapping done differently?
EDIT:
The answer I accepted is probably the best solution when you're capturing keys and want to be sure 'a' is really 'a', but as I explain in the comment underneath that, I still am curious how the key codes are 'translated' when using int'l keyboards. That is: sources suggest at least a-z should be consistent, but I cannot find support for this (or someone who actually tried).
Upvotes: 2
Views: 3498
Reputation: 324727
If you use the keypress
event rather than keyup
or keydown
then the problem goes away because in that event you get character codes rather than key codes.
Example:
document.onkeypress = function(e) {
e = e || window.event;
var charCode = (typeof e.which == "undefined") ? e.keyCode : e.which;
alert( String.fromCharCode(charCode) );
};
And here's the definitive resource on key handling in JavaScript: http://unixpapa.com/js/key.html
Upvotes: 1