Chapter 15. Understanding Actions and Event Handlers

IN THIS CHAPTER

  • Knowing events and event handlers

  • Adding interactivity with the Code Snippets panel

  • Understanding Flash actions

  • Using the Actions panel with Script Assist

  • Learning your first Flash actions

  • Executing actions with event handlers

  • Using navigateToURL

Interactivity in a Flash movie can broadly be thought of as the elements that react and respond to a user's activity or input. A user has many ways to give input to a Flash movie, and Flash has even more ways to react. But how does interactivity actually work? It all starts with actions and event handlers.

Actions and Event Handlers

Even the most complex interactivity in Flash is fundamentally composed of two basic parts: the behavior (what happens) and the cause of the behavior (what makes it happen). Here's a simple example: Suppose you have a looping soundtrack in a movie and a button that, when clicked, turns the soundtrack off. The behavior is the sound turning off, and the cause of the behavior is the mouse clicking the button. Another example is stopping an animation when it reaches a certain frame on its timeline. When the last keyframe of the animation is played (the cause), an action on that keyframe stops the animation (the behavior). In Flash, the building blocks of behaviors are referred to as actions.

Note

Flash CS5 features an interactive authoring tool called the Behaviors panel. Our usage of the term behaviors in the preceding description should not be confused with this feature. The Behaviors panel can be used only for legacy Flash movies that require ActionScript 2.0. In this edition of the book, I discuss only ActionScript 3.0 code.

The first step in learning how to make interactive movies is becoming familiar with the list of possible actions. However, actions can't act without being told to act by something. That something is often the mouse pointer coming in contact with a button, but it can also be a keystroke, or simply a command issued from a keyframe. I refer to any occurrence that can cause an action to happen (such as the button click in the preceding example) as an event. The mechanism you use to tell Flash what action to perform when an event occurs is known as an event handler. This cause-and-effect relationship seems obvious, but it is an extremely important concept.

For the purposes of creating basic interactivity, the difference between an action and the cause of an action is merely a practical detail. As the set of Flash actions, collectively known as ActionScript, continues to grow with each release of the Flash authoring tool (and, therefore, the interactive capabilities that they provide), understanding the relationship between actions and the things that cause them can be the key to adding more sophisticated behavior to your movies with traditional programming techniques. Every interactive framework, whether it is Adobe Flash or Adobe Director or Apple DVD Studio Pro, has unique handlers for specific events. Table 15.1 relates interactive events with Flash handlers.

Note

Any ActionScript covered in this chapter refers to ActionScript 3.0. For any examples in this chapter, make sure you choose Flash File (ActionScript 3.0) from the splash screen when you create a new file.

Table 15.1. Events and Flash Handlers

Event

Type

Event Handler

Example

Playback

Time-based

Keyframes MovieClip instance NetStream instance

Timeline plays until it reaches a certain frame; a MovieClip instance monitors the amount of time that has passed in a movie; when a video stream stops playing, another stream begins playback.

Mouse

User input

SimpleButton instance MovieClip instance Sprite instance Mouse class

A visitor clicks a button;mouse movement is detected over a MovieClip instance.

Key press

User input

SimpleButton instance MovieClip instance Keyboard class

A user presses the Enter key to submit a form; an alert appears if the Caps Lock key is enabled.

Window resize

User input

Stage class

A user clicks the maximize button on a Flash projector or Web browser window and Flash elements respond accordingly.

Microphone or Webcam activity

Audio/video input

Microphone class Camera class

When a user stops talking into a microphone, a graphic turns red; a stream starts to record audio and video when the movement is detected in front of a Webcam.

Data

System-based

URLLoader instance XML instance

Search results appear in the Flash movie when the results have fully loaded.

Although the breadth and depth of ActionScript involved with the interactions described in Table 15.1 may seem overwhelming, don't worry — we're taking it one step at a time. First, you'll learn how to set up the Actions panel, and then we'll look at actions that control movie playback. Later, you'll also learn how to call these actions in various ways with three kinds of event handlers: button manipulation, keyframes, and keystrokes.

What is ActionScript?

Every interactive authoring system uses a language (or code) that enables elements within the system to communicate. Just as there are several languages that people use to speak to one another around the globe, there are hundreds of programming languages in use today. In an effort to make Flash more useable to computer programmers, Flash's scripting language, called ActionScript, strongly resembles JavaScript, a fundamental element for adding advanced interactivity to HTML pages. Right now, I focus on using the most basic Flash ActionScript.

Note

Since Flash Player 9 and Flash CS3 have been released, you can use a completely revamped version of ActionScript called ActionScript 3.0, or AS3. AS3 is more complex than previous versions but is more maintainable and scalable for Flash projects. ActionScript 3.0 will feel more familiar to developers who have used other object-oriented programming languages such as C++ or Java.

Navigating the Actions panel

