I have a problem that I’m not even sure what to search for in order to fix. When I press the spacebar my entire page moves up (scrolls down): I don’t want this to happen. My body tag is styled to overflow:hidden, if that has anything to do with it, so the page won’t have any scrollbars. I’m usually pretty good at executing the preliminary troubleshooting techniques but in this case I don’t even know where to start. How can I stop this behaviour?
Additional information: I am using jQuery 1.4.2
This default scrolling behavior comes from the
keydownevent. In order to prevent it, you must handle thekeydownevent and prevent the default behavior, either by returningfalsefrom the event handler or callingevent.preventDefault().As a rule of thumb, think carefully before you prevent default behavior like spacebar scrolling. I use it all the time and I get extremely annoyed when it doesn’t work in a page.
But if you want to eat the key…
According to the MDN web docs for
KeyboardEvent#keyCode,keyCodeis a deprecated property. Although it still works in most browsers, you are encouraged to use #KeyboardEvent #key (https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key) going forward, which is a more standardized string representation of a key. Thekeyvalue for spacebar is literally the input value:" "(single space string). So if you wanted to be very careful to support all browsers, you could write: