event.keycode not returning correct values in firefox

21,550

Solution 1

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.

Solution 2

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;

Solution 3

KeyboardEvent.keyCode :

The value of keypress event is different between browsers. IE and Google Chrome set the KeyboardEvent.charCode value. Gecko sets 0 if the pressed key is a printable key, otherwise it sets the same keyCode as a keydown or keyup event

So from Firefox point of view, it has actually returned correct values. See the docs.

keyCode, which, keyIdentifier and charCode are deprecated

This feature has been removed from the Web standards. Though some browsers may still support it, it is in the process of being dropped. Avoid using it and update existing code if possible;

keyIdentifier had no support in IE and Firefox and been dropped from Opera and Chrome
With charCode as Non-standard

This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations

So what are the alternatives?

I. Use the key property instead

readonly attribute DOMString key

Holds a key attribute value corresponding to the key pressed

Examples : "a", "A", "@", "%", "$", "ا", "ب", "ة", "ت", ..., "١", "٢", "٣", "Tab", "Enter" , all "F1"...`

It has earned the support of all major browsers (Firefox 52, Chrome 55, Safari 10.1, Opera 46) except Internet Explorer 11 which has non-standard key identifiers and incorrect behavior with AltGraph. More info
If that is important and/or backward compatibility is, then you can use feature detection as in the following code :

Notice that the keyvalue is different from keyCode or which properties in that : it contains the name of the key not its code. If your program needs characters' codes then you can make use of charCodeAt(). For single printable characters you can use charCodeAt(), if you're dealing with keys whose values contains multiple characters like ArrowUp chances are : you are testing for special keys and take actions accordingly. So try implementing a table of keys' values and their corresponding codes charCodeArr["ArrowUp"]=38, charCodeArr["Enter"]=13,charCodeArr[Escape]=27... and so on, please take a look at Key Values and their corresponding codes

if(e.key!=undefined){
        var characterCode = charCodeArr[e.key] || e.key.charCodeAt(0);
    }else{
        /* As @Leonid suggeted   */
        var characterCode = e.which || e.charCode || e.keyCode || 0;
    }
        /* ... code making use of characterCode variable  */  

II.You can also use the code property :

readonly attribute DOMString code

Holds a string that identifies the physical key being pressed. The value is not affected by the current keyboard layout or modifier state, so a particular key will always return the same value.

It has a similar effect to the key property and an output like "keyW" for button W pressed of a US keyboard with QUERTY layout. If the same button was pressed in another layout (AZERTY) or another language (Hebrew) or combined with a modifier (shift), key property would change accordingly, while the code property would still have the same value "keyW" more on this here.

The code property is supported in Chrome 49, Firefox 52, Safari 10.1 and Opera 46 But not in Internet Explorer.

see also :

  1. KeyboardEvent.charCode
  2. KeyboardEvent.keyIdentifier
  3. KeyboardEvent.keyCode
  4. KeyboardEvent.which
  5. KeyboardEvent.key
  6. key property support
  7. KeyboardEvent.code
  8. code property support

Solution 4

IF event.keyCode is not returning proper values then for firefox you can use event.charCode

var keyValue = event.charCode || event.keyCode;

Solution 5

if you're getting a 0 no matter which key you press, try using charCode instead of keyCode

This happens because you are calling the KeyboardEvent object which uses which and charCode as opposed to the Event object which uses keyCode for returning keyboard Unicode values. For more information, refer to MDN web docs for more information regarding the KeyboardEvent: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent

Share:
21,550
Rajat Gupta
Author by

Rajat Gupta

A problem solver & enthusiastic programmer looking out for exciting work opportunities. Highly interested in building Android applications, Web development, & Server side coding involving (sql/ nosql) databases & APIs. I love solving problems, building efficient approaches & algorithms. To describe my strong points, I have pretty decent problem solving skills, fast learner & highly motivated & energetic person! Gained good experience in software development in the past 2 years working on numerous android & web development projects with companies like olready.in, twowaits.com, spactre.com. Selected among Top three finalists for LinkedIn MTV GetAJob Season 4 for Flipkart as Software Developer Intern among 50k candidates.

Updated on July 09, 2022

Comments

  • Rajat Gupta
    Rajat Gupta almost 2 years

    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.

  • Rajat Gupta
    Rajat Gupta over 12 years
    this returns undefined for enter in firefox
  • Rolando Cruz
    Rolando Cruz over 12 years
    yes, but the OP is trying to catch the spacebar keypress =)
  • Rolando Cruz
    Rolando Cruz over 12 years
    Thanks for pointing that out. Actually typed that on the fly =) The edited version should work
  • Leonid
    Leonid over 12 years
    evt.which || evt.charCode || evt.keyCode || 0 - 50% less space
  • Rolando Cruz
    Rolando Cruz over 12 years
    @SomeGuy, this will return a boolean value right? Then charCode will have a boolean value instead of anyone of the three above. Correct me if I'm wrong
  • Tim Down
    Tim Down over 12 years
    @Rolando: No, the || does not necessarily evaluate to a Boolean value. a || b evaluates to a if a is truthy and b otherwise.
  • Tim Down
    Tim Down over 12 years
    @Rolando, @SomeGuy: Also, there's no need to use charCode at all. Every browser that supports charCode also supports which, and some (Opera) only support which.