On a web page, if you hit the spacebar key on your keyboard, the web page will scroll down. This is a default browser behavior. So you can’t stop it using CSS.
But you can do it using JavasScript. Don’t worry if you’re new to JavaScript. It’s only a few lines of code and works without any dependencies.
How to prevent the spacebar from scrolling?
To prevent the spacebar from scrolling the web page, write the following JavaScript:
window.addEventListener("keydown", function (e) {
if (e.keyCode === 32) {
e.preventDefault();
}
});
That’s it!
Explanation of the above JavaScript
keydown
is an event. Every key on your computer keyboard has a unique number. In our case, it’s the spacebar key which has a number of 32. And this is what we are checking in the if
condition. You can find any key’s number here.
Anyways, preventDefault
is a method. And it tells the web browser to stop its default behavior. This is exactly what we are doing.
Inside the function
, “e” is a parameter that is short for the event. However, you can name it anything. Once this event (keydown) is true, the function
will pass the parameter (e).
All this is saying is if the keypress/key-down is equal to the spacebar (32) then prevent its default behavior.
That’s all.