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.

3
  • 2
    The first is position in ASCII table, the second is a keyboard key code value. Commented Jan 24, 2013 at 19:01
  • I wouldn't say this is a duplicate since the linked question doesn't ask about how to translate between the two. Commented Jan 24, 2013 at 19:09
  • More specifically, if I have a single char, how do I get its keycode in any given browser? Commented Jan 24, 2013 at 19:09

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Is there a function that can translate from keyCode to charCode and vice-versa?
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.
api documentation on event.which api.jquery.com/event.which
@AndrewEisenberg Did a little digging for you. Read the edit to my answer.
keyCodes are no unicode values, and fromCharCode does not convert to ascii (which would be more limited) but to strings.
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.