jQuery .keypress & .keydown .which
Solution 1
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.
Solution 2
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
keyCode
andcharCode
. Put (too) simply,keyCode
says something about the actual keyboard key the user pressed, whilecharCode
gives 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 differentcharCode
because the resulting character is different.Explorer and Opera do not support
charCode
. However, they give the character information inkeyCode
, but only withonkeypress
.onkeydown
and-up
keyCode
contains key information."
Solution 3
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.
Solution 4
In normal cases, go for keyup
:
$(document).keyup(function(e){
console.log(e.which);
});
Reasons:
keydown
keeps firing when user holds the keys down, whilekeypress
andkeyup
fire only once.keypress
doesn't detect special keys (e.g.SHIFT
),keydown
andkeyup
do.
Solution 5
KeyPress happens after KeyDown. So you can use KeyDown to determine what key it is, then KeyPress to disallow that character.
ChrisMJ
Updated on August 02, 2020Comments
-
ChrisMJ almost 4 years
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?
-
ChrisMJ about 12 yearsYea, so this is why I am confussed as to why?
-
SpYk3HH about 12 yearswell as jbl pointed out in his answer, this page describes the problem just a little bit, but it still doesn't seem to answer the question in whole. Maybe I read the page wrong, but at one point it still points out the charcode as being pulled on both, simply one reutrns a different value. Perhaps a look in some old js doc will find the answer. I'm looking now, also gonna rewite my object to include the keypress differences
-
SpYk3HH about 12 yearsalthough i would suggest avoiding keypress as it doesn't fire as predictable events as keydown and keyup