0
votes

This is really weird.

I have a textarea. I listen to the keyup and keypress events.

When I press "(", keypress is fired with e.keyCode == e.which == 40

When I press the arrow down key, keyup is fired with e.keyCode == e.which == 40

Why is this so strange?

2
By ( you mean holding shift and pressing 9, correct? - James Montagne
Which browser are you using? With keypress in chrome with jquery, I am unable to capture arrow keys. ( does give me 40, which is the ascii code for that character. - James Montagne

2 Answers

3
votes

Traditionally, the arrow keys overlapped ASCII codes, but were represented to the programmer as a two-byte sequence so you were aware that a special key has been pressed. With the advent of Unicode this is no longer a clean solution.

Browsers have implemented different ways of representing special key input to the Javascript runtime. The details are explained here.

I usually use the 'keydown' event when detecting arrow keys, as this event has the correct keycode attached and will fire with a different keycode(the one for 9) when the user is typing a left parenthesis. This may not work in cases where you want to allow the user to repeat the keyed event by holding down the arrow key.

2
votes

keydown and keyup events provide a code indicating which key is pressed, while keypress indicates which character was entered.

Char code for "(" is 40 (keypress event) and key code for down arrow is also 40 (keyup).

Try:

String.fromCharCode(40); // "("