Flash CS5 has a specific interface element that enables you to add interactive commands to Flash movies — the Actions panel. You don't use menus or wizards to add interactive functionality — you type the ActionScript code describing the interactivity in (or out of) the Actions panel. You can open the Actions panel in a number of ways:

  • Go to Window

    Navigating the Actions panel
  • Press the F9 key/Option+F9.

  • Click the ActionScript icon button at the top-right corner of the Properties panel.

  • Alt+double-click/Option+double-click a keyframe in the Timeline window.

If you have a keyframe selected in the Timeline window, the Actions panel will be titled Actions – Frame (see Figure 15.1). If you have a Movie Clip symbol instance selected on the Stage, you'll see the name Actions – Movie Clip. If you have a button symbol instance selected on the Stage, the Actions panel will be titled Actions – Button. If you have a component selected, the Actions panel will read Actions – Component. Don't be confused — there is only one Actions panel. Flash CS5 simply lets you know the object to which you are assigning actions.

Tip

The Actions panel in Flash CS5 features a Script Assist mode. Script Assist enables you to code ActionScript by selecting actions and filling in parameters, instead of writing out all the code by hand.

The Actions panel enables you to instantly add, delete, or change Flash movie commands.

Figure 15.1. The Actions panel enables you to instantly add, delete, or change Flash movie commands.

As shown in Figure 15.1, the Actions panel in Flash CS5 has three distinct areas (counterclockwise from the left): the Actions Toolbox, the Script navigator, and the Script pane. The Script Assist area is available within the Script pane. There are two auto-snap dividers, one dividing the Actions toolbox and Script navigator from the Script pane, and another subdividing the Actions Toolbox and Script navigator. You may want to practice opening and closing these dividers, as well as dragging each to your preferred width and height, respectively. Figures 15.1 shows a breakdown of the Actions panel in Flash CS5. The following list details the three areas:

  • The Actions Toolbox contains several nested booklets of ActionScript commands. You can select actions to add to the Script pane. The booklets that appear default to the version of ActionScript that your Flash document specifies in the Flash tab of the Publish Settings dialog box (File

    The Actions panel enables you to instantly add, delete, or change Flash movie commands.

Tip

The Actions Toolbox has a booklet selection drop-down menu. The default set of booklets appearing in the Toolbox pertain to ActionScript 1.0, 2.0, and 3.0, but you can switch to other sets of booklets, including various versions of Flash Lite. Each Flash Lite booklet displays only actions compatible with the Flash Lite players that ship on mobile devices and phones.

  • The Script navigator can jump to any script within your Flash document. When you select a keyframe or object in this pane, any code attached to the item appears in the Script pane.

Tip

The Script navigator shows the actions for the entire document, not just for the current timeline.

  • The Script pane displays the current code for an item selected on the Stage, a keyframe selected in the Timeline window, or an item selected in the Script navigator. You can type, copy, cut, and paste code into the Script pane, as long as you are not working in Script Assist mode. An options bar is located at the top of the Script pane as well. The options bar contains several buttons to modify, search, debug, or format your code in the Script pane. You can also find most of these options in the panel's options menu, located in the top-right corner of the panel.

Tip

You can click the pin icon at the bottom tab of the script in the Script pane. You can pin multiple scripts in the Script pane, and quickly tab between them.

  • The Script Assist area within the Script pane enables you to visualize your code with contextual parameters, such as fill-in text fields or drop-down menus, as shown in Figure 15.2. The Script Assist mode is most useful for beginners learning ActionScript for the first time. To enter Script Assist mode, click the Script Assist button on the options bar of the Script pane. Not all actions have the same ease of use within Script Assist; more complex ActionScript code is not well suited for Script Assist mode. When Script Assist mode is enabled, you cannot edit code manually within the Script pane, and you cannot switch the active booklet set.

You can add actions to the Script pane in one of three ways:

  • Drag an action from the Actions Toolbox to the Script pane.

  • Select an action from the Actions menu, accessed by clicking the plus (+) icon.

  • Double-click an action in the Actions pane.

To delete actions, select the action line(s) in the Script pane, and press Delete or Backspace on the keyboard.

The Script Assist mode displays a more user-friendly interface for controlling action parameters.

Figure 15.2. The Script Assist mode displays a more user-friendly interface for controlling action parameters.

After you have added an action to the Script pane, you can specify parameters (or arguments) for the action. Depending on the action, you may or may not need to type such parameters. By default, Flash CS5 provides code hints as you type actions into the Script pane. The Show Code Hint button enables you to see the parameters for an action, as shown in the navigateToURL action in Figure 15.2.

More important, the Script Assist mode makes it much easier for you to add and adjust settings for basic actions, especially those you find in the Timeline Control booklet. You use the Script Assist mode throughout this chapter to learn the basic control actions.

Note

The Script Assist mode is much more useful for legacy ActionScript 1.0 and 2.0 syntax. For ActionScript 3.0 syntax, most actions have limited options revealed in Script Assist mode.

You should get in the habit of clicking the Check Syntax button (the blue check mark) to make sure you didn't mistype an action. If you have an error, the Output panel displays some information related to the error, indicating the line number where the syntax error occurs.

A brief primer on code syntax

Some of the most difficult concepts for beginners to understand with code writing are white space, parentheses ( ( ) ), semicolons ( ; ), and curly braces ( {} ). In the following paragraphs, you learn how each of these affects your ActionScript code.

White space

White space is a collective term referring to any blank areas between lines of code. It includes spaces inserted by the spacebar, indentations inserted with the Tab key, and line returns inserted with the Enter or Return key. When Flash CS5 compiles your ActionScript code into the Flash movie, the white space between your lines of code usually does not generate any errors. For example, the following code works exactly the same:

navigateToURL(new URLRequest("http://flashsupport.com"));

or

navigateToURL(new URLRequest(
        "http://flashsupport.com"
        )
   );

or

navigateToURL( new URLRequest( "http://flashsupport.com" ) );

However, white space is an issue when it separates the key terms in the action, such as:

navigate To URL(new URL Request("http://flashsupport.com"));

The spaces between navigate, To, and URL will cause an error when Flash CS5 tries to create the Flash movie.

Tip

To check if your syntax is correct, click the Check Syntax button in the Actions panel. If you do have any white space errors, the Output panel displays information related to the error. Also, if your code has errors, you are prevented from entering the Script Assist mode.

Parentheses

Many, but not all, actions require parentheses after the action term, such as SoundMixer.stopAll(), navigateToURL(), or even play(). A general rule to remember is that if the action requires a parameter, such as navigateToURL(), then parentheses are required as well.

Note

Parameters are also referred to as arguments.

However, many actions, such as play() and stop(), still require parentheses, even though they do not use any arguments. Another rule for parentheses is that any open parenthesis ( ( ) must eventually be followed by a closing parenthesis ( ) ). A habit I like to encourage is counting the number of opening parentheses in a script and then counting the number of closing parentheses. If the numbers don't match, you need to review your code to find the place where you forgot to include a parenthesis.

Semicolons and curly braces

You've probably already noticed that most actions include a semicolon ( ; ) at the end of the code line. In practice, many coders forget to include semicolons. Usually, Flash is very forgiving if you omit semicolons, but by no means should you be encouraged to omit them. The general rule for semicolons and curly braces is mutually inclusive: If your action doesn't end with a closing curly brace ( } ), it should end with a semicolon. As with parentheses, all opening curly braces must eventually be followed by a closing curly brace ( } ). Curly braces are commonly used with if and function declarations.

