Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

event.keycode not returning correct values in firefox

Tags:

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.

like image 835
Rajat Gupta Avatar asked Sep 07 '11 08:09

Rajat Gupta


People also ask

What is e keycode === 13?

key 13 keycode is for ENTER key.

Why is event keycode deprecated?

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 .

What is the difference between keycode and charCode?

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.


2 Answers

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.

like image 193
Tim Down Avatar answered Sep 19 '22 18:09

Tim Down


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; 
like image 36
Rolando Cruz Avatar answered Sep 18 '22 18:09

Rolando Cruz