How to prevent the pressing of the space bar from scrolling the page with JavaScript?

Estimated read time 2 min read

To prevent the space bar from scrolling the page with JavaScript, you can listen for the keydown event on the document object, and then check if the space bar key was pressed using the keyCode or which property of the event object. If the space bar key was pressed, you can prevent the default behavior of scrolling the page using the preventDefault() method. Here’s an example of how to do this:

document.addEventListener('keydown', function(event) {
  if (event.keyCode === 32 || event.which === 32) {
    event.preventDefault();
  }
});

In this code, we add an event listener to the document object for the keydown event. Inside the event listener function, we check if the keyCode property of the event object is equal to 32, which is the keycode for the space bar key, or if the which property is equal to 32. If the space bar key was pressed, we prevent the default behavior of scrolling the page using the preventDefault() method on the event object.

Note that this code will prevent the space bar key from scrolling the page anywhere on the document. If you only want to prevent the space bar key from scrolling the page in certain elements, such as a textarea or input field, you can add the event listener to those specific elements instead of the document object.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply