Categories
JavaScript Answers

How to Prevent the Pressing of the Space Bar from Scrolling the Page with JavaScript?

Spread the love

Sometimes, we want to prevent the pressing of the space bar from scrolling the page with JavaScript.

In this article, we’ll look at how to prevent the pressing of the space bar from scrolling the page with JavaScript.

Prevent the Pressing of the Space Bar from Scrolling the Page with JavaScript

To prevent the pressing of the space bar from scrolling the page with JavaScript, we can listen to the keydown event with window.addEventListener .

Then in the event handler, we can detect pressing the space bar on the body element.

For instance, we can write:

window.addEventListener('keydown', (e) => {  
  if (e.keyCode === 32 && e.target === document.body) {  
    e.preventDefault();  
  }  
});

We call window.addEventListener with 'keydown' and an event listener that detects presses of the space bar on the body element.

Key code 32 is the space bar and e.keyCode has the numeric code of the key that’s pressed.

e.target has the element that the keydown event is emitted from. And we compare that against the body element with document.body .

e.preventDefault prevents the default behavior when the space bar is pressed, which is to scroll the page.

Conclusion

To prevent the pressing of the space bar from scrolling the page with JavaScript, we can listen to the keydown event with window.addEventListener .

Then in the event handler, we can detect pressing the space bar on the body element.

2 replies on “How to Prevent the Pressing of the Space Bar from Scrolling the Page with JavaScript?”

Java novice: how do i gain access to this area to type the code in? Or should I?
I want my space bar to act like a space bar – not a scrolling tool. Please and thank you in advance for the detailed instructions.

You can use the e.key property to check which key is pressed.

Then if e.key is ‘Spacebar’, then you can call e.preventDefault.

Leave a Reply

Your email address will not be published. Required fields are marked *