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 8 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, which you'll learn about later in this chapter, enables you to quickly add an action or a series of actions to a Flash object or keyframe.

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. We 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 know 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 Macromedia Flash or Macromedia Director or Apple DVD Studio Pro, has unique handlers for specific events. Table 18-1 relates interactive events with Flash handlers.

Table 18-1: Events and Flash Handlers

Event

Type

Event handler

Example

Playback

Time-based

Keyframes

MovieClip object

NetStream object

Timeline plays until it reaches a certain frame; a Movie Clip 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

Button object

MovieClip object

Mouse object

A visitor clicks a button; mouse movement detected over a Movie Clip instance.

Key press

User input

Button object

MovieClip object

Key object

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 object

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 object

Camera object

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

MovieClip object

data objects

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

While the breadth and depth of ActionScript involved with the interactions described in Table 18-1 may seem overwhelming, don't worry — we're taking it one step at a time. First, you'll learn about what the new Behaviors panel can do. Then you'll learn how to set up the Actions panel, whose look and feel has changed from previous versions of Flash. Later, 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 are Behaviors?

Flash 8 includes a Behaviors panel, which was introduced in Flash MX 2004. This panel is designed to help a novice who is just starting to use Flash for design and development. You can open the Behaviors panel, shown in Figure 18-1, by choosing Window ð Behaviors (Shift+F3).

image from book
Figure 18-1: The Behaviors panel showing a Button component with a behavior applied

If you create a new Flash document and select the first frame of Layer 1, you can click the Add Behavior (+) button at the top-left corner of the Behaviors panel to see a list of categories (see Figure 18-2).

image from book
Figure 18-2: The categories in the Add Behavior menu