Your First Five Actions

Now that you have a general picture of what actions do, let's look at five common actions in detail. At this point, we're describing only the functionality of each action, not how to add an action to your movie. I provide information on adding an action in the next section.

Note

You will find coverage of further actions in later chapters.

Actions in the Flash interface appear alphabetically sorted from top to bottom. In the following sections, complementary actions are grouped together.

gotoAndPlay() and gotoAndStop()

These "go to" actions change the current frame of the movie to the target frame specified as the action's parameter. There are two variations:

  • gotoAndPlay(): Changes the current frame to the frame specified, and then executes a play() action. gotoAndPlay() provides the capability to show animated sequences as preludes to individual content areas. gotoAndPlay() also gets frequent use in choose-your-own-adventure style animations, in which the user guides an animated character through different paths in a narrative.

Note

If you use a gotoAndPlay() action to go to a frame that has a stop() action, the timeline stops at the new frame.

  • gotoAndStop(): Changes the current frame to the frame specified and then halts playback on that frame. gotoAndStop() is often used to produce toolbar-style interfaces where the user clicks buttons to view different areas of content in a movie.

Both actions enable you to jump to certain areas of the Flash movie. The parameters of these actions start with the largest time unit, the scene, and end with the smallest one, the frame.

You can specify frames in other scenes as the target of goto actions with the scene parameter. As shown in the following code, you type the name of the scene first, with double quotes around the name, and then the frame number (without quotes) or frame label. In this example, "Scene 2" is the name of the scene and "animate_in" is the frame label in that scene to jump to.

gotoAndPlay("Scene 2", "animate_in");

However, if you specify only one parameter in a gotoAndPlay or gotoAndStop action, the parameter is interpreted as a frame label. For example, the following code tells the current timeline to jump to its "menu" frame label:

gotoAndStop("menu");

There are three methods of specifying the frame to which the movie should go when it receives a goto action. The methods for specifying the frame are

  • number: Specifies the target frame as a number. Frame 1 is the beginning of the movie or scene. Frame numbers should not use surrounding quotes, as frame labels do. The following action tells the current timeline to jump to frame 10 and start playing:

    gotoAndPlay(10);
  • label: Individual keyframes can be given names via the Label section's Name field in the Properties panel. After a frame is labeled, a goto action can target it by name. To specify a label as the target of a goto action, type the name of the frame as the action's parameter. The following example tells the Flash movie to go to the frame labeled "products" and stop at that frame:

    gotoAndStop("products");
  • ActionScript expression: Specifies the target frame as an interpreted ActionScript code segment. You use expressions to dynamically assign targets of goto actions. Here's a quick example of a string variable being used as a frame label:

    var targetLabel = "products";
    gotoAndPlay(targetLabel);

    Notice that the term targetLabel does not use quotes because it is not the actual frame label name. When the Flash Player interprets this action, it looks up the value of targetLabel, which is "products", and inserts that value into the gotoAndPlay action. With strict data typing in ActionScript 3.0, the same action looks like this:

    var targetLabel:String = "products";
    gotoAndPlay(targetLabel);

