Home > Net >  How to intercept enter key on a link in JavaScript?
How to intercept enter key on a link in JavaScript?

Time:12-30

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.

CodePudding user response:

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>

  • Related