Bind enter key to specific button on page

Viewed 48520
<input type="button" id="save_post" class="button" value="Post" style="cursor:pointer;"/>

How can I bind the enter key on the persons keyboard to this specific button on the page? It's not in a form, and nor do I want it to be.

Thanks!

5 Answers

Vanilla JS version with listener:

window.addEventListener('keyup', function(event) {
  if (event.keyCode === 13) {
    alert('enter was pressed!');
  }
});

Also don't forget to remove event listener, if this code is shared between the pages.

Maybe not quite what you're looking for but there is a HTML property that lets you assign a specific button called an access key to focus or trigger an element. It's like this:

<a href='https://www.google.com' accesskey='h'>

This can be done with most elements.

Here's the catch: it doesn't always work. for IE and chrome, you need to be holding alt as well. On firefox, you need to be holding alt and shift (and control if on mac). For safari, you need to be holding control and alt. On opera 15+ you need alt, before 12.1 you need shift and esc.

Source: W3Schools

Related