For keys that have printable character equivalents, you should use the keypress
event because you can retrieve character codes from the keypress
event, which is generally not possible for keyup
and keydown
events.
The event properties you need are which
and keyCode
- pretty much all browsers have one or both of these, though IE muddies the waters by using keyCode
for the character code while some other browsers return a (different) key code. Most non-IE browsers also have charCode
but it seems all such browsers also have which
, so charCode
is never needed. A simple example:
document.onkeypress = function(evt) {
evt = evt || window.event;
var charCode = evt.which || evt.keyCode;
var charStr = String.fromCharCode(charCode);
alert(charStr);
};
Here is a useful reference page.