Publishers of technology books, eBooks, and videos for creative people

Home > Blogs > Flash Animation Five Tips in Five Days: Tip 5 - Targeting Nested Symbols with ActionScript

Flash Animation Five Tips in Five Days: Tip 5 - Targeting Nested Symbols with ActionScript

Suppose you want to use ActionScript to manipulate a symbol that is nested inside another symbol. For example, imagine you have an instance of a symbol named menuHolder on Stage, and inside menuHolder, there is an instance of a symbol named menuItem.


In order to target the menuItem instance with ActionScript, both the menuHolder instance and the menuItem instance must be Movie Clips, and both must have instance names. You can add an instance name by selecting an instance and typing the name into the Instance name field in the Properties panel.


Suppose you've given instance names of menuHolder_mc and menuItem1 to the menuHolder and menuItem instances, respectively. If you have not done so already, you should create a layer named actions on the main Timeline and lock the layer (to prevent artwork from being added to the layer). Select the first frame of the actions layer and open the Actions panel (Window > Actions).

Add the following code to the Actions panel:

menuHolder_mc.menuItem1.addEventListener(MouseEvent.CLICK, onMenuItemClick);

function onMenuItemClick(e:MouseEvent):void {
trace("menuItem clicked");
}

The code above uses a period (.) to access the nested movie clip (this is referred to as "dot syntax"). A mouse event can then be added to menuItem1 to trigger a function.

If you test your movie and click on the menu item, you should see "menuItem clicked" in your Output panel. This indicates that you've successfully referenced the nested instance, and added a CLICK event to that instance.

You can also store the reference to your nested clip using a shorter variable name.

var m1:MovieClip = menuHolder_mc.menuItem1;

m1.addEventListener(MouseEvent.CLICK, onMenuItemClick);
function onMenuItemClick(e:MouseEvent):void {
trace("menuItem clicked");
}

This is especially useful if you need to reference the nested clip several times in your code. Shorter names can yield fewer mistakes and less typing. Nesting is an extremely useful technique to manage your visual assets. Now that you know how to reference your nested symbols with ActionScript, you can nest to your heart's content!

For more tips and step-by-step, illustrated instructions for creating animation in Flash, check out Animation with Scripting in Adobe Flash CS5 Studio Techniques.