Javascript / jQuery How to prevent function re-execution when a key is pressed?

Suppose we have the following jQuery code:

$(document).bind('keyup', function(e) {

arrows=((e.which)||(e.keyCode));

switch (arrows){

case 37:

executeMyfunction();

break;

}

});

If the user holds the left arrow key (37), the executeMyfunction () function is called repeatedly.

How can I prevent this?

I thought that keyup only starts if the key is released, but it doesn’t work (that’s why I use keyup, keydown doesn’t work either).

+1
source share
2 answers

I believe you need to untie the event. I think it should not be keyup, but keypress or keydown.

Maybe something like this.

$ (document) .bind ('keydown', function (e) {

= ((e.which) || (e.keyCode));

() {

37:

executeMyfunction();

$().unbind( 'KeyDown');

break;

} });

:

$(document).bind('keyup', function (e) {

() {

37: $ ().bind( 'KeyDown'); break; }

})

: http://api.jquery.com/unbind/

+1

, debounce . , , , .

0

Source: https://habr.com/ru/post/1743683/


All Articles