Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Jquery: Use preventDefault() to disable only the space bar

I’d like to use the function preventDefault() to disable the spacebar from jump-scrolling down, like it usually does in Chrome, for example. If I try this:

$('html').keydown(function(e){
 if(e.keyCode == 32){
  e.preventDefault()
 }
});

I get the intended behavior, but the preventDefault function has all kinds of unwanted effects as well on my website. How do I specifically assign this function to say "prevent the default behavior of the spacebar, and do nothing else"?

Thank you!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Below should work in vanilla js:

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

explanations:

add a key down event listener on window itself then check whether key pressed is space or not and also check that its target is on document body

you could also check the key like: e.code === "Space" but checking 2 numbers is faster performance wise

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading