Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jQuery to listen to keydown event

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');   } } 
like image 883
Don P Avatar asked Feb 17 '13 08:02

Don P


People also ask

What is Keydown event in jQuery?

The keydown event occurs when a keyboard key is pressed down. The keydown() method triggers the keydown event, or attaches a function to run when a keydown event occurs. Tip: Use the event. which property to return which keyboard key was pressed.

How do I use Keydown event?

The keydown event is fired when a key is pressed. Unlike the keypress event, the keydown event is fired for all keys, regardless of whether they produce a character value. The keydown and keyup events provide a code indicating which key is pressed, while keypress indicates which character was entered.

How does jQuery detect keyboard press?

jQuery | keypress() The keypress() method in jQuery triggers the keypress event whenever browser registers a keyboard input. So, Using keypress() method it can be detected if any key is pressed or not.

What is Keyup and Keydown in jQuery?

jQuery keyup() Method The order of events related to the keyup event: keydown - The key is on its way down. keypress - The key is pressed down. keyup - The key is released.


2 Answers

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.

like image 127
Aidan Ewen Avatar answered Sep 23 '22 02:09

Aidan Ewen


You could still use .on()

$(document).off('keyup#textfield');  $(document).on('keyup#textfield', function(event) {     if (event.keyCode == 13) {          console.log('Enter was pressed');     } }); 
like image 24
MarvinVK Avatar answered Sep 21 '22 02:09

MarvinVK