Using jQuery to listen to keydown event

Don P picture Don P · Feb 17, 2013 · Viewed 90.8k times · Source

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');
  }
}

Answer

Aidan Ewen picture Aidan Ewen · Feb 17, 2013

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.