Reputation: 31
I'm creating a web front end to control a small robot. Ajax calls will be made on a keydown
, to start the robot, and keyup
to stop it.
My problem is that when a key is held down the keyup
, keydown
, and keypress
events seem to cycle continually. Does anybody know of a way to only have keydown
fire when the key is first pressed and keyup
to fire when it has been released?
--edit: I forgot to mention it originally but I have tried saving the state of the button. The problem is that keydown
, keypress
and keyup
events fire over and over again as I am holding the key down.
Upvotes: 3
Views: 2540
Reputation: 104780
I cannot reproduce the problem- I do not find any keyup events thrown from keydown, no matter how long I hold down a key.
This method listens for a keydown, runs some code, and waits for a keyup before listening for another keydown.
The alert is only called on a keyup.
var A=[], who=// I used a textarea, substititute your own target
who.onkeydown= who.onkeyup= function(e){
e=window.event || e;
var t= e.type, target= e.target || e.srcElement;
A.push(t);
if(t== 'keydown'){
// start robot and stop listening to keydown
target.onkeydown= '';
}
else if(t== 'keyup'){
// stop robot and listen for keydown
target.onkeydown= arguments.callee;
alert(A)
}
}
Upvotes: 2
Reputation: 1053
When you start your robot, remove the event handler from the keypress event and add an event handler for the keyup event to stop the robot.
When your keyup event fires, stop the robot and add you keypress handler back.
EDIT: By actually removing the event handler from your keydown event. You'll want to use the keydown and keyup events... not the keypress.
So basically:
Upvotes: 0
Reputation: 23383
You could try saving the state of the key. When the key goes down, check if the key is already pressed, if not, start the robot and mark the key as pressed. If it's already pressed, don't do anything. On key up, do the same thing for stopping the robot and mark the key as not pressed.
Upvotes: 1