slandau
slandau

Reputation: 24082

Bind enter key to specific button on page

<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!

Upvotes: 37

Views: 55529

Answers (5)

Josh
Josh

Reputation: 77

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

Upvotes: 0

Alexander Kim
Alexander Kim

Reputation: 18401

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.

Upvotes: 3

Abhishek Hingorani
Abhishek Hingorani

Reputation: 451

If you want to use pure javascript :

document.onkeydown = function (e) {
  e = e || window.event;
  switch (e.which || e.keyCode) {
        case 13 : //Your Code Here (13 is ascii code for 'ENTER')
            break;
  }
}

Upvotes: 24

Parham
Parham

Reputation: 1067

using jQuery :

$('body').on('keypress', 'input', function(args) {
    if (args.keyCode == 13) {
        $("#save_post").click();
        return false;
    }
});

Or to bind specific inputs to different buttons you can use selectors

$('body').on('keypress', '#MyInputId', function(args) {
    if (args.keyCode == 13) {
        $('#MyButtonId').click();
        return false;
    }
});

Upvotes: 12

Chris Laplante
Chris Laplante

Reputation: 29668

This will click the button regardless of where the "Enter" happens on the page:

$(document).keypress(function(e){
    if (e.which == 13){
        $("#save_post").click();
    }
});

Upvotes: 50

Related Questions