Creating Event Handlers

To create an event handler, we define the handler and attach it to the appropriate object. We’ll begin with the most common handlers—those attached to buttons and movie clips.

Attaching Event Handlers to Buttons and Movie Clips

To attach an event handler to a button or a movie clip, we must physically place the code of the handler function onto the desired button or clip. We may do so only in the Flash authoring tool, by selecting the object on stage and entering the appropriate code in the Actions panel, shown in Figure 10.1.

Attaching an event handler to a button

Figure 10-1. Attaching an event handler to a button

Let’s try making a simple event handler function for both a button and a movie clip. To create a button event handler, follow these instructions:

  1. Start a new Flash movie.

  2. Create a button and drag an instance of it onto the main Stage.

  3. With the button selected, type the following code in the Actions panel:

    on (release) {
      trace("You clicked the button");
    }
  4. Select Control Test Movie.

  5. Click the button. The message, “You clicked the button,” appears in the Output window.

When the movie plays and we press and release the button, the release event is detected by the interpreter and it executes the on (release) event handler. Each time that we press and release the button, the message, “You clicked the button,” appears in the Output window.

Now let’s try making a slightly more interesting event handler ...

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.