42

I want to detect when the enter key is pressed, on HTML that will be injected dynamically.

To simply detect when the enter key is pressed, I can do:

$('#textfield').keydown(function (e){
    if(e.keyCode == 13){
        console.log('Enter was pressed');
    }
})

This code works for on(), but I am worried it is inefficient since jQuery will check every time a key is pressed. Is there anything inefficient about this?

$('body').on('keydown','#textfield', function(event) {
  if (event.keyCode == 13) {
    console.log('Enter was pressed');
  }
}
Axel
  • 3,331
  • 11
  • 35
  • 58
Don P
  • 60,113
  • 114
  • 300
  • 432
  • 4
    No. Literally thousands of things happen when a key is pressed, it'll be like a drop in the ocean. – JJJ Feb 17 '13 at 08:59

3 Answers3

62

If you want to capture the keypress anywhere on the page -

$(document).keypress(function(e) {
  if(e.which == 13) {
    // enter pressed
  }
});

Don't worry about the fact this checks for every keypress, it really isn't putting any significant load on the browser.

Aidan Ewen
  • 13,049
  • 8
  • 63
  • 88
10

You could still use .on()

$(document).off('keyup#textfield');

$(document).on('keyup#textfield', function(event) {
    if (event.keyCode == 13) {
         console.log('Enter was pressed');
    }
});
Gavin Anderegg
  • 6,281
  • 2
  • 25
  • 35
MarvinVK
  • 2,964
  • 1
  • 22
  • 21
1

In practical terms, nothing you have to worry about. The browser is already going to be bubbling that event, and even though it may be trapped by the body and run a selector from the delegated event, this is not a deep or difficult practical check for JQuery to perform, especially with an ID-only selector.

Plynx
  • 11,341
  • 3
  • 32
  • 33
  • Agree. BTW: You don't really have a choice - theres no way to add a listener to key (although it would be nice). – Fabian Lauer Feb 17 '13 at 09:03
  • ...and even if there were a way to add a listener to a single key, internally the browser would *still* have to react to every keypress to determine which key was pressed. – JJJ Feb 17 '13 at 09:20