Javascript bind keyup/down event

Viewed 50632

How do I bind a function to the key down/up events?

It can be either binded to the entire document or a single element, either will work in this case.

This has to be without any JavaScript library. I am only primarily concerned with the latest Firefox. Particularly the canvas element.

Ive tried this: (FF 3.6.9 Windows 7)

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <title>Test</title>
    </head>
    <body>
        <div class="wrapper">
            <canvas id="game" width="800" height="400">
            </canvas>
        </div>
        <script type="text/javascript">
            var el = document.getElementById("game");

            el.onkeydown = function(evt) {
                evt = evt || window.event;
                alert("keydown: " + evt.keyCode);
            };

            el.onkeyup = function(evt) {
                evt = evt || window.event;
                alert("keyup: " + evt.keyCode);
            };
        </script>
    </body>
</html>
1 Answers
Related