Getting Help for Events and Event Listeners

Now that the Flash document is ready to go, it's time to write and register an event listener, but where do you start? Computers are fussy beasts and won't work properly unless everything is done their way. ActionScript is the same. Event handling uses specific words, punctuation, and even capitalization. Everything has to be just so, or your event will be a nonevent. For beginner ActionScript coders, one of the challenges is learning the right words to use to define and register particular events. This section explains what questions you need to ask as you're coding and where to find the answers.

The first question to ask is this: What type of event is going to serve as the trigger to set your actions in motion? In this case, the event is the movement of the mouse over an object named mcCircle, so this is a mouse-related event. With that bit of knowledge, you can consult ActionScript reference tools that list different types of events. You're looking for one that sounds like it deals with mouse events.

The best reference tool that's close at hand while you're ActionScripting is the ActionScript 3.0 and Components reference. Open it through the help menu: Help→Flash Help. Flash opens the help pages in the Adobe Help window, which works like a web browser, with Forward and Back buttons and such. When you first fire it up, the window lists several help systems you can use. In this case, click the link ActionScript 3.0 and Components.

This electronic reference book provides details on every object, function, and element of ActionScript. Click the names on the left to open up descriptions and examples in the main window. Events are in the list of "packages" in the upper-left corner. The packages that begin with "fl." are related to Flash components, video, multi-language tools, motion classes, tweens, and transitions. Some of these you can't use unless you've added the related components to your Flash document. The packages that begin with "flash." are built into Flash Player and work in any Flash document.

Scroll down and click "flash.events." The main window fills with classes and descriptions. Under the heading Classes, you see all the different types of event classes. Some may seem a little mysterious, like AsyncErrorEvent. But other names—like KeyboardEvent and MouseEvent—sound more helpful. One click on MouseEvent, and your journey is over. The window fills with all the programmer's details you need to handle a MouseEvent, like the public constants that Mouse Events use (see the box on Mouse Events: Public Constants).

Tip

It's kind of a lengthy trip to hunt down the help details on a specific event type, but it's worth remembering. If you end up writing a lot of event listeners, you'll probably remember the details for the events you use all the time. Occasionally, though, you'll need to look up the details for some oddball and unfamiliar event type. So leave some breadcrumbs (or fold down the corner of this page) to remind yourself how to look up events in the ActionScript 3.0 Language and Components Reference.

The reason for mucking through all this programming gobbledegook is about to become apparent. Scroll down and look at the items under Public Constants. These are the names of the actual events that MouseEvent can recognize: CLICK, DOUBLE_CLICK, and so on, including MOUSE_OUT and MOUSE_OVER—the two events you need for your script. Each event type (MouseEvent, KeyboardEvent, ErrorEvent) has related constants that you use when you create event listeners. You have to type these constants exactly as they're defined (including capital letters, underscores, and so on) for your event listener to work. In addition to the constants, the events have properties you can use in your programs. For example, MouseEvent has properties called altKey, ctrlKey, and shiftKey. These are Booleans, and they can tell you whether a particular key is being pressed during a mouse event. You can use them to define, say, a special action for Shift-click and a different one for Alt-click.

Tip

You can ignore the items with the red triangles next to their names unless you're planning on doing some AIR (Adobe Integrated Runtime) programming. The triangles indicate that these classes, properties, and methods are available only in AIR. For more details on AIR projects, see Chapter 21 (Meet Adobe AIR).

So, you know you want to listen for a mouse event; specifically, you want to trigger some actions when the mouse is over the mcCircle movie clip. That makes mcCircle the event target, because it's the object where the event takes place. As described earlier and as shown in Figure 13-1, the event target creates an event object, and then sends it to an event listener. The event object delivers information about the event that happened. Often, all that's necessary is notification that the event took place. As programmer, it's your job to tell the event target the name of the event that serves as a trigger and where to deliver the event object. This process is called registering an event, and it's done with a line of code like this:

mcCircle.addEventListener(MouseEvent.MOUSE_OVER, mouseOverListener);

In ActionScript-speak, this statement "registers an event listener." Almost all events use a similar method to register event listeners, so it's worthwhile to examine the statement completely. The first chunk of code, mcCircle.addEventListener, is nearly recognizable. The dot syntax indicates that mcCircle is an object, and that makes addEventListener either a property or a method of the object. The action verb "add" in the name hints that it's a method, because methods are actions, while properties are characteristics. In fact, addEventListener is a method that's included with just about every object in Flash. That means you can use nearly any object to register an event listener. The details in the parentheses are the parameters for the method.

