Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Click button with spacebar

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?

like image 998
bruh Avatar asked Dec 19 '22 06:12

bruh


1 Answers

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.

like image 54
fouroh4 Avatar answered Dec 30 '22 13:12

fouroh4