setFocus() Explained!

Ok, I recently just needed to use setFocus() and I searched the forums and was confused as 90% of the people posting were as to why it wasn’t working.

Here are some tips, guidelines and do’s and donts to ensure your setFocus will work smoothly.

** Usage **


// returns currently focused instancename:String
Selection.getFocus();
// returns true or false if setFocus was successfull
Selection.setFocus(instancename:String);

The help documents state for instancename:String the following.

You can use a relative or absolute path.

This is incorrect to my tests, I tried using relative pathing such as “containerMc.textInstanceName” it simply would not work.

Selection is a _root function, it’s going to try and basically do

Selection.setfocus(_root.instancename)

Hence if you used a relative pathing from a class/movieclip it will not work.

Workaround #1)
you can always use direct pathing using _root

Selection.setFocus("_root.mc1.mc2.textInstanceName");

This works great if you are not loading swfs with form fields. However, like always _root is very very bad to use if you’re loading the swf into another one because the _root will go to the parent swf’s _root and mess things up. So the next question is, how do we get a relative path to a absolute path?

Workaround #2)
Below is an actionscript snippet that will get the current dot notation root path and set the focus.

Selection.setFocus(targetPath(this)+".instanceName");

Make sure you put a . before putting the instance name, the instance name should be a path with dot notation so if you’re text field is inside a movie clip it should be “.mcinstancename.textfieldinstancename”

Feel free to ask questions you have regarding this matter, hope this will help everyone understand this “setFocus()” a bit better.

Edit, I forgot F.A.Q.

Q: The setFocus is tracing back as true but it’s still not focusing the text field what gives?
**A: Check to make sure the setFocus was the very last action called to after any button presses or what not. If you setFocus then the user cicks a button the button will take focus over. To help debug try putting a

instanceName.onKillFocus = function() {
     trace(Selection.getFocus());
     trace(_name+" :: Lost Focus");
}

It will trace what object and it’s path that took over focus. If you pressed a button sometimes it will retain the focus but not be “focused for text input”. This is a weird bug or just how flash works. To return focus at the very last code running on the button actions simply put

Selection.setFocus(Selection.getFocus());

**

Q: Can I use a variable instead of an instance name for a text field?
A: I’ve never used variable names for text fields, I much rather use instanceName for control purposes, if you’re loading vars just run a function to set .text or you can always use different variable names than the instance name