Search code examples
javascriptfirefoxkeyboard-eventskeydown

document.onkeydown doesn't work in firefox


I'm in trouble, I got this site (bummer.wtf) where every time you hit a button this button brings you in a different page. Everything works perfectly in Chrome and Safari, but in firefox I get trouble, nothing seems to happen.

    document.onkeydown = function(event){
var key = event.which || event.keyCode;
     if(window.event && window.event.keyCode == 65) 
     {
        window.location.href = "about.html"
     }
     if(window.event && window.event.keyCode == 67) 
     {
        window.location.href = "contact.html"
     }
    }

What can I do? I got a similar script for the enter button, but that one work perfectly even on firefox.


Solution

  • Firefox uses event.key not event.code check that instead (actually check both for it to work everywhere). Also you should add event as a parameter. If on IE window.event will exist; however for others it will not.

    document.onkeydown = function(event){
        var keyCode = event.key|| event.code;
        if (keyCode == 65) {
            window.location.href = "about.html"
        }
    
        if(keyCode == 67) {
            window.location.href = "contact.html"
        }
    }