Wednesday, May 26, 2010

Detailing of onkeyup, onkeydown and onkeypress javascript events

Developers need to be very careful while using these events because they don't work the same way as they look like. onkeydown and onkeyup events are fired when a keyboard key is pressed and released subsequently. these events will give you the keycode of the key only.
onkeypress event is also fired when you press a key but this event will give you the charcode of the key only. infact if you try to get the keycode from the event, it will give you the same value as charcode.

Now you might be wondering what is the difference in keycode and charcode and why there is two different type of implementation and which event needs to be captured and implemented and when?

Keycode: This value just tells you which key on the keyboard user actually pressed.
Charcode: This value is basically ascii value of the resulting character coming out of the key pressed.

so for e.g. if i press 'a' or 'A', keycode value will remain the same but charcode value will differ for both.

It is worth to mention here that there are few keys in the keyboard which does not emit any resulting character for e.g. arrow keys, for such keys the onkeypress events will not be fired.

Which events to be used:  it is upto your requirements. Let say I have a requirement of allowing users to type numbers only in a textbox, I would prefer to use "onkeypress" event, and put a check for ascii value of numbers only. I wouldn't be interested to know what else user is typing and I would prefer to leave arrow/backspace/esc etc keys unnoticed since they don't emit any characters eventually.

If I have a requirement in which I would like to handle the above situation in more granular way for e.g. I won't let user hit the ENTER button or focus out by pressing ESCAPE button, I would prefer to get hold of all the characters with their keycode and use onkeydown event.

If I have a requirement that I want to do some action based on what key is pressed (but don't want to play around with the key itself), I would prefer to use onkeyup event. for e.g. having accelerator keys in the dialog box so let say close my dialog as soon as key 'o' from OK of dialogbox is pressed and released.

Before winding up this article let me give you some examples to make it more clear for you.

Pressed char 'a':
keydown
keyCode is 65
charCode is 0

keypress
keyCode is 97
charCode is 97

keyup
keyCode is 65
charCode is 0


Pressed some 'arrow' key:
keydown
keyCode is 37
charCode is 0

keyup
keyCode is 37
charCode is 0



keypress did not fire

No comments:

Post a Comment