Reputation: 2065
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
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
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>
Upvotes: 106
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
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
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