Keyboard Event Handling: onkeypress

JavaScript FAQ | Keyboard & Mouse Events FAQ  

Question: Which character did the user type?

Answer: To identify the printable character the user has typed, use the keypress event properties that hold the character code:

  • keypress event.charCode (supported in most browsers except MSIE, Opera)
  • keypress event.which (supported in most browsers other than MSIE)
  • keypress event.keyCode (character code in Internet Explorer)

    Unlike event.keyCode of keydown/keyup events, the character codes in keypress events reflect the actual characters the user typed (and not necessarily the keys pressed). The characters may be capital or small, Latin or locale-specific. For example, depending on the current state of the client, the F key on the keyboard may produce a capital Latin letter F, a small Latin letter f, a capital Cyrillic letter A, a small Cyrillic letter a, or any other character that might be mapped to this particular key – quite a few different characters with their own character codes. Therefore, we must use the keypress event here; should we use keydown, we would get the same key code 70 (F) for all of the above.

    Click here and press any key - the actual character you typed will be displayed below:
    Latest keydown event:  
    The keypress event (if any):

    This example uses the String.fromCharCode() method that maps the character code back to the corresponding character. For comparison, the script displays not only the character typed but also the key pressed. Here is the source code of this example (the onkeydown event handler source is omitted):

    function keypressHandler(e) {
      var evt = e ? e:event;
      var chrTyped, chrCode = 0;
      var sProperties = ''
       +(evt.keyCode ==null ? '':' keyCode=' +evt.keyCode )
       +(evt.charCode==null ? '':' charCode='+evt.charCode)
       +(evt.which   ==null ? '':' which='+evt.which)
      if (evt.charCode!=null)     chrCode = evt.charCode;
      else if (evt.which!=null)   chrCode = evt.which;
      else if (evt.keyCode!=null) chrCode = evt.keyCode;
      if (chrCode==0) chrTyped = 'SPECIAL KEY';
      else chrTyped = String.fromCharCode(chrCode);
      document.getElementById('sChrCode').innerHTML =
      document.getElementById('sChrName').innerHTML =
        ' Character: '+chrTyped.bold();
      return true;
    //Register the event handlers:

    See also:

  • Keyboard event properties
  • Which key did the user press?
  • Copyright © 1999-2012,