Handling key events sequentially is not always easy.
Firstly, there are two different types of codes: keyboard codes (a number denoting the key on the keyboard that the user pressed) and character codes (a number denoting a Unicode character). You can only reliably get character codes in a keypress event. Do not try to get character codes for keyup and keydown .
Secondly, you get different sets of values ββin the keypress event for what you get in the keyup or keydown .
I recommend this page as a useful resource. In summary:
If you are interested in finding the user who typed a character, use the keypress event. Strange IE only stores the character code in keyCode , and all other browsers store it in which . Some (but not all) browsers also store it in charCode and / or keyCode . An example of a keystroke handler:
function(evt) { evt = evt || window.event; var charCode = evt.which || evt.keyCode; var charStr = String.fromCharCode(charCode); alert(charStr); }
If you are interested in finding a non-printable key (for example, cursor keys), use the keydown event. Here keyCode always a property of use. Note that keyup events have the same properties.
function(evt) { evt = evt || window.event; var keyCode = evt.keyCode;
Tim Down Sep 18 '09 at 15:21 2009-09-18 15:21
source share