Ok so what is the difference in .keypress and .keydown/.keyup? At present I am using .keydown which returns a .which value of 38 for my key, now if i change it to .keypress it returns a value of 109 for that same key. What is the difference and why are the values different for the same key?
- Different browser's should result in different event which's but not different key commandsSpYk3HH– SpYk3HH2012-04-17 12:56:40 +00:00Commented Apr 17, 2012 at 12:56
- I have a json object with every key event and each divided by browser, i'll post it too a fiddle real quick with all three keypresses and we can test this out, gimmie like 10 minsSpYk3HH– SpYk3HH2012-04-17 12:57:30 +00:00Commented Apr 17, 2012 at 12:57
5 Answers
If you press a button it fires a keydown and releasing it fires a keyup. The keypress usually comes between those two.
keydown and keyup talk about which key has been changed. keypress tells which character that key represents.
Note that this is all browser-dependent!
See this article about the differences between the key events as implemented on various browsers.
Comments
I'll be d$%^@d, there really is a difference with keypress and all this time I never realized. lol
See my fiddle and try something like the letter "r"
http://jsfiddle.net/SpYk3/NePCm/
Somehow I never paid attention to this
Found more info:
http://www.quirksmode.org/js/keys.html
"The two properties are
keyCodeandcharCode. Put (too) simply,keyCodesays something about the actual keyboard key the user pressed, whilecharCodegives the ASCII value of the resulting character. These bits of information need not be the same; for instance, a lower case 'a' and an upper case 'A' have the samekeyCode, because the user presses the same key, but a differentcharCodebecause the resulting character is different.Explorer and Opera do not support
charCode. However, they give the character information inkeyCode, but only withonkeypress.onkeydownand-upkeyCodecontains key information."
3 Comments
You should read the following post : http://javascript.info/tutorial/keyboard-events
Keydown triggers on any key press and gives scan-code. Keypress triggers after keydown and gives char-code, but it is guaranteed for character keys only.