Warning

Using frame numbers to specify the targets of goto actions can lead to serious scalability problems in Flash movies. Adding frames at the beginning or in the middle of a movie's timeline causes the subsequent frames to be renumbered. When those frames are renumbered, all goto actions that use frame numbers must be revised to point to the correct new number of their target frames.

In the vast majority of cases, goto actions that use a frame label to specify target frames are preferable to goto actions that use a frame number to specify target frames. Unlike numbered frame targets, goto actions with labeled frame targets continue to function properly, even if the targeted frame changes position on the timeline.

nextFrame() and prevFrame()

The nextFrame() and prevFrame() actions act like a gotoAndStop() action, in that they both transport the timeline to a new position and stop.

  • nextFrame(): This action tells the current timeline to move forward one frame and stop playback. nextFrame() can be used in conjunction with prevFrame to quickly set up a slideshow-style walk-through of content, where each of a series of contiguous keyframes contains the content of one "slide." This action does not use any parameters. The following code moves the timeline to the next frame:

    nextFrame();
  • prevFrame(): This action moves the current timeline backward one frame and stops playback. For example, if the timeline is on frame 20, and the movie runs a prevFrame() action, the timeline moves to frame 19. As with the nextFrame() action, prevFrame() does not use any parameters:

    prevFrame();

nextScene() and prevScene()

These actions advance the Flash movie to a new scene. Here's how they work:

  • nextScene(): This action tells the current timeline to move to the first frame of the next scene. You can use nextScene() for more elaborate slide shows or demonstration movies, where each scene contains animated content with a stop action on the last frame. The last frame of the scene then contains a button using the nextScene() action. This action does not use any parameters. The following code tells the movie to jump to the next scene:

    nextScene();
  • prevScene(): This action jumps the movie to the previous scene. For example, if the playhead is in Scene 2, the timeline moves to the first frame of Scene 1. As with the nextScene() action, prevScene() does not use any parameters:

    prevFrame();

Note

The nextScene() and prevScene() actions do not automatically recycle the scenes when the last or first scene is reached, respectively. For example, if you have three scenes and use a nextScene() action while the movie is on the last scene, the movie does not jump back to the first scene.

Warning

As I mention earlier, you should avoid the use of multiple scenes in your Flash document. Although you may find it simpler to segment your Flash content across several scenes as you begin to learn Flash, most seasoned Flash designers and developers use only one scene, and separate content across several Movie Clip symbols placed on one or more frames of Scene 1. Scenes are not compatible with standard targeting syntax, as you'll learn in the next chapter.

play() and stop()

These simple actions are the true foundations of Flash timeline control. play() sets a movie or a Movie Clip instance in motion. When a play() action is executed, Flash starts the sequential display of each frame's contents along the current timeline.

