DekGenius.com
[ Team LiB ] Previous Section Next Section

Recipe 7.2 Targeting Movie Clips with Dynamic Names

7.2.1 Problem

You want to target a movie clip in which the clip's name is generated dynamically.

7.2.2 Solution

Use array-access notation (square brackets) and string concatenation (the + operator).

7.2.3 Discussion

If you know a movie clip's name, you can target it using standard dot notation:

// Target a movie clip named myMovieClipA that is within a clip named holderClip that
// is, in turn, within _root.
_root.holderClip.myMovieClipA._x = 25;

However, the situation is a little different when the movie clip's name (or any part of the path) is not explicitly known. For example, if you have the movie clip's name stored in a variable, you may make the common mistake of trying to use the variable name within the target path:

// This will not work! It will look for a movie clip named "myVar" instead of a movie
// clip with the same name as the value of myVar.
_root.holderClip.myVar._x = 25;    // Wrong!

Instead, you should use array-access notation. All objects, including movie clips, can be treated as associative arrays. This means that you can access any element of a movie clip—even a nested movie clip—using the array-access operator ([]). Note that while standard dot notation expects a movie clip reference, array-access notation expects a string or a variable that contains a string value:

// This works! It evaluates myVar through the use of array-access notation. It
// targets the clip within holderClip that has the same name as the value of myVar.
_root.holderClip[myVar]._x = 25;

Another common mistake when using array-access notation is to accidentally use a dot before the array-access operator:

// This will not work! There should not be a dot between holderClip and the 
// array-access operator.
_root.holderClip.[myVar]._x = 25;   // Wrong!

Using array-access notation is extremely beneficial when you have sequentially named movie clips that you want to target:

// These few lines of code can set the _visible property to false for 50 movie clips
// named myMovieClip0 thru myMovieClip49.
for (var i = 0; i < 50; i++) {
  _root["myMovieClip" + i]._visible = false;
}

7.2.4 See Also

Recipe 7.1

    [ Team LiB ] Previous Section Next Section