24

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.

  • Please check the "related" sidebar on the right. http://stackoverflow.com/questions/2343573/pressing-spacebar-moves-page-down – showdev Aug 30 '13 at 00:21

3 Answers3

45

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.

Community
  • 1
  • 1
Michael Schwartz
  • 8,153
  • 14
  • 81
  • 144
  • 1
    This code can block pressing space key on HTML input. You must check for (e.target === document.body) here full correct answer: http://stackoverflow.com/a/22559917/3120495 – ujeenator Sep 29 '15 at 15:36
8

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);
João Paulo Macedo
  • 15,297
  • 4
  • 31
  • 41
0

Have you tried capturing the keydown event in javascript? If you are using jQuery you can read more about capturing key events here: http://api.jquery.com/keydown/

If you aren't you can capture and ignore the space bar keypress as described here: https://stackoverflow.com/a/2343597/1019092

Community
  • 1
  • 1
S.E.T.
  • 137
  • 1
  • 8
  • @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."* – Stephen P Aug 30 '13 at 00:45