How to setFocus() when your app loads

If your flex app begins with a login screen, you'll most likely want the cursor to default to the username text field. But if you simply call setFocus() on that text field when the application's creationComplete event fires, it won't work.  There is another step that you have to take.  You have to add some JavaScript to the HTML page that houses your swf.  In order for your text field to gain focus, and show the blinking cursor, your .swf has to first gain focus within the HTML page.

 

You can add the following JavaScript function to the HTML page:

 

function setFocus(){
    setTimeout("document.getElementById('YouAppsNameGoesHere').focus()",1);
}

 

Your app's name should be the same name as your Flex project name.  If you look inside the HTML wrapper that Flex creates when your app is compiled, you should see that the ID attribute of the OBJECT tag is the name of your Flex project.  This is the ID that the JavaScript code is referring to.  You might also wonder why I've used setTimeout(), rather than simply using document.getElementById().focus().  This is because FireFox, for some reason, requires the setTimeout().

 

Don't forget to call this function in the onload event of the body tag!


RECENT ARTICLES