The first parameter is the event the listener is listening for. In this case, it's a MouseEvent, and the specific type of event is named by the constant MOUSE_OVER. As you know from your extensive research in the Flash help files, those capital-lettered constants are the specific triggers for a MouseEvent. A comma separates the parameters of the method. In this statement, there are two parameters. The second parameter, mouseOverListener, is the name of the event listener. An event listener is simply a function—a series of statements or actions—that run when the event happens. You get to name (and write all the code for) the event listener. It's helpful to use a name that shows that this is an event listener and that describes the event that triggers the actions; hence the name "mouseOverListener."

The event listener is a function, much like the functions described on Functions and Methods Put the Action in ActionScript. The most significant detail is that the function has to list the event object in its parameters. You can think of the event object as the message sent from the event target to the event listener. Here's the code for mouseOverListener:

function mouseOverListener (evt:MouseEvent):void
{
  mcText.gotoAndStop("over");
}

The first line begins with the keyword function, indicating that what follows defines a function—a list of actions. Next comes the name of the function: mouseOverListener. The function's parameter is the event object; in this case, the event object's name is evt. That's followed by a colon (:) and the object class MouseEvent. The name doesn't matter—it can be evt, e, or george. As always, it's helpful to choose a name that means something to you now and will still make sense 5 years from now when you're trying to remember how the code works. You do have to accurately define the class or type of event, which in this case is MouseEvent. The term :void indicates that this function doesn't return a value. If you need to brush up on how to build a function, see Functions and Methods Put the Action in ActionScript.

Once the curly brackets begin, you know that they contain the list of statements or actions that the function performs. In this case, there's simply one line that tells the movie clip mcText to go to the frame labeled "over" and stop there. All in all, here's the complete code so far, with accompanying line numbers:

1  mcCircle.addEventListener(MouseEvent.MOUSE_OVER, mouseOverListener);
2
3  function mouseOverListener (evt:MouseEvent):void
4  {
5   mcText.gotoAndStop("over");
6  }

What you have at this point is one complete and registered event listener. Line 1 identifies mcCircle as the event target for a MOUSE_OVER event. It also registers the event listener as mouseOverListener. Beginning on Line 3, you have the code for mouseOverListener. Any actions you place between those curly brackets will happen when the mouse cursor is over mcCircle.

You can go ahead and test your movie if you want, but it's not going to behave all that well. It needs a few more lines of code to make it presentable. If you test your movie at this point, you'll see a lot of movie clip flickering. If you mouse over the circle, the flickering stops and the text changes to "mouse over." That much works well. When you move the mouse out of the circle…nothing happens. The text still reads "mouse over." That's because you haven't written the mouse-out event. Fortunately, it's very similar to the mouse-over code. In fact, all you have to do is copy and paste the mouse-over code, and then make changes where needed, as shown in bold text in this example:

7
8    mcCircle.addEventListener(MouseEvent.MOUSE_OUT, mouseOutListener);
9
10     function mouseOutListener (evt:MouseEvent):void
11  {
12     mcText.gotoAndStop("out");
13  }

By now, you should be able to read and understand most of the code. Like the first example, the event is registered using the mcCircle object. The event in this case is MOUSE_OUT, and the event listener is named accordingly: mouseOutListener. The action part of the event listener sends the timeline playhead to the frame labeled "out," which displays the text "mouse out"—back where it was when the program started. Perfect.

Well, almost perfect. If you test the movie now, you'll find that it behaves well when you mouse over the circle and when you mouse out of the circle. At the beginning though, there's still a bunch of movie clip flickering, unless the mouse starts off over the circle. Time for a little Flash troubleshooting. Unless they're told otherwise, movie clips play one frame, and then the next, and so on, until they reach the last frame, and then they play over again. And again. And again. Your main movie has only one frame, so it's not causing the flickering. mcCircle only has one frame, so it's not causing the flickering either. The mcText clip has two frames, and those are the ones doing the dance when you start your animation. You need a line of code that stops the movie clip on Frame 1. Then it will be up to the mouse events to control which frame is shown. All you need is one line that says:

mcText.gotoAndStop(1);

The method gotoAndStop() is part of every movie clip. This bit of code tells mcText to go to Frame 1 and stop. The parameter inside the parentheses has to refer to a specific frame. You can do that with a frame number, as shown here, or you can do it with a frame label as you did in your event listeners. If you're wondering how you can find out about the properties and methods for particular classes and objects, see the box on this page.

As a statement on the first frame of your main movie clip, mcText.gotoAndStop(1) runs when the animation begins. It doesn't really matter whether it comes before or after the other lines of code. Those other bits of code don't do anything until an event happens. Not so with the statement above. There's nothing to prevent it from running as soon as Frame 1 of the main movie clip loads.

