How to prevent scrolling triggered by the space key

There was the DOM node which should do something when the user presses the space key. So, I added an event listener and implemented the desired behaviour. I was naive enough to think that I was done and tried it out. But, I forgot that space key does what an space key gotta do—it scrolls the page. Still being naive, I thought that preventing this was fairly trivial but it took me longer than I want to admit.

Adding an event.preventDefault() to my event handler did not work. This surprised me and left me speechless for a moment. In a desperate attempt to solve this I slapped event.stopPropagation() and return false on it. Not working either. What was the problem then? I was listening to the keyup event. At this point, however, the scrolling is already triggered. You actually want to listen to the keydown event and call its preventDefault function.

Whenever something appears harder than it should be than it probably is. I was, indeed, working against the web. My DOM node was a <div>. Let's rewind: The scrolling which is triggered by the space key can be prevented in the keydown event. But if you run into a situation, you are probably doing something wrong already. If you need an interactive element, use one! Pressing space on a <button> does not scroll the page. As a plus, you don't even have to set tabindex to 0. Convenient, isn't it?