views:

364

answers:

3

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.

A: 

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.

Josh Close
A: 

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:

  1. assign keydown event handler
  2. assign keyup event handler
  3. on keydown, remove the keydown event handler and start your robot
  4. on keyup, re-assign the keydown event handler
smencer
As you can see from the edit the problem is actually that the events just cycle continually. Very shortly after keydown is fired keyup fires even though the physical key is being held down.
Rammay
Are you using any sort of library (dojo, jQuery, etc) to handle these events? Could you share your code?
smencer
+2  A: 

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)
 }
}
kennebec