views:

920

answers:

3

How do I determine if the delete key was pressed using actionscript?

addEventListener(KeyboardEvent.KEY_UP, onKeyUp);

...

function onKeyUp(event:KeyboardEvent):void
{
    trace(event.keyCode);
}

The above code yields no value when delete, backspace, enter, and other command keys are pressed. However, arrow keys do yield values.

+1  A: 

Just guessing you are using the TEXT_INPUT event, this doesn't work for delete and backspace. To catch those ones you can add an eventListener on the stage and listen to a KeyboardEvent.

Theo.T
No, I'm listening for events on the stage. Code snippet updated to reflect this.
Soviut
You must write stage.addEventListener(KeyboardEvent.KEY_DOWN, eventKeyDown) though (stage.* !) even though you are in the scope of the Document Class. Works for me...
Theo.T
+1  A: 

Code will work fine if the display object that you attached the listener is in focus. For global listening, as Theo said, you have to attach the listener to the stage. Accessing stage from an object that's not yet added to the display list will result in null error. Do it in the ADDED_TO_STAGE event handler to be safe.

Amarghosh
So what was the issue Soviut ? Just curious ...
Theo.T
+2  A: 
this.stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyPressed);
....

function onKeyPressed(event:KeyboardEvent):void
{
   if (event.keyCode==Keyboard.DELETE) {
       .....
       }

}

it's workin nice... But if you test movie from Flash, it will not work, so export to swf and test....

Armen Mkrtchyan
Interesting. I guess because the simulator is running inside the FLash IDE, the IDE itself is intercepting delete commands.
Soviut