I am trying the following code for triggering a js method when space-bar is pressed within an input box.
<input id="j1" /> $('#j1').keypress (function (event){ alert(event.keycode) }); In firefox this returns correct value only when enter is pressed, values returned for other keys are just 0 everytime. In IE/ chrome this works perfectly.
key 13 keycode is for ENTER key.
KeyCode was deprecated because in practice it was “inconsistent across platforms and even the same implementation on different operating systems or using different localizations.” The new recommendation is to use key or code .
keyCode: Returns the Unicode value of a non-character key in a keypress event or any key in any other type of keyboard event. event. charCode: Returns the Unicode value of a character key pressed during a keypress event.
In non-IE browsers, you want the which or charCode property in a keypress event rather than the keyCode property. The keypress event is for detecting typed characters while keyup and keydown are for detcting physical keys (in those events, keyCode works in every major browser).
var charCode = (typeof event.which == "number") ? event.which : event.keyCode; However, jQuery normalizes the which property of keypress events by using code similar to this, so in jQuery you just need
var charCode = event.which; For (a lot) more detail about key events, see http://unixpapa.com/js/key.html.
The problem is not all browsers have the same implementations on keypresses. The solution would be to check all possible places where the key was registered. In this case: event.keycode and event.which
See this post for more info
jQuery Event Keypress: Which key was pressed?
EDIT
Finally dug up my old functions, this is the actual code that I use:
evt = (evt) ? evt : event; var charCode = evt.which || evt.charCode || evt.keyCode || 0;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With