Search code examples
javascriptjqueryfirefoxpreventdefault

Disable arrow key page scrolling in Firefox


I have a project where the arrow keys can be used as a method of input, in most browsers simply using .preventDefault() works perfectly, however Firefox (v37 on both Win8 and OSX) still seems to move the browser window (If there's available off screen scroll-able area)

$(document).keyup(function (evt) {
    if (evt.keyCode == 39 || evt.keyCode == 40) { // Right arrow, Down arrow
        evt.preventDefault();
        // Actual code
    } else { 
        if (evt.keyCode == 37 || evt.keyCode == 38) { // Left arrow, Up arrow
            evt.preventDefault();
            // Actual code
        }
    }
})

I've seen some things about using charCode, however my code does run so the .preventDefault() is defiantly being hit.

As far as I can tell, there's no reason this should move the window position.

Am I doing something wrong? Or if not, is there another way to disable the window moving due to arrow keys?


Solution

  • You have to listen keydown event instead of keyup cause the former is always happened prior to the latter. This mean that browser may respond to keydown event before keyup event is happened. In this case you cannot cancel browser's response action (i.e. scrolling) from keyup listener anymore.