Senica Gonzalez
Senica Gonzalez

Reputation: 8182

How can I deal with different keyCodes on different browsers?

I've seen some forums posts about different browsers reporting different keyCodes, but everyone seems so avoid the "why?".

I was trying to capture the colon (:) keyCode and realized that Firefox reports back e.keyCode 56. While Chrome reports back 186 (I think that's what it was).

Is there a universal way of getting the right keyCode across all browsers?

And why are they different if they are the same keys?

I would be more curious as to whether there is a international way of getting the same key press.

Upvotes: 20

Views: 21858

Answers (7)

QuirkyCoder
QuirkyCoder

Reputation: 1

2023 here, and I've been using a different solution to this for a long time.

It involves using a hidden textarea to get the typed character. It is a bit of a hack, but it works flawlessly in all major browsers and saves the headache of working with e.key, e.keyCode, etc.

I'll just post the code here. It's fairly self-explanatory. If you're wanting this to work in all mobile browsers, including Opera Mini, etc. then you'll have to change the fixed positioning to absolute positioning and make sure the textarea is always positioned around the middle of the visible part of the page to avoid scrolling whenever a character is typed.

Basically, create a hidden textarea, add a keydown event to the window object that focuses the textarea, get the value of the textarea, clear the textarea, focus the previously focused element again...and optionally then generate the typed character in the previously focused element.

/* Create a hidden textarea */
var keyGrabber = document.createElement('textarea');
keyGrabber.style.border = '0';
keyGrabber.style.margin = '0';
keyGrabber.style.padding = '0';
keyGrabber.style.outline = 'none';
keyGrabber.style.position = 'fixed';
keyGrabber.style.top = '0';
keyGrabber.tabIndex = '-1';

document.body.appendChild(keyGrabber);

/* Avoid confusion for screen readers */
keyGrabber.setAttribute('aria-hidden', 'true');

/* Init the variables here so they are global and easy to access */
var oldActiveElement = document.activeElement;
var oldStart = 0;
var oldEnd = 0;

/* Catch the keydown event and store the active elements
   selection start and end in case you still want the
   character to be typed */
window.addEventListener('keydown', function(e) {
    oldActiveElement = document.activeElement;
    oldStart = oldActiveElement.selectionStart;
    oldEnd = oldActiveElement.selectionEnd;
    keyGrabber.focus();
    /* If you need to capture keys that don't generate
       written characters, you'll have to do that here
       using e.key || e.keyCode */
});

keyGrabber.addEventListener('input', function() {
    var character = keyGrabber.value;
    if(character == ':') {
        alert('You typed a colon!');
        /* Replace alert with whatever code you want
           to execute when a colon is typed */
    }
    keyGrabber.value = '';
    oldActiveElement.focus();
    /* This part is optional, in case you want to still
       have the typed character generate in an input
       and also fire the event. You would then also
       replace "window.addEventListener..." with
       "yourInput.addEventListener..." */
    var part1 = oldActiveElement.value.slice(0, oldStart);
    var part2 = oldActiveElement.value.slice(oldEnd, oldActiveElement.value.length);
    oldActiveElement.value = part1 + character + part2;
    oldActiveElement.selectionStart = oldStart + 1;
    oldActiveElement.selectionEnd = oldActiveElement.selectionStart;
});

Please don't copy/paste this code and expect it to work flawlessly. I'm typing this from memory and not copying it from a working file. I can't remember if setting the tabIndex to -1 stops the .focus() from working. I think it's fine, but please double check this.

Upvotes: 0

Roland
Roland

Reputation: 5234

Have also a look at this GitHub file: key-to-charCode/jQuery.getChar.js on how you can use keyDown instead of keyPress events.

I used this for a barcode scanner with a keyboard wedge, on a mobile device that had a bug on returning (keyPress) data for scanning a hyphen. It worked pretty good. Except when I tested the app in a browser with a regular keyboard, I noticed that the hyphen works on Chrome, but not on Firefox. Strange, but true. Fixed by adding code 173 in the above JavaScript file, in addition to code 189.

This makes me wonder what the keyboard is actually sending. The keydown code of 173 or 189 for pressing the hyphen key (- _) is apparently not sent by the keyboard itself, but created by the browser that sends the keyDown event to my JavaScript application.

Upvotes: 0

kidconcept
kidconcept

Reputation: 559

The modern way to do this is use event.key. See MDN Key.

Upvotes: 3

wraiford
wraiford

Reputation: 651

2022 - event.key gives the "logical" key, event.code gives the "physical" key

Some examples tested on macOS Firefox, Windows Edge, and Windows Chrome:

event.key event.code
"Enter" "Enter"
"Enter" "NumpadEnter"
"8" "Digit8"
"8" "Numpad8"
"/" "Slash"
"/" "NumpadDivide"

Edge cases

  • Windows Chrome/Edge, when pressing Ctrl + Enter the event.key is "\n"

Upvotes: 1

Tim Down
Tim Down

Reputation: 324507

It depends whether you're interested in which physical key the user has pressed or which character the user has typed. If it's the character you're after, you can get that reliably in all major browsers (using the keypress event's which property in most browsers or keyCode in IE <= 8), but only in the keypress event. If you're after the key, use the keydown or keyup event and examine the keyCode property, although the exact key-code mappings do differ somewhat between browsers.

An excellent explanation of and reference for all JavaScript key-related events can be found at http://unixpapa.com/js/key.html.

To detect the user typing a colon character reliably in all the major browsers, you could do the following:

document.onkeypress = function(e) {
    e = e || window.event;
    var charCode = (typeof e.which == "number") ? e.which : e.keyCode;
    if (charCode && String.fromCharCode(charCode) == ":") {
        alert("Colon!");
    }
};

Upvotes: 18

ifroz
ifroz

Reputation: 113

I think you should make JavaScript to get the keycode of the ':' character, so the script will know what is it in a certain environment. Similar question had been asked here, in stackoverflow.

Upvotes: 0

Plaudit Design
Plaudit Design

Reputation: 1156

See http://unixpapa.com/js/key.html for an explanation why they have different keys. I do not know of an international way to match keys.

Upvotes: 13

Related Questions