سؤال

Say that I am not using jQuery, and want to support IE8 along with the other mainstream browsers.

In order to normalize events, I am following this pattern:

document.onkeydown = function(e) {
    
    var code;
    
    if (!e) {
        var e = window.event;
    }
    
    code = e.which || e.keyCode;

    // More stuff here...
};

However, I suspect that if I changed the order of my e.which vs e.keyCode check, like so...

code = e.keyCode || e.which;

...then my code might act differently across browsers.

  1. Question: Does the order matter? Is one order "better" than the other?
  2. Bonus: If I'm only supporting IE8 and up, does e.charCode matter?
  3. Another bonus: Should I use var e = window.event or just e = window.event?
هل كانت مفيدة؟

المحلول

1. Yes, the order matters.

The order you should use is indeed:

code = e.which || e.keyCode;

This is because most browsers support e.which (IE<9 excluded, of course). This way, any browser (IE>=9 and FF, Chrome, Opera, Safari, etc.) that supports e.which will use it, and those that don't will use e.keyCode.

Should you switch the order to:

code = e.keyCode || e.which;

You'll get e.keyCode for virtually every browser (instead of e.which) which will tell you the key that was pressed but not the resulting character (which I suspect is not what you want).

2. No, e.charCode does not matter.

Browser support for e.charCode is spotty at best. Even IE9 documentation states that it's for compatibiity only. Most popular modern browsers return undefined or 0 (or ASCII, or Extended ASCII, if you're lucky and even then it's only on keypress).

Additional reading for both 1 and 2 should probably be done at:

Should you wish to play around with key events, I made a fiddle for you to report the [relevant] properties of the event parameter when you type in the sole input field.

3. You should definitely use var e = window.event;.

If you don't use var, you're effectively declaring window.e = window.event which is silly. Use var to keep e defined in the scope of your handler.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top