11

I need to bind the 'enter' key on the keyboard to a specific javascript method, but ONLY when a certain text field is in focus.

<input id="post" type="text" style="width:400px;"/>

How would I do this?

I know you can do it with forms and stuff that have a submit action, but can I just bind the 'enter' key to a specific function when this above input field is in focus?

slandau
  • 23,528
  • 42
  • 122
  • 184

2 Answers2

19
$("#post").focus(function() {
    $(this).data("hasfocus", true);
});

$("#post").blur(function() {
    $(this).data("hasfocus", false);
});

$(document.body).keyup(function(ev) {
    // 13 is ENTER
    if (ev.which === 13 && $("#post").data("hasfocus")) {
        ...
    }
});

I recommend you instead bind the the ENTER keyup event on your $("#post") input directly rather then listening for the event on the entire page.

Raynos
  • 166,823
  • 56
  • 351
  • 396
  • if you're using a function to do something else like I was remember to throw an `e.preventDefault();` in before the function call to prevent the form being submitted. – grepsedawk Mar 25 '14 at 20:01
  • 1
    you recommend to bind it on #post only and then write a code to listen to the whole document? i don't even ... – user151496 Apr 28 '16 at 09:12
15

Just bind the onkeyup event to the input in question. You don't need to worry about checking focus at all, because by definition that input will only receive keyup events when it has focus.

I assume JQuery is OK since you included the tag in your question, so within your document ready handler do something like this:

$("#IDforyourcontrol").keyup(function(ev) {
   // 13 is ENTER
   if (ev.which === 13 && /*whatever other conditions you care about*/) {
      // do something
   }
}); 
nnnnnn
  • 147,572
  • 30
  • 200
  • 241
  • "by definition that input will only receive keyup events when it has focus" is not strictly true. Events can also be dispatched programatcially so an input can receive a keyup event when it isn't in focus (and for many events on other elements there are bubbling and capture phases to consider too). However, adding a keyup listener to the input should be sufficient for the OP's requirements. – RobG May 10 '11 at 01:03
  • OK, sure, I didn't think about events triggered programatically, though it seems unlikely that somebody would want to trigger a keyup for the enter key programmatically and distinguish that from user actions. Still, I think my main point is valid that for this purpose you normally wouldn't need to worry about checking where the focus is. Raynos's answer explains how to allow for focus too, so I guess it answers the OP more completely though I wouldn't bind the event to the document.body (but I for one have never needed to check focus for that type of thing). – nnnnnn May 10 '11 at 01:26
  • good answer, implicit, performant. I use it on the input itself `` and then `myFunction(e) {if (e.which === 13....}` – Asaf David Nov 24 '15 at 08:08