The rate at which the frames appear is measured as frames per second, or fps. The fps rate can be set from 0.01 to 120 (meaning that the play action can cause the display of as little as 1 frame every 100 seconds to as many as 120 frames in 1 second, subject to the limitations of the computer's processing speed). In Flash CS5, the default fps is 24.

After play() has started, frames continue to appear one after the other, until another action interrupts the flow, or the end of the movie or Movie Clip's timeline is reached. If the end of a movie's timeline is reached, the movie either loops (begins playing again at frame 1, Scene 1) or stops on the last frame.

After the end of the Movie Clip's timeline is reached, playback loops back to the beginning of the clip, and the clip continues playing. To prevent looping, add a stop() action to the last frame of your Movie Clip.

Note

A single play() action affects only a single timeline, whether that timeline is the main movie timeline or the timeline of a Movie Clip instance. For example, a play action executed inside a Movie Clip does not cause the Main Timeline to begin playing. Likewise, any goto action on the Main Timeline doesn't migrate to the Movie Clips that reside there. A timeline must be specifically targeted to control playback along that timeline. If there is no specified target, the action is referring to its own timeline. However, this is not the case for animations within graphic symbol instances. An animation in a graphic symbol is controlled by actions on the timeline in which the symbol instance is present — Flash ignores actions on a graphic symbol's timeline.

The stop() action, as you may have guessed, halts the progression of a movie or Movie Clip that is in a play state. stop() is often used with buttons for user-controlled playback of a movie or on frames to end an animated sequence.

Tip

Movie Clip instances placed on any timeline begin to play automatically. Remember to add a stop() action on the first frame of a Movie Clip if you don't want it to play right away.

navigateToURL()

Want to link to a Web resource from a Flash movie? No problem. That's what navigateToURL() is for. For ActionScript 3.0, you can find the navigateToURL() action in the flash.net

navigateToURL()

Warning

The navigateToURL() action can be used only with ActionScript 3.0 content. If you need to publish legacy ActionScript 1.0 and 2.0 content, use the getURL() action.

navigateToURL() has two parameters that are familiar to Web designers and developers (the first one, url, is required for this action to work):

  • URLRequest: This is the network address of the page, file, script, or resource to which you are linking, formatted within a URLRequest wrapper. Any value is permitted (including ActionScript expressions), but the linked item can be displayed only if the reference to it is correct. The URLRequest value is directly analogous to the HREF attribute of an HTML anchor tag. You can use a relative or absolute URL as well. Examples:

    http://www.yoursite.com/
    ftp://ftp.yoursite.com/pub/documents.zip
    menu.html
    /cgi-bin/processform.cgi
      /script/form.cfm

    Tip

    You can specify secure domain URLs by using the https protocol for SSL (Secure Sockets Layer) connections.

  • window: This is the name of the frame or window in which you want to load the resource specified in the URL setting. The window parameter is directly analogous to the target attribute of an HTML anchor tag. In addition to enabling the entry of custom frame and window names, the window parameter can use the following browser-standard target names:

    • "_self": Loads the URL into the same frame or window as the current movie. If you do not specify a window parameter in the getURL action, this behavior is the default.

    • "_blank": Creates a new browser window and loads the URL into it.

    • "_parent": Removes the current frameset and loads the URL in its place. Use this option if you have multiple nested framesets, and you want your linked URL to replace only the frameset in which your movie resides.

    • "_top": Loads the URL into the current browser and removes all framesets in the process. Use this option if your movie is in a frame, but you want your linked URL to be loaded normally into the browser, outside the confines of any frames.

Note

Frame windows and/or JavaScript windows can be assigned names. You can target these names by manually typing the name in the Window field. For example, if you had a frame defined as <frame name="main". . .>, you could load specific URLs into a frame named main from a Flash movie.

Tip

The navigateToURL() action works in the Test Movie environment. Both the Flash stand-alone player and the Test Movie command give you access to external and/or local URLs.

Here are some examples of how you can write a navigateToURL() action. The following code tells the browser to load the URL www.wiley.com into the current browser window:

navigateToURL(new URLRequest("http://www.wiley.com"));

Alternatively, you can specify a unique target for the loaded URL. The following example loads an HTML document named menu.html into a frame named menu_frame:

navigateToURL(new URLRequest("menu.html"), "menu_frame");

A more advanced usage of the navigateToURL() action sends variables from the Flash movie to a Web server's script, which is set up to receive the variables. The following code opens a Google.com search results page for the term "Flash Video":

var googleURL = new URLRequest("http://google.com/search");
   var searchData = new URLVariables();
   searchData.hl = "en";
   searchData.q = "Flash Video";
   googleURL.data = searchData;
   navigateToURL(googleURL, "_blank");

As I mention with the goto actions, you can also use expressions with navigateToURL() actions. Expressions can be used as parameters of any ActionScript action. The following example uses a string variable to specify the URL used by a navigateToURL() action:

var siteURL = new URLRequest("http://www.flashsupport.com");
navigateToURL(siteURL);

You should start familiarizing yourself with the ActionScript notation that Flash uses for each action (see Table 15.2). As you use Flash for more advanced interactivity, you'll need to have a firm grasp of code notation.

Table 15.2. Common Actions and ActionScript Notation

Action

ActionScript Notation

Arguments

gotoAndStop

gotoAndStop(arguments);

Scene name (frame label, number, or expression)

gotoAndPlay

gotoAndPlay(arguments);

Scene name (frame label, number, or expression)

nextFrame

nextFrame();

None

prevFrame

prevFrame();

None

nextScene

nextScene();

None

prevScene

prevScene();

None

play

play();

None

stop

stop();

None

navigateToURL

navigateToURL(arguments);

URLRequest instance, target frame, or window

Making Actions Happen with Event Handlers

The ten common actions I discuss in the previous sections provide many of the behaviors that you need to make an interesting interactive Flash movie. But those actions can't make your movies interactive on their own. They need to be told when to happen. To tell a Flash movie when an action should occur, you need event handlers. Event handlers specify the condition(s) under which an action can be made to happen. For example, you might want to mouse-click a button to initiate a play() action, or you might want a movie to stop when a certain keyframe in the timeline is reached. Creating interactivity in your movies is simply a matter of deciding what event you want to detect (mouse-click, keystroke, and so on), adding the appropriate event handler to detect it, and specifying the action(s) that should be performed when it happens.

Before I describe each event handler in detail, in the next section I show you an example of exactly how an event handler merges with an action to form a functioning interactive button.

Using the Code Snippets panel

The Code Snippets panel, new in Flash CS5, contains many useful prewritten blocks of code that you can apply in your Flash movies. This panel is found under Window

Using the Code Snippets panel

The Code Snippets panel, shown in Figure 15.3, is the fastest way to use and learn ActionScript 3.0. As you work with the Code Snippets panel and practice modifying the code it generates, try to look at the code to understand how it works. When you have a question about a particular piece of code, highlight it and press F1 on your keyboard to look it up in Flash Help.

The new Code Snippets panel

Figure 15.3. The new Code Snippets panel

Note

The Code Snippets panel also supports custom snippets through its Options flyout menu.

Combining an action with an event handler to make a functioning button

Imagine that you have a short, endlessly looping movie in which a wire-frame cube rotates. Now imagine that you want to add a button to your movie that, when clicked, stops the cube from rotating by stopping the playback of the looping movie. Here's what you need to do:

Note

For this exercise, you can use the rotatingCube.fla file located in the ch15 folder on this book's CD-ROM. The finished file is named rotatingCube_complete.fla.

  1. Open the starter Flash document, rotatingCube.fla. Save this document as rotatingCube_complete.fla on your local hard drive.

  2. Make a new layer called button.

  3. Place a button on the button layer. You can use Flash CS5's sample Stop button found in the classic buttons

    Combining an action with an event handler to make a functioning button

    Tip

    Selecting buttons and editing button properties sometimes can be tricky if buttons are enabled in the Flash authoring environment. For easier button manipulation, disable buttons by unchecking Enable Simple Buttons under the Control menu.

  4. Select the button instance, and open the Properties panel. Name the instance stopButton. Button symbol instances must be named to be accessible by ActionScript.

  5. With the stopButton instance selected, open the Code Snippets panel (Window

    Combining an action with an event handler to make a functioning button
  6. In the Actions panel, find the line of code that has the gotoAndStop() action, and change the line to the following code:

    stop();

    Note

    In computer programming, a constant is a reserved word with a predefined value.

  7. Now that you have a button in your Flash movie that stops the movie's playback when it is clicked, save your Flash document (.fla), and test the movie by choosing Control

    Combining an action with an event handler to make a functioning button
The Stop button on the Stage

Figure 15.4. The Stop button on the Stage

Tip

The Code Snippets panel offers a large amount of prewritten code that you can add to your Flash movies. Try experimenting with the other snippets in the panel to add more functionality to the movie you just created to get practice working with ActionScript 3.0.

To make any interactivity in your movies, you simply have to apply the basic principles you used to make the stop button: Decide which action (or actions) you want to happen, and indicate when you want that action to happen with an event handler. Let's look now at more event handlers you can use to make those actions happen.

The Flash event handlers

Three primary event handlers exist in Flash: those that detect mouse activity on button symbol instances (button manipulation), those that recognize when a key is pressed on the keyboard (key presses), and those that respond to the progression of the timeline (keyframes).

Working with mouse events and buttons

Event handlers that occur based on the user's interaction with a button rely entirely on the location and movement of the mouse pointer. If the mouse pointer comes in contact with a button symbol's hit area, the pointer changes from an arrow icon to a finger pointer icon. At that time the mouse is described as "over" the button. If the mouse pointer is not over a button, it is said to be out or outside of the button. General movement of the mouse without the mouse button depressed is referred to as rolling. General movement of the mouse with the mouse button pressed is referred to as dragging.

Note

If you don't know how to make a button symbol and its various states, read Chapter 6, "Symbols, Instances, and the Library."

Warning

Event handlers and actions for buttons can be placed only on button instances, not on the four frames in the timeline of the original button symbol. One of the features in Flash CS5 is that it does not enable you to place any actions in a button symbol timeline.

Here are the mouse-based events for Flash display objects that use the addEventListener() method. Each of these events is case-sensitive when typed in ActionScript 3.0 code.

MouseEvent.MOUSE_DOWN

A single mouse-click can actually be divided into two separate components: the downstroke (the press) and the upstroke (the release). A MouseEvent.MOUSE_DOWN event occurs when the mouse pointer is over the hit area of a button and the downstroke of a mouse-click is detected. This event is best used for control panel-style buttons, especially toggle switches.

Warning

Typically, developers should program reversible decisions for primary navigation so that users can abort their clicks by rolling the cursor away from the hit area before releasing the mouse. For example, a user might click a button for more information and decide he or she would rather not get that information. I do not recommend using the MouseEvent.MOUSE_DOWN event for important user moves such as these because it does not give users an opportunity to abort their moves.

MouseEvent.MOUSE_UP and MouseEvent.CLICK

These events occur when the mouse pointer is over the hit area of a button and both the downstroke and the upstroke of a mouse-click are detected. The MouseEvent.CLICK event is the standard button-click event.

Tip

If you use the Track as Menu Item behavior for a button instance in the Properties panel, a button responds to a MouseEvent.MOUSE_UP event over its Hit state even if the mouse was pressed outside of the button's hit area.

MouseEvent.ROLL_OVER

This event occurs when the mouse pointer moves onto the hit area of a button without the mouse button depressed.

Note

To perform standard rollover button effects, such as graphic art changes or sound events, you can insert graphics and sound on to the Over state of the button symbol timeline.

MouseEvent.ROLL_OUT

This event occurs when the mouse pointer moves off of the hit area of a button without the mouse button depressed. This event is commonly used for switching an advanced button's graphic state back to its original state when the user rolls off the button.

Capturing time events with keyframes

The keyframe event handler depends on the playback of the movie itself, not on the user. Just about any action can be attached to any keyframe on the timeline. An action attached to a keyframe is executed when the playhead enters the keyframe, whether it enters naturally during the linear playback of the movie or as the result of a goto action. So, for example, you may place a stop action on a keyframe to pause the movie at the end of an animation sequence.

Note

In ActionScript 3.0 code, button handlers can be defined in keyframes, but the code referenced by a button handler does not execute when the playhead enters the frame where that code exists.

In some multimedia applications, keyframe event handlers can differentiate between the playhead entering a keyframe and exiting a keyframe. Flash has only one kind of keyframe event handler (essentially, on enter). Hence, as a developer, you do not need to add keyframe event handlers explicitly — they are a presumed element of any action placed on a keyframe.

Tip

Complex movies can have dozens, or hundreds (or even thousands!), of actions attached to keyframes. To prevent conflicts between uses of keyframes for animation and uses of keyframes as action containers, it is highly advisable to create an entire layer solely for action keyframes. Name the layer actions and keep it on top of all your layers for easy access. Remember not to place any symbol instances, text, or artwork on your actions layer. You can also create a labels layer to hold — you guessed it — frame labels.

The process for adding an action to a keyframe is as follows:

  1. Create a keyframe on a timeline. This keyframe can exist in the Main Timeline (that is, Scene 1) or a Movie Clip symbol timeline.

  2. Select the keyframe in the Timeline window, and open the Actions panel. The Actions panel title should read Actions – Frame.

  3. Type your desired actions in the Script pane.

In the next section, you get a little more hands-on experience adding actions to both buttons and keyframes.

Creating Invisible Buttons and Using navigateToURL

In this section, you learn how to create an "invisible button" and practice the use of navigateToURL() actions. An invisible button is essentially a button symbol that has only a Hit state defined, with empty Up, Over, and Down states. After you create an invisible button, you can use it to convert any type of Flash element into a button. By dragging an instance of the invisible button on top of another piece of artwork or symbol instance on the Stage, you can add interactivity to that element.

Note

Make a copy of the themakers_ad_starter.fla file, located in the ch15 folder of the book's CD-ROM. This file contains a sample layout of graphics and text for a mock Flash ad, sized for display on a Microsoft Windows Mobile 6 device screen.

With the starter Flash document (.fla) open in Flash CS5, quickly familiarize yourself with the existing content. There are four layers on the Main Timeline (Scene 1). The comments layer indicates what the Flash document is, the border layer contains a black outlined box with no fill, the graphics layer contains a graphic symbol of branding artwork, and the animText layer contains a Movie Clip instance featuring a tweened animation. Go ahead and test this movie (Control

Creating Invisible Buttons and Using navigateToURL
The artwork of the Flash movie designed for a Windows Mobile screen

Figure 15.5. The artwork of the Flash movie designed for a Windows Mobile screen

In this exercise, you're going to add two invisible buttons to this movie. One is an oval-shaped button that fits over the thumbprint graphic, and another is a rectangular-shaped button that fits over the company's name. The thumbprint button, when clicked, opens the e-mail client to send an e-mail to the company. When the user clicks the name button, a new browser window opens displaying the company's Web page.

  1. In the starter Flash document, create a new layer named actions. Place this layer just underneath the comments layer.

  2. Save the starter document as makers_ad.fla. Currently, there is more than one frame on the Main Timeline, and if you were to develop this Flash movie further, you wouldn't want the playhead going past the first frame without some input from the user.

  3. Select the first frame of this layer and open the Actions panel (F9,/Option+F9), and type the following code in the Script pane:

    stop();
  4. With this first frame of the actions layer still selected, open the Properties panel and in the Label section's Name field, type //stop. This adds a frame comment of //stop to the layer in the Timeline window. This comment provides a quick visual cue about the behavior of this keyframe. Now you're going to make your first invisible button.

  5. Choose Insert

    The artwork of the Flash movie designed for a Windows Mobile screen
  6. Rename Layer 1 to hit area graphic. On this layer of the button symbol's timeline, create a keyframe for the Hit state. Move the playhead in the Timeline window to this new keyframe.

  7. Select the Rectangle tool, and draw a uniform square on the symbol's Stage. The square can be any color, although I prefer red for invisible buttons. If you drew the shape with a stroke, delete the stroke. Select the square, and in the Properties panel, give the square a width and height of 50 pixels. Then using the Align panel, center the square on the Stage. Your button symbol and timeline should now resemble Figure 15.6.

    The square acts as the active area of the button symbol.

    Figure 15.6. The square acts as the active area of the button symbol.

  8. Now, go back to Scene 1 (the Main Timeline), and create a new layer. Rename this layer linkButton, and place it above the graphics layer.

  9. Open the Library panel (Ctrl+L/

    The square acts as the active area of the button symbol.
  10. Using the Free Transform tool, size the instance to fit the size of the text, without overlapping other elements on the Stage, as shown in Figure 15.7.

    The linkButton instance resized over the company's name

    Figure 15.7. The linkButton instance resized over the company's name

  11. With the Selection tool, select frame 1 of the actions layer, and open the Actions panel (F9,/Option+F9). Your Action panel title bar should read Actions - Button. In the Script pane, add a button listener for the MouseEvent.CLICK event, directing the Web browser to a new Web page when the linkButton instance is clicked. Add the following code below the existing stop(); action:

    linkButton.addEventListener(MouseEvent.CLICK, onLinkClick);
    
    function onLinkClick (evt) {
       var siteURL = new URLRequest("http://www.theMakers.com");
       navigateToURL(siteURL, "_blank");
    }

    For this example, I used the URL http://www.theMakers.com. When you're linking to domain names, make sure that you specify the transfer protocol (such as http://, ftp://, and so on). If you are linking to relative URLs, specify the name of the HTML document (or other resource) that you want to access. This onLinkClick() handler containing the navigateToURL() action directs a button click on this instance to [theMAKERS] Web site, in a new browser window.

  12. Save your Flash document, and test it by using Control

    The linkButton instance resized over the company's name
  13. Now, go back to the Flash document and add another invisible button. You'll use a different procedure this time. On the Scene 1 timeline, create a new layer and name it emailButton. Place this layer above the linkButton layer.

  14. On the first frame of the emailButton layer, select the Oval tool, and draw a perfect circle anywhere on the Stage. Again, you can use any fill color you want. If the circle has a stroke, delete the stroke. With this circle selected, open the Properties panel and give the circle a width and height of 50 pixels.

  15. With the circle selected, choose Modify

    The linkButton instance resized over the company's name
  16. Now, edit the new symbol, either by double-clicking the instance on the Stage or by double-clicking its listing in the Library panel. On this symbol's timeline, rename Layer 1 to hit area graphic. Now, select the keyframe for the Up state, and drag it to the Hit state. Note that you may need to click, and then click and drag the keyframe for this method to work properly. When you are finished, your circle shape should be on only the Hit area of the button's timeline.

  17. Go back to the Scene 1 timeline, and you'll notice that your circle button is now an invisible button, just as our rectangular one is. Move the circular invisible button over the thumbprint graphic, and use the Free Transform tool to shape the circle as an oval that closely matches the shape of the thumbprint, as shown in Figure 15.8. Also, name the instance emailButton in the Properties panel.

  18. Select frame 1 of the actions layer, and open the Actions panel. Repeat Step 11 of this exercise, referencing the new emailButton instance. This time, however, we'll use a mailto: URL, as in "mailto:". Type this value within a URLRequest wrapper. For this navigateToURL() action, however, you do not need to specify a window parameter. Add the following code below the existing lines of code:

    emailButton.addEventListener(MouseEvent.CLICK, onEmailClick);
    
    function onEmailClick (evt) {
       var mailURL = new URLRequest("mailto:[email protected]");
       navigateToURL(mailURL);
    }

    Tip

    You can specify subject lines and body text in mailto: URLs as well, just as you can with HTML documents. For example, the following code opens a new e-mail message window addressed to , with a subject line of "Web Feedback" and body text of "Here are my comments." The following code should be typed as one line of code. Do not type the

    The linkButton instance resized over the company's name
    "mailto:[email protected]?  
    The linkButton instance resized over the company's name
    subject=Web%20Feedback&body=Here%20are%20my%20comments%3A");
    The thumbprint graphic now has an invisible button on top of it.

    Figure 15.8. The thumbprint graphic now has an invisible button on top of it.

  19. Save your Flash document once again, and test the movie. When you click the active area over the thumbprint graphic, the default e-mail client on your system should open, displaying a new message window with the To: field predefined to the URL you typed in Step 18.

Tip

You can also change the title and description metadata published with the .swf file by choosing Modify

The thumbprint graphic now has an invisible button on top of it.

Now you know how to make invisible buttons and add navigateToURL() actions to them. In your own work, you may come to realize the true benefit of invisible buttons: You can quickly drag several instances of either invisible button shape (oval or rectangle) to the Stage to create active areas. This offers two benefits: First, you don't have to make button symbols from regular graphics that don't need four button states, and second, you can make "hidden" areas in interactive puzzles or games.

Summary

  • ActionScript is Flash's interactive language. It is a set of actions that enables Flash to communicate with internal elements (timelines, symbols, sounds, and so on) and external Web pages and scripts.

  • ActionScript 3.0, or AS3, is the newest version of the scripting language for the Flash Player. AS3 is available only in Flash Player 9 or later. You must use ActionScript 1.0 or 2.0 for legacy Flash content playable in Flash Player 8 or earlier.

  • Flash CS5 includes a new panel called the Code Snippets panel, which allows you to apply prewritten code to your Flash movies.

  • Flash interactivity is based on a relatively simple structure: An event handler waits for something to happen (a playback point being reached or the user providing input), and when that something does happen, it executes one or more actions (which alter the movie's playback, behavior, or properties; load a file; or execute a script).

  • All actions need an event handler to activate them. Event handlers include keyframes on a timeline, button clicks, mouse movements, and key presses. More advanced event handlers are discussed in later chapters.

  • Invisible buttons enable you to create interactive areas on top of other Flash artwork or symbols.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset