Disable scroll down when spacebar is pressed on firefox

30,220

Solution 1

This should do the trick. It states that when the spacebar is pressed on the page/document it doesn't just prevent its default behavior, but reverts back to original state.

return false seems to include preventDefault. Source

Check JQuery API's for more information about keydown events - http://api.jquery.com/keydown/

window.onkeydown = function(e) { 
    return !(e.keyCode == 32);
};

JQuery example

$(document).keydown(function(e) {
    if (e.which == 32) {
        return false;
    }
});

EDIT:

As @amber-de-black stated "the above code will block pressing space key on HTML inputs". To fix this you e.target where exactly you want spacebar blocked. This can prevent the spacebar blocking other elements like HTML inputs.

In this case we specify the spacebar along with the body target. This will prevent inputs being blocked.

window.onkeydown = function(e) {
  if (e.keyCode == 32 && e.target == document.body) {
    e.preventDefault();
  }
};

NOTE: If you're using JQuery use e.which instead of e.keyCode Source.

The event.which property normalizes event.keyCode and event.charCode

JQuery acts as a normalizer for a variety of events. If that comes to a surprise to anyone reading this. I recommend reading their Event Object documentation.

Solution 2

Detect if the spacebar is being pressed. If it is, then prevent its default behaviour.

document.documentElement.addEventListener('keydown', function (e) {
    if ( ( e.keycode || e.which ) == 32) {
        e.preventDefault();
    }
}, false);
Share:
30,220
Alberto Castro Yepiz
Author by

Alberto Castro Yepiz

Updated on September 30, 2020

Comments

  • Alberto Castro Yepiz
    Alberto Castro Yepiz over 3 years

    I want to disable the scroll down when i pressed the spacebar. This only happens in firefox.

    I already use overflow:hidden and meta tag viewport.

    Thanks.

  • Stephen P
    Stephen P almost 11 years
    @Alberto - be sure to read the part of the answer that says "this is the expected behavior in most browsers. I use it all the time and I get extremely annoyed when it doesn't work in a page."
  • ujeenator
    ujeenator over 8 years
    This code can block pressing space key on HTML input. You must check for (e.target === document.body) here full correct answer: stackoverflow.com/a/22559917/3120495