Adding Scripts to Frames

Flash documents are fundamentally structured around the concept of animation. Every Flash document comprises a linear sequence of frames, or slices of visual and audio content. A great deal of ActionScript code is tied to this frame-based structure. By placing a code block on a frame, we stipulate the timing of that block’s execution relative to the playback of the movie. Whenever we add code to a frame, we must always consider not only what we want the code to do, but when we want the code to execute.

For example, we may want to write some code that places a new movie clip on stage when the 20th frame of a movie is displayed:

_root.attachMovie("myClip", "clip1", 0);

In order for that code to execute when the 20th frame is displayed, we must attach it to a keyframe at frame 20 of the movie. To attach code to a keyframe, we select the keyframe in the timeline, open the Actions panel, and then add the desired code to the Script pane. During playback, code on a keyframe is executed before the content of the frame is displayed.

Code on keyframes is used to perform tasks synchronized to the movie’s playback and to establish program elements such as variables, functions, and objects for use throughout a movie clip or movie. A timeline loop is a simple example of a synchronized task. Suppose we attach the following code to frame 15 of a movie:

gotoAndPlay(10);

When the playhead of the movie reaches frame 15, the code executes and the movie begins playing back at frame ...

Get ActionScript: The Definitive Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.