Creating a play/pause toggle using the Spacebar in Flex
March 24th, 2008 . by polyGeekI’m creating a Flex based videoPlayer/slideShow viewer for a client. One small usability feature that I wanted to add is making the Spacebar act as a play/pause toggle.
|
Click on any button or the stage to give the SWF focus |
| view source code |
It’s not as straight forward as one might think. First off if you create a Flex application then which ever component has focus receives the keyboard input. Which is really cool unless you don’t want it to do that. And this is the first occasion I’ve had for using applicationComplete() before. Because you have to have access to the application stage in order to set up the keyboard event and that isn’t available on creationComplete() - as noted here at the Flex cookbook.
Here’s the gist of the code:
private function appInit():void {
stage.addEventListener( KeyboardEvent.KEY_DOWN, keyPressHandler );
}
private function keyPressHandler( e:KeyboardEvent ):void {
// if the spaceBar is pressed then toggle video play/pause
if( e.charCode == 32 ) {
if( this.focusManager.getFocus() != toggleBtn ) {
this.focusManager.setFocus( toggleBtn );
// whatever happens when you click on the button you place here
// it's best to have a 'clickHandler' that calls another method
toggleBtnHandler();
}
}
}











