Home > ActionScript 3, Flex > Setting TextInput Focus on Load

Setting TextInput Focus on Load

For those who have tried, you’ve probably noticed that your Flex applications can set focus on TextInput elements when it loads. The reason behind this is that the Flash player doesn’t get focus unless you click on it or tell it to get focus from JavaScript. There is a solution that seems to work well with most browsers for getting focus on the Flash player:

function getFlashMovieObject(movieName) {
    if (window.document[movieName]) {
        return window.document[movieName];
    }

    if (navigator.appName.indexOf("Microsoft Internet")==-1) {
        if (document.embeds && document.embeds[movieName]) {
            return document.embeds[movieName];
        }
    } else {
        return document.getElementById(movieName);
    }
}

function setBrowserFocus() {
    getFlashMovieObject('${application}').focus();
}

You must also add the onload attribute to the body so it will call the setBrowserFocus method like this:

<body onload="setBrowserFocus()">

Once you’ve done this all you have to do is create a handler that will set the focus on a TextInput like so:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application
    xmlns:mx="http://www.adobe.com/2006/mxml"
    layout="absolute"
    creationComplete="creationCompleteHandler()">
    <mx:Script>
        <![CDATA[

            private function creationCompleteHandler():void
            {
                focusManager.setFocus(textInput);
            }

        ]]>
    </mx:Script>
    <mx:TextInput id="textInput" />
</mx:Application>
Categories: ActionScript 3, Flex
  1. No comments yet.
  1. No trackbacks yet.