event.keycode not returning correct values in firefox

Rajat Gupta picture Rajat Gupta · Sep 7, 2011 · Viewed 20.9k times · Source

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.

Answer

Tim Down picture Tim Down · Sep 7, 2011

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.