I have a button with an anchor, that I would like to trigger with the spacebar for accessibility reasons. Instead, clicking the spacebar jumps the page down when button is in focus.
<a href="stackoverflow.com">Go to Stack Overflow</a>
I have tried eating the spacebar key:
window.onkeydown = function(e) { 
  return !(e.keyCode == 32);
};
but of course this is not what I want. I'm not sure if mapping the spacebar key to the enter key is a smart solution, or if its possible. How can I trigger a button with the spacebar using pure JS?
You might want to look into a prevent default solution:
window.onkeydown = function(event){
    if(event.keyCode === 32) {
        event.preventDefault();
        document.querySelector('a').click(); //This will trigger a click on the first <a> element.
    }
};
That will stop the space bar from performing the default action (to send a space) and then you can add your scroll to command below that inside the function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With