Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: different keyCodes on different browsers?

So I've seen some forums posts about different browsers reporting differenct 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 univeral 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.

Thanks.

like image 535
Senica Gonzalez Avatar asked Oct 07 '10 16:10

Senica Gonzalez


People also ask

What make JavaScript same in all browsers?

Javascript is defined by the ECMA-262 standard, which is updated anually. Every revision has added some new syntax. All browsers since IE5 support a common subset of syntax in the same way, it's only a question of if they support new syntax options or not.

What is e KeyCode === 13?

Keycode 13 is the Enter key.

What replaced KeyCode in JavaScript?

Definition and Usage. Note: The keyCode property is deprecated. Use the key property instead.

Is KeyCode deprecated in JavaScript?

Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes.


2 Answers

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!");
    }
};
like image 147
Tim Down Avatar answered Oct 02 '22 02:10

Tim Down


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.

like image 32
Plaudit Design Avatar answered Oct 02 '22 02:10

Plaudit Design