Search code examples
javascriptinternet-explorerkeypress

How do I properly attach to the keypress event?


I have a seemingly simple problem to which I can't find a solution. Given the following code:

<html>
    <head>
        <script type="text/javascript">
            document.onkeypress = function(ev) {
                if (!ev) { alert("Broken"); return; }
                var key = ev.charCode || ev.keyCode;
                alert(key);
            }
        </script>
    </head>
    <body>Test</body>
</html>

If I save it as a file and load it in IE and I press a key it always comes up with the "Broken" alert whereas it works fine (alert with the keycode) in Firefox.

If I use window.onkeypress instead of the document handler it's not being called at all in IE. If I attach the handler in the onload event it doesn't make a difference. Using events like keydown or keyup don't make a difference (still broken in IE).

Yet, when I use jsfiddle for the example it works fine in IE.

So: What does jsfiddle differently from the code above and how do I get it to work in IE?


Solution

  • Including a DOCTYPE is important in any browser, but even more in IE. If one is omitted, I believe it uses quirks mode, which means bad things. You can add the HTML5 doctype:

    <!DOCTYPE html>
    

    Doctypes should be the first non-empty line in an HTML file. That means even comments shouldn't come before the doctype, and can cause IE to use quirks mode.

    Here is a nice little read on the difference between standards mode and quirks mode: https://developer.mozilla.org/en-US/docs/Quirks_Mode_and_Standards_Mode

    In addition, as a note, IE uses the global event variable for events, so you should check that instead of thinking it's broken. For example:

    ev = ev || window.event;
    

    can replace your if statement line.