1

Is there a way to intercept enter key on a link without using Bookmarklet (href="javascript:...")?

I was trying this:

addEventListener('keypress', (e) => {
  console.log(e);
  if (e.charCode == 13) {
    alert('x');
  }
});
<a href="#">this is link</a>

If you press the tab and enter the code is not triggered. Only when the link is not in focus the alert will be triggered. Is there a way to trigger JavaScript on press enter over a link? Or is href the only way? There should be a way to use JavaScript and not have to put JavaScript into every link on the page.

And if you ask why I need this, it's because of this question: how to open a file upload dialog box when a hyperlink is clicked, I want to update my answer and see if I can trigger click on input[type="file"] when you press enter.

jcubic
  • 61,973
  • 54
  • 229
  • 402

1 Answers1

3

If you want the handler to trigger only when the link is focused, add the listener to element itself.

To have a more consistent keyboard event handling, listen for keydown instead of keypress which has been deprecated.

To intercept enter's default action of opening the link, use event.preventDefault()

Lastly, avoid charcodes or keycodes, use key instead which is more consistent across different keyboard layouts.

link.addEventListener('keydown', (e) => {
  const { key } = e
  console.log(key);
  if (key === 'Enter') {
    e.preventDefault();
    alert('You just tried opening Google');
  }
});
<a id="link" href="https://www.google.com">Google</a>
Brother58697
  • 2,290
  • 2
  • 4
  • 12
  • Oh wow, didn't know that keypress was deprecated. – jcubic Dec 29 '22 at 18:39
  • @jcubic You can use a delegated event as well, only that the link needs `tabindex` being set. When delegating, target check is more likely needed, depending on the other content of the page. – Teemu Dec 29 '22 at 18:41