1

I need to get the char code value for the opening curly bracket.

I used "{".charCodeAt(0) but it returns 123,

However when If I get the value from keyboard events, that value is 219. Which one is correct?
Please advise me how to get the correct value for the curly bracket

Yurii
  • 4,811
  • 7
  • 32
  • 41
raky
  • 181
  • 1
  • 2
  • 11
  • "[charCodeAt()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charCodeAt) method returns the numeric Unicode value of the character ..." The value you can retrieve in a keyboard event depends on the event. From `keydown/up` you'd get a keyboard key mapping code, from `keypress` you'd get a numeric Unicode value of the character produced by pressed key. Please elaborate your question, i.e. define "char code". – Teemu Sep 10 '14 at 05:57
  • possible duplicate of [Is there a full list of JavaScript keyCodes available?](http://stackoverflow.com/questions/5603195/is-there-a-full-list-of-javascript-keycodes-available) – jasonscript Sep 10 '14 at 06:06
  • @raky, `123` is correct, test it by `String.fromCharCode(123)` gives `{` –  Sep 10 '14 at 06:06

1 Answers1

1

Yes the unicode value of { is 123 (0x7B) according to wikipedia.

However the keyCode attribute in Keyboard.event is not a unicode value, see KeyboardEvent documentation on MDN. People fall into the trap of using it as a character value because without the shift modifier a lot of the values are actually the same.

KeyboardEvent.keyCode

A system and implementation dependent numerical code identifying the unmodified value of the pressed key. Read only. See the document of KeyboardEvent.keyCode for the detail.

You need to get hold of the actual character. There are lots of questions like this one on the subject.

One approach is to use String.fromCharCode(e.which) which will work correctly for most browsers but only for KeyboardEvents originating from keypress, not keydown, or keyup handlers.

Differences between keydown and keypress

document.body.addEventListener("keydown", function(e) {console.log(e.keyCode)}, false);

 219

Whereas

document.body.addEventListener("keypress", function(e) {console.log(e.keyCode)}, false);

123
Community
  • 1
  • 1
Adam
  • 35,919
  • 9
  • 100
  • 137