340 Handling Events
Specifying events for on or onClipEvent methods
To use an on() or onClipEvent() handler, attach it directly to an instance of a button or
movie clip on the Stage and specify the event you want to handle for that instance. For a
complete list of events supported by the
on() and onClipEvent() event handlers, see on
handler
and onClipEvent handler in the ActionScript 2.0 Language Reference.
For example, the following
on() event handler executes whenever the user clicks the button to
which the handler is attached:
on (press) {
trace("Thanks for pressing me.");
}
You can specify two or more events for each on() handler, separated by commas. The
ActionScript in a handler executes when either of the events specified by the handler occurs.
For example, the following
on() handler attached to a button executes whenever the mouse
rolls over and then off the button:
on (rollOver, rollOut) {
trace("You rolled over, or rolled out");
}
You can also add key press events using on() handlers. For example, the following code traces
a string when you press the number 3 on the keyboard. Select a button or movie clip instance,
and add the following code to the Actions panel:
on (keyPress "3") {
trace("You pressed 3")
}
Or, if you want to trace when the Enter key is pressed by a user, you could use the following
code format. Select a button or movie clip instance, and add the following code to the Actions
panel:
on (keyPress "<Enter>") {
trace("Enter Pressed");
}
Select Control > Test Movie, and press the Enter key to see the string trace to the Output
panel. If nothing traces, select Control > Disable Keyboard Shortcuts and try again. For more
information on adding keypress interactivity to your applications, see
Key.
NOTE
Attaching onClipEvent() and on() handlers is not a recommended practice. Instead, you
should put your code in frame scripts or in a class file, as demonstrated throughout this
manual. For more information, see “Using event handler methods” on page 330 and
“Attaching code to objects” on page 746.