2

Possible Duplicate:
Javascript KeyCode vs CharCode = Utter Confusion

What is the difference between the return value of String.charCodeAt(index) and JavaScript key codes? And is there a way to translate between the two?

For example:

console.log('.'.charCodeAt(0));  // prints 46 on Mac/Chrome

But the keyCode for '.' is 190.

Community
  • 1
  • 1
Andrew Eisenberg
  • 28,387
  • 9
  • 92
  • 148

2 Answers2

2

string.charCodeAt(index) is designed to return you the ascii value for the character of a string at a specified position.

keyCode is the browser implementation of what the value for the keyboard key that was pressed. unfortunately, it's not standardized across all browsers either.

Edit:

String.fromCharCode(unicodeValue);

This will convert a unicode value such as keyCode into an ascii value. Just be mindful that not all keyCode values are going to convert to an appropriate ascii value (since there isn't one) such key presses like { delete, up, down, left, right, home, insert, page up, page down }

Example: pressing the Delete key returns a keyCode of 46, if you do alert(String.fromCharCode(46)); you will see it output a period since the 46 is the ascii value for a period.

Matthew Cox
  • 13,566
  • 9
  • 54
  • 72
  • Is there a function that can translate from keyCode to charCode and vice-versa? – Andrew Eisenberg Jan 24 '13 at 19:12
  • jQuery has implemented a version of keyCode called `event.which` that it adds to the event object of a callback method. It normalizes these keyCodes so that they are consistent across all browsers and versions that jQuery supports. That is the hard part done ... then you just need to write a mapping function that maps to the proper ascii values. – Matthew Cox Jan 24 '13 at 19:15
  • api documentation on `event.which` http://api.jquery.com/event.which/ – Matthew Cox Jan 24 '13 at 19:16
  • @AndrewEisenberg Did a little digging for you. Read the edit to my answer. – Matthew Cox Jan 24 '13 at 19:27
  • keyCodes are no unicode values, and `fromCharCode` does not convert to ascii (which would be more limited) but to strings. – Bergi Jan 24 '13 at 19:29
1

Unlike onkeydown and onkeyup the onkeypress event does infact return a charCode property that can be translated to its character representation using String.fromCharCode

input.onkeypress = function(e) {
     var char = String.fromCharCode(e.charCode);
}

Also check out this link for some good research regarding keyCodes / charCodes on different browsers & platforms

http://unixpapa.com/js/key.html

lostsource
  • 21,070
  • 8
  • 66
  • 88