JavaScript KeyCode vs CharCode

The answers to all your questions can be found on the following page.

…but in summary:

  • The only event from which you can reliably obtain character information (as opposed to key code information) is the keypress event.
  • In the keypress event, all browsers except IE <= 8 store the character code in the event’s which property. Most but not all of these browsers also store the character code in the charCode property.
  • In the keypress event, IE <= 8 stores the character code in the keyCode property.

This means to get the character code corresponding to the keypress, the following will work everywhere, assuming a keypress event object is stored in a variable called e:

var charCode = (typeof e.which == "number") ? e.which : e.keyCode

This will generally return you a character code where one exists and 0 otherwise. There are a few cases where you’ll get a non-zero value when you shouldn’t:

  • In Opera < 10.50 for keys Insert, Delete, Home and End
  • In recent versions of Konqueror for non-character keys.

The workaround for the first problem is a little involved and requires using the keydown event as well.

Leave a Comment