Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are Javascript char codes compatible with all or certain browsers?

I have found the following code on the internet, when I saw this solution I wondered if this key code is the same for all browsers.

var CalendarFilter = Backbone.View.extend({
      // ...
      events: {
        'click .filter':  'filter',
        'keypress input[type=text]': 'filterOnEnter'
      },
      filterOnEnter: function(e) {
        if (e.keyCode != 13) return;
        this.filter(e);
      },
      filter: function(e) { /* ... */ });
      }
    });

Just a doubt, thanks.

like image 926
Uuid Avatar asked Dec 25 '12 02:12

Uuid


1 Answers

First of all, charCode is not keyCode! charCode follows the ascii set, while keyCode is a particular index of the key.. The different values between the two can be seen here: Keyboard Event Character Values for the Lower ASCII Character Set - O'Reilly Answers

One major difference between charCode and keyCode is that charCode is deprecated and typically has no value in some browsers [apart from 0] when referenced

Funnily enough, onkeypress seems to return the character code instead of the keyCode, while onkeyup and onkeydown works as expected, so there may be some issues when detecting keyCode values. You can test this out here JavaScript - Detecting keystrokes - Additional reference: keyCode and charCode.

keyCode, charCode and which is not recommended by w3c, however, there is still legacy support for the keyCode model. Solid cross browser/platform support is done with fixed virtual keyCodes that stay independent of keyboard layout - hence being "virtual".

Other Virtual keyCodes - outside of the fixed virtual keyCodes - seems to be consistently implemented across vendors as well: KeyboardEvent - Document Object Model (DOM) | MDN Virtual-Key Codes (Windows)

jQuery uses it's own keyCode/charCode event object property: .which, which attempts to unify keyCode and charCode. And favors keyCode values - event.which – jQuery API

In short, your specific keyCode: "13", should work with most browsers that support javascript as it is a fixed virtual keycode and is consistent with all browsers and platforms

like image 173
extramaster Avatar answered Sep 20 '22 16:09

extramaster