builtin method for detecting keyboard space/enter click of focusable elements?

34 views Asked by At

I have an element that is clickable and focusable but it is not a button.

I have used the tabindex="0" attribute so it can be tab focused.

For buttons, if you tab focus onto them and hit Enter/Space, it is effectively the same as clicking it.

I want to replicate the exact same behaviour with my element.

I assume there is a built-in way of doing this besides using a keydown event listener but I can't find a solution.

1

There are 1 answers

0
Michael M. On

You can create a keydown event handler and dispatch a new click event if the enter key is being pressed.

However, you won't get all event data as a natural click event. For example, the e.clientX and e.clientY properties don't make much sense if you've used tab and enter. This likely won't matter to you though.

const thing = document.getElementById("thing");

thing.addEventListener('click', function(e) {
  console.log("Thing was clicked at (" + e.clientX + ", " + e.clientY + ")");
});

thing.addEventListener('keydown', function(e) {
  if (e.key == "Enter" || e.key == " ") {
    e.target.dispatchEvent(new CustomEvent('click'));
  }
});
<div id="thing" tabindex="0">Thing</div>