jquery - How can I avoid autorepeated keydown events in JavaScript? -
if user holds down key, multiple keydown events fired. usability reasons need use keydown, not keyup, want avoid situation. relevant code following:
$(document).keydown(function(e) { var key = 0; if (e == null) { key = event.keycode;} else { key = e.which;} switch(key) { case config.keys.left: goleft(); break; case config.keys.up: goup(); break; case config.keys.right: goright(); break; case config.keys.down: godown(); break; case config.keys.action: select(); break; } });
so when user holds down down key, example, godown() fired multiple times. fire once if user holds key down.
use event.repeat
detect whether or not event repeating. wait "keyup" before allowing handler execute second time.
var allowed = true; $(document).keydown(function(event) { if (event.repeat != undefined) { allowed = !event.repeat; } if (!allowed) return; allowed = false; //... }); $(document).keyup(function(e) { allowed = true; }); $(document).focus(function(e) { allowed = true; });
Comments
Post a Comment