Cursor Position / Field Focus upon startup in Flex

Flex - Tips and Tricks

If you would like to have your Flex application automatically position on a specific field when your application opens you will need to do two things. First, you need to modify the HTML template that presents your application and second, set the focus within the Flex application itself.

Inside your Flex application you will find a directory called "html-template". Under this directory open the file named "index.template.html". Find the line

<body scroll="no">

and modify it to

<body scroll="no" onLoad="window.document.${application}.focus()" >

In your application you will need to have a function that is called once your application is loaded. In this case we have a function called "init" that is called when the application is completely loaded.

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" applicationComplete="init();" viewSourceURL="srcview/index.html">

The "init" function in the script code includes the setFocus operation on the field that I need the user to be first positioned in.

private function init():void{
searchField.setFocus();
someService.invoke();
}

Once the html template and initial function is changed, your user will be positioned in the field where we've performed the ".setFocus()". Very useful for usernames for a login screen where we don't want the user to have to use their mouse to click in the field first. A good UI should ensure that the user goes to the page, enters their username, presses tab, then enter and the mouse is not required at all.