Setting Focus in Flex Components

While Flex framework supports working with focus, you need to help it a little bit in some scenarios. For example, if your application starts with a Login view it would be nice if the cursor would be automatically placed in the user ID field so the user can immediately start typing. Calling the function setFocus() on the TextInput will show a blinking cursor, but the this field doesn’t respond to the keyboard until the user clicks inside the TextInput.

This has to do with fact that the SWF embedded in the HTML Wrapper doesn’t have the focus yet. So you need to ask the wrapper to give the focus to your SWF.

  

<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
         xmlns:s="library://ns.adobe.com/flex/spark"
         applicationComplete="giveFocus2SWF()"
         >
  <fx:Declarations>
    <fx:String id="activateJS">
      <![CDATA[
        try { 
          var el = document.getElementById("%objectID%")
          el.tabIndex = 0;
          el.focus(); 
        } catch (ex) {
          alert(ex);
        }
      ]]>
    </fx:String>
  </fx:Declarations>
  <fx:Script>
    <![CDATA[
      import flash.utils.setTimeout;
      private function giveFocus2SWF():void {
        if (ExternalInterface.available) {
          ExternalInterface.call(
            "eval",
            activateJS.replace("%objectID%", ExternalInterface.objectID)
          );
        } 
        userID.setFocus();        
        
      }
    ]]>
  </fx:Script>
...

As soon as you leave Flash Player, you run into Web browser compatibility issues. The code above works fine with IE, Firefox and Opera. In order to make it work with Chrome you must define wmode=”opaque” to SWFObject parameters (in HTML template).

It doesn’t work with Safari as of yet, and I’ll update this post as soon as I find the solution.

Valery Silaev

One thought on “Setting Focus in Flex Components

  1. The ExternalInterface.objectID was null in my case. As for the rest this works like a charm. Thanks a lot!

Comments are closed.