Search code examples
javascriptcross-browserkeypress

Javascript Spacebar Event Handler - only works in Firefox


<script>

$(function(){

    $("#button-start").click(game.start);

    $(window).keypress(function(e) 
    {
        if (e.keyCode == 0) 
        {
            game.check(true);
        }
    });
});

</script>

This only captures the spacebar keypress event in Firefox. Does not work in IE or Chrome.

How do I modify this to make it work for all browsers?


Solution

  • jQuery normilised the key codes under which event property. Spacebar has code 32:

    $(window).keypress(function(e) {
        if (e.which === 32) {
            game.check(true);
        }
    });
    

    You can use $(document) instead to be more browser compatible.