Scripting buttons in Flash CS4 (AS3)

Buttons in Flash provide interactivity. To work, a button needs to have (1) a listener, and (2) a function. This is different from previous versions of ActionScript. To those of us who learned an earlier version, the new way can seem unnecessarily complex. However, I've grown used to it now.

Below, a square moves infinitely right and left on the Timeline. One button is scripted to stop the Timeline. The other button is scripted to make the Timeline play.

You need to upgrade your Flash player (v.9 or later) to view this example.

The listener must be on the frame where the button symbol first appears in the Timeline:

stop_btn.addEventListener(MouseEvent.CLICK, stopMove);

The function (which is called by the listener) can appear on the same frame, or on an earlier frame:

function stopMove(e:MouseEvent):void {
stop();
}

Two things that often confuse new Flash coders:

(1) The function's name (in this case, stopMove) must appear in the listener, as shown above. The two must match exactly, including the use of upper- and lowercase letters.

(2) The button on the Stage must be assigned an instance name in the Properties panel. This is not the same as the symbol name, which you can see in the Library. Above, the button's instance name is stop_btn. In the Library, the symbol name of this button is Pushie.

To learn more about the way the listener and the function work together, see Flash Basics: AS3 Buttons.

DOWNLOAD The movie above is buttons.fla (44 KB).

Education use: This package was created as an example for my journalism students. It is not intended to be used commercially.

Use and re-use: How to Script a Button in Flash CS4 (AS3) by Mindy McAdams is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License.
Creative Commons License

Updated 24 April 2010