0

In jQuery, we can use 'window.onkeydown' to trigger action when a key is pressed. But 'onkeydown' will 'continuously' execute the function that we have assigned for the trigger. Is there a way that we can execute the assigned function only one time? Thank you!

On key down is specially annoying when I do something like:

window.onkeydown = function(e){
  if (e.keyCode == 17){
    jQuery('<h2/>').appendTo($('#myDiv'))
  }
}

In this case, as long as I hold down the Ctrl key (keyCode 17), jQuery will continuously create h2 elements inside the #myDiv, and the result I want is just 1 h2 is created.

Lan Mai
  • 365
  • 1
  • 5
  • 18

1 Answers1

1

You could perhaps use jQuery one() to have the event execute once and only once. The event is unbound after it occurs:

The .one() method is identical to .on(), except that the handler for a given element and event type is unbound after its first invocation.

jQuery(window).one('keydown', function(e) {
    if (e.keyCode == 17){
        jQuery('<h2/>').appendTo($('#myDiv'))
      }
});

If you need the event to continue to be bound after it executes, you'd probably instead need to look at something like debounce to limit executions.

Community
  • 1
  • 1
Alexander Staroselsky
  • 37,209
  • 15
  • 79
  • 91
  • Hi, I did solve the problem with another path. But thank you very much for your answer. Have a good day :) – Lan Mai Feb 07 '17 at 17:17