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');   } } 
                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.
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.
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.
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.
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.
You could still use .on()
$(document).off('keyup#textfield');  $(document).on('keyup#textfield', function(event) {     if (event.keyCode == 13) {          console.log('Enter was pressed');     } }); 
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With