Home > front end >  Jquery: Use preventDefault() to disable only the space bar
Jquery: Use preventDefault() to disable only the space bar

Time:12-16

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!

CodePudding user response:

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

  • Related