These categories represent a variety of objects you can control with one or more behaviors. So what do behaviors do? In the simplest sense, a behavior is automated scripting. When you add a behavior to an event handler, Flash 8 generates the necessary ActionScript code to make that behavior happen. Let's take a quick look at a Web behavior.

  1. Create a new Flash document by choosing File ð New. In the New Document dialog box, double-click the Flash document item. Save the new document as button_behavior.fla.

  2. Rename Layer 1 to button.

  3. Open the Components panel (Ctrl+F7 or z+F7). Expand the User Interface set, and drag an instance of the Button component to the Stage.

    Tip 

    Whenever you place a new element on the Stage, make sure you set its X and Y positions to an integer value in the Property inspector. An integer is a whole number, without any decimals. By placing your elements at integer values, embedded fonts display much more crisply.

  4. Select the Button component instance on the Stage, and open the Property inspector. In the <Instance Name> field, type cbtWeb. Click the Parameters tab, and in the label field, type web site (see Figure 18-3).

    Tip 

    Throughout this book, we use naming conventions for our symbol instances, especially Movie Clip and component instances. The convention for this example uses a three-letter prefix for component names, such cbt. This abbreviation stands for component button. Naming conventions enable you to more quickly review and understand your ActionScript code.

  5. With the Button instance selected on the Stage, open the Behaviors panel. Click the Add Behavior (+) button, and choose Web ð Go to Web Page. In the Go to URL dialog box, type http://www.flashsupport.com in the URL field. Choose "_blank" in the Open in menu. Refer to Figure 18-4. Click OK when you are done entering the parameters.

  6. Now look at the code that Flash 8 created for the behavior. Select the cbtWeb instance, and choose Window ð Actions (F9). You'll see the following code:

     on (click) {    //Goto Webpage Behavior    getURL("http://www.flashsupport.com","_blank");    //End Behavior } 

    The heart of this code is the event handler, on(), and the getURL() action. When the user clicks the Button component instance, the on() handler detects the click and executes (or invokes) the getURL() action. You'll learn more about these actions later in this chapter.

    Note 

    The click event is available in Flash Player 7 and higher, and is specific to the UI components. This event is not used for standard mouse events on Button symbol instances.

  7. Save your Flash document (FileðSave) and choose ControlðTest Movie. When the Flash movie loads, click the button. Your Web browser should open to the www.flashsupport.com Web site, the official support site for this book.

image from book
Figure 18-3: The settings for the Button component

image from book
Figure 18-4: The Go to URL settings

On the CD-ROM 

You can find the completed file, button_behavior.fla, in the ch18 folder of this book's CD-ROM.

We won't discuss any other behaviors in this chapter, as you can find specific categories of behaviors explained in other parts of the book:

  • MovieClip behaviors, Chapter 19, "Building Timelines and Interactions"

  • Projector behavior, Chapter 23, "Using the Flash Player and Projector"

  • Sound behaviors, Chapter 15, "Adding Sound"

Behaviors enable you to learn by example — you can add a behavior to an object and look at the code used to describe the interaction.

Note 

Experienced Flash developers and programmers will be the first to tell you that it's not a good idea to put a lot of code on objects that are on the Stage. Most scripts are placed on one or more keyframes, or the code is stored in a separate .as file. You learn more about programming practices in Part VII, "Approaching ActionScript."

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 usable to computer programmers, Flash's scripting language, called ActionScript, changed much of its formatting in Flash 5 to mirror JavaScript, a fundamental element for Dynamic HyperText Markup Language (DHTML) and HTML Web pages. Right now, we focus on using the most basic Flash ActionScript.

Note 

In Flash MX 2004, ActionScript matured to a whole new version, dubbed ActionScript 2.0, or AS2. ActionScript 2.0 is a different — and more complex — style of coding than what was used in Flash MX and earlier. The ActionScript style used in Flash MX and earlier is now known as ActionScript 1.0, or AS1. It's still perfectly valid to code in either style. ActionScript 2.0 will feel more familiar to developers who have used other object-oriented programming languages such as C++ or Java.

Cross-Reference 

If you're interested in learning the fundamental building blocks of ActionScript programming, check out our advanced coverage of ActionScript in Chapters 24 through 35. The three chapters of Part V are intended to provide a starting point for Flash designers and developers who are new to Flash actions and interactive concepts. Exhaustive coverage of the ActionScript language can be found in the Flash ActionScript Bible series by Joey Lott and Robert Reinhardt (Wiley).

Navigating the Actions Panel

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

  • Go to Windows ð Actions

  • Press the F9 key (or Option on Mac)

  • Alt +double-click (or 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 18-5). 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 simply read Actions. Don't be confused — there is only one Actions panel. Flash 8 simply lets you know the object to which you are assigning actions.

image from book
Figure 18-5: The Actions panel enables you to instantly add, delete, or change Flash movie commands.

New Feature 

The Actions panel in Flash 8 features a new 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. If you used Normal mode in Flash MX or earlier, you'll be happy to know that Normal mode is essentially re-integrated as Script Assist in Flash 8.

As shown in Figure 18-5, the Actions panel in Flash 8 has three distinct areas (counter-clock-wise from the left): the Actions toolbox, the Script navigator, and the Script pane. The new 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 18-5 and 18-6 show a breakdown of the new Actions panel in Flash 8.

image from book
Figure 18-6: The Script Assist mode displays a more user-friendly interface for controlling action parameters.

  • The Actions toolbox contains several nested booklets of ActionScript commands. You can select actions to add to the Script pane.

    New Feature 

    The Actions toolbox now has a booklet selection drop-down menu. The default set of booklets displayed in the toolbox pertain to ActionScript 1.0 and 2.0, but you can switch to other sets of booklets, including Flash Lite 1.0 and Flash Lite 1.1. These booklets only display actions compatible with the Flash Lite 1.0/1.1 players that ship on some mobile 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 is displayed 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, as fill-in text fields or drop-down menus, as shown in Figure 18-6. 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.

Tip 

When the Actions panel is in focus, a highlighted bar shows up on the left side of the Script pane. This highlighted color enables you to know if you can start typing in the Script pane.

For this chapter, you'll work primarily within the Timeline Control booklet, located within the Global Functions booklet in the Actions toolbox.

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 the Delete or Backspace key on the keyboard.

Once 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 8 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 gotoAndPlay action in Figure 18-5.

More importantly, 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.

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.

Cross-Reference 

In Chapter 24, "Knowing the Nuts and Bolts of Code," you can also learn about referencing actions in the Help panel of Flash 8.

For now, let's look at two booklets in the Actions toolbox's Global Functions booklet: Timeline Control and Browser/Network. The Timeline Control actions are listed in alphabetical order. The first eight actions in this booklet, including gotoAndPlay, gotoAndStop, play, and stop, control the playback of the movie. The last action, stopAllSounds, is a global command to handle sound playback.

Note 

If you're in Script Assist mode, the actions listed in the action booklets may change. The actions in the Timeline Control booklet are reduced to goto, play, stop, and stopAllSounds. The Script Assist mode enables the missing actions in one of the other actions. For example, the gotoAndPlay and gotoAndStop actions are both available in the parameters of the goto action in Script Assist mode. The Browser/Network actions are also truncated in a similar fashion.

The Browser/Network actions — fscommand, getURL, loadMovie/loadMovieNum, loadVariables/loadVariablesNum, and unloadMovie/unloadMovieNum — enable movies to load external files and communicate with the browser, a Web server, or the stand-alone player. In this chapter, we'll get you up and running with the getURL action, which enables you to link to other Web resources outside of the Flash movie (such as Web pages and file downloads).

Note 

Throughout this book, you'll see most actions specified with () characters at the end of the action's name. For example, the gotoAndPlay action is really a method, and in code, it appears as gotoAndPlay(). In Part VII of this book, we provide more detailed information about code terms and practices.

The remaining Action booklets primarily offer extended ActionScript programming capabilities. We discuss many of these actions in later chapters.

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 8 compiles your ActionScript code into the Flash movie, the white space between your lines of code usually will not generate any errors. For example, the following code works exactly the same:

 on(release){ getURL("mypage.html"); } 

or

 on(release){    getURL("mypage.html"); } 

or

 on      (             release){ getURL("mypage.html"); } 

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

 get URL("mypage.html"); 

The space between get and URL will cause an error when Flash 8 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 will display information related to the error. Also, if you 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 on(), getURL(), or even play(). A general rule to remember is that if the action requires a parameter, such as on (release), 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 we 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 an opening 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 actions beginning with on, such as on() and onClipEvent(), as well as if and function declarations.

Cross-Reference 

You'll learn more about if statements and functions in Part VII, "Approaching ActionScript."

image from book
Deprecated and Incompatible Actions: What Are They?

As the ActionScript language of Flash continues to expand and encompass new functionality, older actions coexist with newer and better actions (or methods, properties, event handlers, and functions, which we'll discuss later). While Flash Player 8 will continue to support ActionScript 1.0 and earlier actions, it's better not to use older actions if the newest version of the Flash Player has a new way of accomplishing the same task. Older actions that have been replaced with a new action (or new way to perform the same task) are called deprecated actions. The Actions panel in Flash 8 houses all deprecated actions in the Deprecated booklet of the Actions pane. Why shouldn't you use these actions? As you'll see in more advanced scripting, Flash 8 has specific syntax to target Movie Clips and determine whether certain frames have loaded, among other features of the ActionScript "dot syntax" language. The following figure shows the actions within the Deprecated ð Actions booklet. Note that there are other groups of deprecated actions inside the Deprecated booklet as well.

Although you should avoid actions that are highlighted in the Deprecated booklet if possible, Flash Player 8 continues to support them.

Flash 8 will also let you know if certain actions are not supported with the Player version that is selected in the Flash format tab of the Publish Settings (File ð Publish Settings). Note that you can also find the Player version setting in the Property inspector when you click an empty area of the Stage or the Work area. If an action is not supported by the version you have selected, the action is highlighted in yellow. The following figure shows this type of highlighting in the Actions panel. You will notice that the tooltip (or rollover description) indicates which version of the Flash Player supports the action.

Flash Player 4 (or earlier) and Flash Lite 1.0/1.1 will not support the onClipEvent or updateAfterEvent actions (among others), as these actions were introduced in Flash Player 5.

image from book




Macromedia Flash 8 Bible
Macromedia Flash8 Bible
ISBN: 0471746762
EAN: 2147483647
Year: 2006
Pages: 395

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net