Parad0x13
Parad0x13

Reputation: 2065

HTML prevent space bar from scrolling page

I'm using the code:

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

which does exactly what I want, stops the page from scrolling when the spacebar is pressed. However it also prevents the user from typing spaces in a textbox

Is there a way to prevent the spacebar-scroll as well as retain the spacebar functionality while typing?

Upvotes: 54

Views: 55631

Answers (5)

Chris54
Chris54

Reputation: 1

CSS:

body::-webkit-scrollbar {display: none;} /* Chrome, Safari and Opera */
body {-ms-overflow-style: none;}  /* IE and Edge */
html {scrollbar-width: none;}  /* Firefox */

JavaScript:

window.addEventListener('keydown', function() {if (event.keyCode == 32) {document.body.style.overflow = "hidden";}});
window.addEventListener('keyup', function() {if (event.keyCode == 32) {document.body.style.overflow = "auto";}});

JavaScript makes the overflow hidden onkeydown event when the spacebar is pressed so it can't be scrolled and when you leave the spacebar it makes the overflow auto so it can be scrolled again. This changes the width of the page so the CSS can be added to disappear the scrollbar.

Upvotes: 0

Oriol
Oriol

Reputation: 288590

Try checking if target is the body:

window.addEventListener('keydown', function(e) {
  if(e.keyCode == 32 && e.target == document.body) {
    e.preventDefault();
  }
});
body { height: 100000px; }
<input />
<textarea></textarea>

Demo

Upvotes: 106

Stephan
Stephan

Reputation: 357

You could look into e.target and if it is the body you return false.

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

Upvotes: 2

Brian Glaz
Brian Glaz

Reputation: 15696

You can check the target of the event, and only run your code if it's not a 'type-able' element. For example:

window.onkeydown = function(e) {
    var elem = e.target.nodename;
    if( elem !== 'TEXTAREA' && elem != 'INPUT' ) {
        return !(e.keyCode == 32);
    }
};

Upvotes: 1

epascarello
epascarello

Reputation: 207537

window.onkeydown = function(e) { 
    e = e || window.event;  //normalize the evebnt for IE
    var target = e.srcElement || e.target;  //Get the element that event was triggered on
    var tagName = target.tagName;  //get the tag name of the element [could also just compare elements]
    return !(tagName==="BODY" && e.keyCode == 32);  //see if it was body and space
};

Upvotes: 0

Related Questions