Tuesday, October 18, 2011

Focus Flex App on start up


When a flex application loads it doesn't actually have focus until the user clicks on it.

So even though you can call setFocus() on a TextInput or Button and visually it appears that your control has focus (blue border), if you try to type you'll notice that nothing happens. This can be quite frustrating for a user.

One way to solve this is to edit the html file that loads your application (e.g. the index.template.html), and call the JavaScript focus() function on the flash element. I found this website explains it quite nicely:
http://www.appfoundation.com/blogs/giametta/2007/07/09/internet-explorer-setting-focus-on-flex-apps-flash-player/.

If for prefer to keep all your code in ActionScript you can accomplish the same thing by doing this:
 ExternalInterface.call("function() { var app = document.getElementById('"+id+"'); app.tabIndex = 0; app.focus(); }");

I usually put that line of code inside my applicationComplete event handler.

One other thing to note is that if you call setFocus on a component that isn't finished being initialized it won't always work. For best results call setFocus() in a creationComplete event handler.

I added the app.tabIndex = 0 after finding that the focus didn't work on Safari. This came from stackoverflow.

13 comments:

Anonymous said...

Thanks, it works on FF 5 and IE9 but not in Chrome 14... :(

Chris Callendar said...

Interesting. It does work for me in Chrome 14 (Mac). Not sure if that's the difference.

Chris Callendar said...

Have you tried this solution (the one with the most up votes)?
http://stackoverflow.com/questions/594821/object-focus-problem-with-safari-and-chrome-browsers.

Try setting the tabIndex property. That worked for me on Safari at least.

App Development Company said...

It is very important for me, thank you so much for sharing this blog.

Fernand Feukeu said...
This comment has been removed by the author.
TheNoax-IT said...
This comment has been removed by a blog administrator.
Unknown said...
This comment has been removed by a blog administrator.
Julie taylor said...
This comment has been removed by a blog administrator.
Suruchi Pandey said...
This comment has been removed by a blog administrator.
Anonymous said...
This comment has been removed by a blog administrator.
Anonymous said...
This comment has been removed by the author.
rajesh said...
This comment has been removed by a blog administrator.
rajesh said...
This comment has been removed by a blog administrator.