Javascript keyboard events: the difference between keypress and keydown

Some things you learn the hard way. I was trying to catch some keyboard events in order to replace comma’s with dots in html input items and validating the input against a regular expression along the way. The results I got were at best confusing, but never as expected.

I did some reading on sites like http://javascript.info/tutorial/keyboard-events, and found out there is a fundamental difference between the keypress and keydown event. This shows especially when catching the “.” “,” or decimal point (yes, the decimal point on your numeric keypad is another character!)

The next output is consecutively a comma, a dot, and a decimal point on the numeric keypad. The keydown and keyup event present values that are unexpected, like the ¼ character. Only keypress shows comma and dot as expected.

keydown keyCode=188 which=188 charCode=0 char=¼
keypress keyCode=44 which=44 charCode=44 char=,
keyup keyCode=188 which=188 charCode=0 char=¼
——————————
keydown keyCode=190 which=190 charCode=0 char=¾
keypress keyCode=46 which=46 charCode=46 char=.
keyup keyCode=190 which=190 charCode=0 char=¾
——————————
keydown keyCode=110 which=110 charCode=0 char=n
keypress keyCode=46 which=46 charCode=46 char=.
keyup keyCode=110 which=110 charCode=0 char=n

Remember this when getting unexpected results when grabbing key-events in your web application.

Laat een reactie achter

Je e-mailadres wordt niet gepubliceerd. Vereiste velden zijn gemarkeerd met *

Deze site gebruikt Akismet om spam te verminderen. Bekijk hoe je reactie-gegevens worden verwerkt.

By using this site you acknowledge the use of cookies (which are mostly harmless, btw) More information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below you are agreeing to these settings.

Close