In ActionScript programming, the order in which different functions and statements appear isn't always important. It doesn't matter which event listener appears first in your code. The order in which the event listeners run is determined by the order in which someone mouses over or out of mcCircle. So whenever possible, you may as well arrange your code so it's easy to read and understand. In this case, it's probably best to register all your event listeners in the same spot, and then put the event listener functions together. You may also want to put the code that isn't dependent on a listener at the very top. So here, with a little rearranging for readability, is the code up to this point:

1
2   mcText.gotoAndStop(1);
3
4   mcCircle.addEventListener(MouseEvent.MOUSE_OVER, mouseOverListener);
5   mcCircle.addEventListener(MouseEvent.MOUSE_OUT, mouseOutListener);
6
7   function mouseOverListener(evt:MouseEvent):void
8   {
9    mcText.gotoAndStop("over");
10  }
11
12  function mouseOutListener(evt:MouseEvent):void
13  {
14    mcText.gotoAndStop("out");
15  }

Line 1 stops mcText in its tracks before it has a chance to start flickering between its two frames. Lines 3 and 4 register event listeners. Beginning on line 6 are the functions that make up the event listeners. At this point, you can test your program, and it should behave pretty well. If something unexpected happens, double-check your spelling and make sure you have semicolons at the end of the statements.

So far in this example you've seen how an event listener attached to one object (mcCircle) can effect a change in another object (mcText). A single event listener can change any number of objects, including the object that registers the listener. After all, any statements you put between the curly brackets of an event listener will run when the event happens.

So, the next steps change the mcCircle object to give it a rollover-style behavior. Once you make these changes, both the text and the circle will change in response to MOUSE_OVER and MOUSE_OUT events. Before you can indulge in ActionScript programming fun, you need to create a new keyframe in the mcCircle movie clip with a different image. Then you get to add statements to the two event listeners, mouseOverListener and mouseOutListener, to describe the actions.

Here are the steps to set up mcCircle's timeline:

In your ActionScript, you need to add the lines that control the behavior of the mcCircle movie clip. They're all of the gotoAndStop() variety. Start off with a line that stops the movie clip from flickering when the animation begins.

mcCircle.gotoAndStop(1);

Then, between the curly brackets of mouseOverListener, add code to change the circle to a star when a MOUSE_OVER event happens.

mcCircle.gotoAndStop("over");

Last but not least, between the curly brackets of the mouseOutListener, add code to change the star back to a circle when the mouse moves away from mcCircle.

mcCircle.gotoAndStop("out");

When you're done, the complete code should look like this:

1   mcText.gotoAndStop(1);
2   mcCircle.gotoAndStop(1);
3
4   mcCircle.addEventListener(MouseEvent.MOUSE_OVER, mouseOverListener);
5   mcCircle.addEventListener(MouseEvent.MOUSE_OUT, mouseOutListener);
6
7   function mouseOverListener(evt:MouseEvent):void
8   {
9     mcText.gotoAndStop("over");
10    mcCircle.gotoAndStop("over");
11  }
12
13  function mouseOutListener(evt:MouseEvent):void
14  {
15    mcText.gotoAndStop("out");
16    mcCircle.gotoAndStop("out");
17  }

Now is a good time to test your movie. If everything runs as it should, you enjoy a high-quality mouse-over and mouse-out experience. Both the graphics and the text change with the mouse events. On the other hand, if you're getting somewhat different results, you may want to download 13-2_Mouse_Event_done.fla from the Missing CD page at www.missingmanuals.com/cds to look for places where your code doesn't match the downloaded file.

As it stands now, your mouse event project isn't the flashiest thing on the block (pun intended). Still, it's worth considering how you can take the same rollover style behaviors and create larger, more impressive projects. For example, using the same mouse events, it would be easy to create a photo gallery that has half a dozen or more photo thumbnails and one large "feature" image, like the one in Figure 13-4. When the mouse moves over one of the thumbnails, the thumbnail changes to display a highlight, and the feature image changes to match the thumbnail. You can even add a text caption that changes for each picture. Once you've created one photo gallery, it's easy to reuse your code by simply swapping in new photos. The variations are limited only by your time and imagination. For example, the photo gallery animation mentioned in Chapter 7 (7-5_Photo_Gallery.fla), uses mouse-click events. When a thumbnail is clicked, the playhead moves to a different point on the timeline, where a tween shows the photo move in 3-D space and fill the stage. Another click, and it shrinks back to size.