Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
177
rated 0 times [  179] [ 2]  / answers: 1 / hits: 31474  / 13 Years ago, fri, october 7, 2011, 12:00:00

If the user holds down the key, multiple keydown events are fired. For usability reasons I need to use keydown, not keyup, but I want to avoid this situation. My relevant code is the 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 the user holds down the down key, for example, goDown() is fired multiple times. I would like it to fire just once even if the user holds the key down.


More From » jquery

 Answers
287

Use event.repeat to detect whether or not the event is repeating. You could then wait for keyup before allowing the handler to execute a 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;
});

[#89742] Wednesday, October 5, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ronniem

Total Points: 584
Total Questions: 111
Total Answers: 111

Location: Finland
Member since Sat, Nov 6, 2021
3 Years ago
ronniem questions
Sat, Apr 24, 21, 00:00, 3 Years ago
Wed, Mar 10, 21, 00:00, 3 Years ago
Sat, Feb 6, 21, 00:00, 3 Years ago
;