Hack 95 Give the Flash SWF Keyboard Focus

figs/beginner.gif figs/hack95.gif

Flash can't detect keystrokes or accept text input unless the SWF has keyboard focus. Force keyboard focus onto your Flash SWF without requiring the user to click manually.

The browser does not give your SWF browser focus until you select the SWF, usually by clicking on it.

This means that your SWF cannot respond to keypresses until it has been clicked on at least once, something that can be undesirable in a number of situations. For example, you may have just loaded a video game in which the player must take control using the arrow keys. Unless the user is made to click on the SWF before the game commences, the arrow keypresses are not detected. The usual workaround is to force the user to click once on the SWF, usually by clicking a Start button put there solely for this purpose. It is better to have a large clickable area and text instructions such as "Click anywhere to proceed," but it is even more elegant to not require the user to click at all.

Fortunately, you can force browser focus from within Flash using the following ActionScript (it works best when tested in a browser, rather than from Test Movie mode within the Flash authoring application):

getURL("javascript:me.focus( );void 0;");

Using getURL( ), the line invokes the JavaScript Window.focus( ) method, targeting a file called me. As long as your SWF is called me.swf, it will gain focus automatically.

Final Thoughts

Although this is a very short hack, it's one of those little touches that makes your Flash presentation's look and feel much more professional. Users expect to be able to fill in and tab between the text fields in a pop-up form without first having to click on it. If keypresses don't register, users get confused. As with the preceding hack, this technique doesn't work in browsers that don't support JavaScript-to-Flash communication, such as Mozilla.