Search code examples
javascriptfirefoxkeypressesc-key

Esc key not getting recognized in Firefox


For some reason this script isn't working in Firefox:

document.onkeydown=function keypress(e) {
    if (e.keyCode == 27) {
        window.location = "/edit"
    };
};

It works fine in Chrome, but for some reason it's not working in Firefox.

Basically, what it does is load the /edit page when you press the escape key.


Solution

  • use:

    document.onkeydown=function keypress(e) {
      e=(e||window.event);  
        if (e.keyCode == 27) {
            try{e.preventDefault();}//Non-IE
            catch(x){e.returnValue=false;}//IE
            window.location = "/edit";
        };
    }
    

    The default-action for ESC is to stop loading the page,
    so you must prevent from this behaviour, otherwise you cannot change the location.

    Fiddle: http://jsfiddle.net/doktormolle/CsqgE/ (Click into the result-frame first before using ESC)

    But however, you really should use another key.
    A user expects that the loading of the current page stops if he uses ESC , nothing else.