Add Life to the Web, Afterburner, Aftershock, Andromedia, Allaire, Animation PowerPack, Aria, Attain, Authorware,
Authorware Star, Backstage, Bright Tiger, Clustercats, ColdFusion, Contribute, Design In Motion, Director, Dream Templates,
Dreamweaver, Drumbeat 2000, EDJE, EJIPT, Extreme 3D, Fireworks, Flash, Fontographer, FreeHand, Generator, HomeSite,
JFusion, JRun, Kawa, Know Your Site, Knowledge Objects, Knowledge Stream, Knowledge Track, LikeMinds, Lingo, Live
Effects, MacRecorder Logo and Design, Macromedia, Macromedia Action!, Macromedia Flash, Macromedia M Logo and
Design, Macromedia Spectra, Macromedia xRes Logo and Design, MacroModel, Made with Macromedia, Made with
Macromedia Logo and Design, MAGIC Logo and Design, Mediamaker, Movie Critic, Open Sesame!, Roundtrip, Roundtrip
HTML, Shockwave, Sitespring, SoundEdit, Titlemaker, UltraDev, Web Design 101, what the web can be, and Xtra are either
registered trademarks or trademarks of Macromedia, Inc. and may be registered in the United States or in other jurisdictions
including internationally. Other product names, logos, designs, titles, words, or phrases mentioned within this publication may
be trademarks, service marks, or trade names of Macromedia, Inc. or other entities and may be registered in certain jurisdictions
including internationally.
Third-Party Information
This guide contains links to third-party websites that are not under the control of Macromedia, and Macromedia is not
responsible for the content on any linked site. If you access a third-party website mentioned in this guide, then you do so at your
own risk. Macromedia provides these links only as a convenience, and the inclusion of the link does not imply that Macromedia
endorses or accepts any responsibility for the content on those third-party sites.
Speech compression and decompression technology licensed from Nellymoser, Inc. (www.nellymoser.com).
Sorenson™ Spark™ video compression and decompression technology licensed from
Sorenson Media, Inc.
APPLE COMPUTER, INC. MAKES NO WARRANTIES, EITHER EXPRESS OR IMPLIED, REGARDING THE
ENCLOSED COMPUTER SOFTWARE PACKAGE, ITS MERCHANTABILITY OR ITS FITNESS FOR ANY
PARTICULAR PURPOSE. THE EXCLUSION OF IMPLIED WARRANTIES IS NOT PERMITTED BY SOME STATES.
THE ABOVE EXCLUSION MAY NOT APPLY TO YOU. THIS WARRANTY PROVIDES YOU WITH SPECIFIC
LEGAL RIGHTS. THERE MAY BE OTHER RIGHTS THAT YOU MAY HAVE WHICH VARY FROM STATE TO
STATE.
Macromedia Flash MX 2004 and Flash MX Professional 2004 are the professional standard
authoring tools for producing high-impact web experiences. ActionScript is the language you use
when you want to develop an application within Flash. You don’t have to use ActionScript to use
Flash, but if you want to provide user interactivity, work with objects other than those built into
Flash (such as buttons and movie clips), or otherwise turn a SWF file into a more robust user
experience, you’ll probably want to use ActionScript.
Intended audience
This book assumes that you already have Flash MX 2004 or Flash MX Professional 2004 installed
and know how to use it. You should know how to place objects on the Stage and manipulate them
in the Flash authoring environment. If you have written programs before, ActionScript will feel
familiar. But even if you haven’t, ActionScript isn’t hard to learn. It’s easy to start with very simple
commands and build more complexity as you go along.
System requirements
ActionScript does not have any system requirements in addition to Flash MX 2004 or Flash MX
Professional 2004. However, the documentation assumes that you are using the default
publishing settings for your Flash files: Flash Player 7 and ActionScript 2.0. If you change
either of these settings, explanations and code samples shown in the documentation may not
work correctly.
Using the documentation
This document provides an overview of ActionScript syntax, information on how to use
ActionScript when working with different types of objects, and details on the syntax and usage of
every language element. Start by learning the terminology and basic concepts used in the rest of
the document (see Chapter 2, “ActionScript Basics,” on page 25). Next, learn the mechanics of
writing and debugging Flash scripts (see Chapter 3, “Writing and Debugging Scripts,”
on page 55).
Before writing your own scripts, you should complete the lessons “Write Scripts with
ActionScript” and “Create a Form with Conditional Logic and Send Data,” which provide a
hands-on introduction to working with ActionScript. To find these lessons, select Help >
How Do I > Quick Tasks.
9
After you understand the basics, you are ready to use the information in the rest of this document
as it applies to the specific effect you are trying to achieve. For example, if you want to learn how
to write a script that performs a certain action when a user clicks the mouse, see Chapter 4,
“Handling Events,” on page 83.
When you find information about a certain command you want to use, you can look up its entry
in Chapter 12, “ActionScript Dictionary,” on page 205; every language element is listed there in
alphabetical order.
Typographical conventions
The following typographical conventions are used in this book:
• Code fontindicates ActionScript code.
• Code font italic indicates an element, such as an ActionScript parameter or object name,
that you replace with your own text when writing a script.
Terms used in this document
The following terms are used in this book:
• You refers to the developer who is writing a script or application.
• The user refers to the person who will be running your scripts and applications.
• Compile time is the time at which you publish, export, test, or debug your document.
• Runtime is the time at which your script is running in Flash Player.
ActionScript terms such as method and object are defined in Chapter 2, “ActionScript Basics,”
on page 25.
Additional resources
Specific documentation about Flash and related products is available separately.
• For information about working in the Flash authoring environment, see Using Flash Help. For
information about working with components, see Using Components Help.
• For information about creating communication applications with Flash Communication
Server, see Developing Communications Applications and Managing Flash Communication Server.
• For information about accessing web services with Flash applications, see Using Flash Remoting.
The Macromedia DevNet website (www.macromedia.com/devnet) is updated regularly with the
latest information on Flash, plus advice from expert users, advanced topics, examples, tips, and
other updates. Check the website often for the latest news on Flash and how to get the most out
of the program.
The Macromedia Flash Support Center (www.macromedia.com/support/flash) provides
TechNotes, documentation updates, and links to additional resources in the Flash community.
10Introduction: Getting Started with ActionScript
PART I
Welcome to ActionScript
This part includes basic information on the ActionScript language.
Chapter 1 includes information on what is new or changed in ActionScript and Flash Player 7. If
you have used ActionScript before, be sure to review this information carefully.
If you are new to ActionScript, read Chapters 2 and 3 to get a good foundation for understanding
ActionScript terminology and syntax and for learning how to write and debug your scripts.
Macromedia Flash MX 2004 and Macromedia Flash MX Professional 2004 provide several
enhancements that make it easier for you to write more robust scripts using the ActionScript
language. These new features, which are discussed in this chapter, include new language elements,
improved editing and debugging tools (see “ActionScript editor changes” on page 21 and
“Debugging changes” on page 22), and the introduction of a more object-oriented programming
model (see “New object-oriented programming model” on page 22).
This chapter also contains an extensive section that you should read carefully if you plan to
publish any of your existing Flash MX or earlier files to Flash Player 7 (see “Porting existing
scripts to Flash Player 7” on page 15).
New and changed language elements
This section describes the ActionScript language elements that are new or changed in Flash MX
2004. To use any of these elements in your scripts, you must target Flash Player 7 (the default)
when you publish your documents.
• The Array.sort() and Array.sortOn() methods let you add parameters to specify
additional sorting options, such as ascending and descending sorting, whether to consider case
sensitivity when sorting, and so on.
• The Button.menu, MovieClip.menu, and TextField.menu properties work with the new
ContextMenu and ContextMenuItem classes to let you associate context menu items with
Button, MovieClip, or TextField objects.
• The ContextMenu class and ContextMenuItem class let you customize the context menu that
is displayed when a user right-clicks (Microsoft Windows) or Control-clicks (Macintosh) in
Flash Player.
• The Error class and the throw and try..catch..finally commands let you implement
more robust exception handling.
• The LoadVars.addRequestHeader() and XML.addRequestHeader() methods add or change
HTTP request headers (such as
Content-Type or SOAPAction) sent with POST actions.
• The MMExecute() function lets you issue Flash JavaScript API commands from ActionScript.
• (Windows only) The Mouse.onMouseWheel event listener is generated when the user scrolls
using the mouse wheel.
13
• The MovieClip.getNextHighestDepth() method lets you create MovieClip instances at
runtime and be guaranteed that their objects render in front of the other objects in a parent
movie clip’s z-order space. The
dynamically created MovieClip instances using the depth as a search index.
MovieClip.getInstanceAtDepth() method lets you access
• The MovieClip.getSWFVersion() method lets you determine which version of Flash Player
is supported by a loaded SWF file.
• The MovieClip.getTextSnapshot() method and the TextSnapshot object let you work with
text that is in static text fields in a movie clip.
• The MovieClip._lockroot property lets you specify that a movie clip will act as _root for
any movie clips loaded into it, or that the meaning of
that movie clip is loaded into another movie clip.
_root in a movie clip won’t change if
• The MovieClipLoader class lets you monitor the progress of files as they are being loaded into
movie clips.
• The NetConnection class and NetStream class let you stream local video files (FLV files).
• The PrintJob class gives you (and the user) more control over printing from Flash Player.
• The Sound.onID3 event handler provides access to ID3 data associated with a Sound object
that contains an MP3 file.
• The Sound.ID3 property provides access to the metadata that is part of an MP3 file.
• The System class has new objects and methods, and the System.capabilities object has several
new properties.
• The TextField.condenseWhite property lets you remove extra white space from HTML text
fields that are rendered in a browser.
• The TextField.mouseWheelEnabled property lets you specify whether a text field’s contents
should scroll when the mouse pointer is positioned over a text field and the user rolls the
mouse wheel.
• The TextField.StyleSheet class lets you create a style sheet object that contains text formatting
rules such as font size, color, and other formatting styles.
• The TextField.styleSheet property lets you attach a style sheet object to a text field.
• The TextFormat.getTextExtent() method accepts a new parameter, and the object it
returns contains a new member.
• The XML.addRequestHeader() method lets you add or change HTTP request headers (such
as
Content-Type or SOAPAction) sent with POST actions.
New security model and legacy SWF files
Rules for how Flash Player determines whether two domains are the same have changed in Flash
Player 7. In addition, rules that determine whether and how a SWF file served from an HTTP
domain can access a SWF file or load data from an HTTPS domain have changed. In most cases,
these changes won’t affect you unless you are porting your existing SWF files to Flash Player 7.
However, if you have SWF files published for Flash Player 6 or earlier that load data from a file
stored on a server, and the calling SWF is playing in Flash Player 7, the user might see a dialog
box that didn’t appear before, asking whether to allow access. You can prevent this dialog box
from appearing by implementing a policy file on the site where the data is stored. For more
information on this dialog box, see “About compatibility with previous Flash Player security
models” on page 191.
14Chapter 1: What’s New in Flash MX 2004 ActionScript
You might also need to implement a policy file if you are using runtime shared libraries. If either
the loading or loaded SWF file is published for Flash Player 7 and the loading and loaded files
aren’t served from the exact same domain, use a policy file to permit access. For more information
on policy files, see “About allowing cross-domain data loading” on page 190.
Porting existing scripts to Flash Player 7
As with any new release, Flash Player 7 supports more ActionScript commands than previous
versions of the player; you can use these commands to implement more robust scripts. (See “New
and changed language elements” on page 13.)However, if you used any of these commands in
your existing scripts, the script might not work correctly if you publish it for Flash Player 7.
For example, if you have a script with a function named Error, the script might appear to compile
correctly but might not run as expected in Flash Player 7, because Error is now a built-in class
(and thus a reserved word) in ActionScript. You can fix your script by renaming the Error
function to something else, such as ErrorCondition.
Also, Flash Player 7 implements a number of changes that affect how one SWF file can access
another SWF file, how external data can be loaded, and how local settings and data (such as
privacy settings and locally persistent shared objects) can be accessed. Finally, the behavior of
some existing features has changed.
If you have existing scripts written for Flash Player 6 or earlier that you want to publish for Flash
Player 7, you might need to modify the scripts so they conform with the implementation of Flash
Player 7 and work as designed. These modifications are discussed in this section.
ECMA-262 Edition 4 compliance
Several changes have been implemented in Flash Player 7 to conform more closely to the
ECMA-262 Edition 4 proposal (see www.mozilla.org/js/language/es4/index.html). In addition to
the class-based programming techniques available in ActionScript 2.0 (see “New object-oriented
programming model” on page 22), other features have been added and certain behaviors have
changed. Also, when publishing for Flash Player 7 and using ActionScript 2.0, you can cast one
object type to another. For more information, see “Casting objects” on page 39. These capabilities
don’t require you to update existing scripts; however, you may want to use them if you publish
your scripts to Flash Player 7 and then continue to revise and enhance them.
Porting existing scripts to Flash Player 715
Unlike the changes mentioned above, the changes listed in the following table (some of which
also improve ECMA compliance) may cause existing scripts to work differently than they did
previously. If you used these features in existing scripts that you want to publish to Flash Player 7,
review the changes to make sure your code still works as intended or to determine whether you
need to rewrite your code. In particular, because
undefined is evaluated differently in certain
cases, you should initialize all variables in scripts that you port to Flash Player 7.
SWF file published for Flash Player 7SWF file published for earlier versions of
Flash Player
Case sensitivity is supported (variable names that
differ only in capitalization are interpreted as being
different variables). This change also affects files
loaded with
with
LoadVars.load(). For more information, see
#include and external variables loaded
“Case sensitivity” on page 29.
Evaluating
NaN.
myCount +=1;
trace(myCount); // NaN
undefined in a numeric context returns
When undefined is converted to a string, the result is
16Chapter 1: What’s New in Flash MX 2004 ActionScript
Domain-name rules for settings and local data
In Flash Player 6, superdomain matching rules are used by default when accessing local settings
(such as camera or microphone access permissions) or locally persistent data (shared objects).
That is, the settings and data for SWF files hosted at here.xyz.com, there.xyz.com, and xyz.com
are shared, and are all stored at xyz.com.
In Flash Player 7, exact-domain matching rules are used by default. That is, the settings and data
for a file hosted at here.xyz.com are stored at here.xyz.com, the settings and data for a file hosted
at there.xyz.com are stored at there.xyz.com, and so on.
A new property,
System.exactSettings, lets you specify which rules to use. This property is
supported for files published for Flash Player 6 or later. For files published for Flash Player 6, the
default value is
Flash Player 7, the default value is
false, which means superdomain matching rules are used. For files published for
true, which means exact-domain matching rules are used.
If you use settings or persistent local data and want to publish a Flash Player 6 SWF file for Flash
Player 7, you might need to set this value to
For more information, see
System.exactSettings on page 662.
false in the ported file.
Cross-domain and subdomain access between SWF files
When you develop a series of SWF files that communicate with each other—for example, when
using
loadMovie(), MovieClip.loadMovie(), MovieClipLoader.LoadClip(), or Local
Connection objects—you might host the movies in different domains, or in different subdomains
of a single superdomain.
In files published for Flash Player 5 or earlier, there were no restrictions on cross-domain or
subdomain access.
In files published for Flash Player 6, you could use the
or
System.security.allowDomain() method to specify permitted cross-domain access (for
LocalConnection.allowDomain handler
example, to let a file at someSite.com be accessed by a file at someOtherSite.com), and no
command was needed to permit subdomain access (for example, a file at www.someSite.com
could be accessed by a file at store.someSite.com).
Files published for Flash Player 7 implement access between SWF files differently from earlier
versions in two ways. First, Flash Player 7 implements exact-domain matching rules instead of
superdomain matching rules. Therefore, the file being accessed (even if it is published for a Player
version earlier than Flash Player 7) must explicitly permit cross-domain or subdomain access; this
topic is discussed below. Second, a file hosted at a site using a secure protocol (HTTPS) must
explicitly permit access from a file hosted at a site using an insecure protocol (HTTP or FTP);
this topic is discussed in the next section (see “HTTP to HTTPS protocol access between SWF
files” on page 19).
Porting existing scripts to Flash Player 717
Because Flash Player 7 implements exact-domain matching rules instead of superdomain
matching rules, you might have to modify existing scripts if you want to access them from files
that are published for Flash Player 7. (You can still publish the modified files for Flash Player 6.)
If you used any
LocalConnection.allowDomain() or System.security.allowDomain()
statements in your files and specified superdomain sites to permit, you must change your
parameters to specify exact domains instead. The following code shows an example of the kinds of
changes you might have to make:
// Flash Player 6 commands in a SWF file at www.anyOldSite.com
// to allow access by SWF files that are hosted at www.someSite.com
// or at store.someSite.com
System.security.allowDomain("someSite.com");
my_lc.allowDomain = function(sendingDomain) {
return(sendingDomain=="someSite.com");
}
// Corresponding commands to allow access by SWF files
// that are published for Flash Player 7
System.security.allowDomain("www.someSite.com", "store.someSite.com");
my_lc.allowDomain = function(sendingDomain) {
return(sendingDomain=="www.someSite.com" ||
sendingDomain=="store.someSite.com");
}
You might also have to add statements like these to your files if you aren’t currently using them.
For example, if your SWF file is hosted at www.someSite.com and you want to allow access by a
SWF file published for Flash Player 7 at store.someSite.com, you must add statements like the
following to the file at www.someSite.com (you can still publish the file at www.someSite.com for
Flash Player 6):
To summarize, you might have to modify your files to add or change allowDomain statements if
you publish files for Flash Player 7 that meet the following conditions:
• You implemented cross-SWF scripting (using loadMovie(), MovieClip.loadMovie(),
MovieClipLoader.LoadClip(), or Local Connection objects).
• The called SWF file (of any version) is not hosted at a site using a secure protocol (HTTPS), or
the calling and called SWF files are both hosted at HTTPS sites. (If only the called SWF file is
HTTPS, see “HTTP to HTTPS protocol access between SWF files” on page 19.)
• The SWF files are not in same domain (for example, one file is at www.domain.com and one is
at store.domain.com).
18Chapter 1: What’s New in Flash MX 2004 ActionScript
You have to make the following changes:
• If the called SWF file is published for Flash Player 7, include System.security.allowDomain
or
LocalConnection.allowDomain in the called SWF file, using exact domain-
name matching.
• If the called SWF file is published for Flash Player 6, modify the called file to add or change a
System.security.allowDomain or LocalConnection.allowDomain statement, using exact
domain-name matching, as shown in the code examples earlier in this section. You can publish
the modified file for either Flash Player 6 or 7.
• If the called SWF file is published for Flash Player 5 or earlier, port the called file to
Flash Player 6 or 7 and add a
domain-name matching, as shown in the code examples earlier in this section.
(LocalConnection objects aren’t supported in Flash Player 5 or earlier.)
HTTP to HTTPS protocol access between SWF files
As discussed in the previous section, rules for cross-domain and subdomain access have changed
in Flash Player 7. In addition to the exact-domain matching rules now being implemented, you
must explicitly permit files hosted at sites using a secure protocol (HTTPS) to be accessed by files
hosted at sites using an insecure protocol. Depending on whether the called file is published for
Flash Player 7 or Flash Player 6, you must implement either one of the
(see “Cross-domain and subdomain access between SWF files” on page 17), or use the new
LocalConnection.allowInsecure Domain or System.security.allowInsecureDomain()
statements.
System.security.allowDomain statement, using exact
allowDomain statements
Warning: Implementing an allowInsecureDomain() statement compromises the security offered
by the HTTPS protocol. You should make these changes only if you can’t reorganize your site so that
all SWF files are served from the HTTPS protocol.
The following code shows an example of the kinds of changes you might have to make:
// Commands in a Flash Player 6 SWF file at https://www.someSite.com
// to allow access by Flash Player 7 SWF files that are hosted
// at http://www.someSite.com or at http://www.someOtherSite.com
System.security.allowDomain("someOtherSite.com");
my_lc.allowDomain = function(sendingDomain) {
return(sendingDomain=="someOtherSite.com");
}
// Corresponding commands in a Flash Player 7 SWF file
// to allow access by Flash Player 7 SWF files that are hosted
// at http://www.someSite.com or at http://www.someOtherSite.com
System.security.allowInsecureDomain("www.someSite.com",
You might also have to add statements like these to your files if you aren’t currently using them.
A modification might be necessary even if both files are in same domain (for example, a file in
http://www.domain.com is calling a file in https://www.domain.com).
Porting existing scripts to Flash Player 719
To summarize, you might have to modify your files to add or change statements if you publish
files for Flash Player 7 that meet the following conditions:
• You implemented cross-SWF scripting (using loadMovie(), MovieClip.loadMovie(),
MovieClipLoader.LoadClip(), or Local Connection objects).
• The calling file is not hosted using an HTTPS protocol, and the called file is HTTPS.
You must make the following changes:
• If the called file is published for Flash Player 7, include
System.security.allowInsecureDomain or LocalConnection.allowInsecureDomain in
the called file, using exact domain-name matching, as shown in the code examples earlier in
this section. This statement is required even if the calling and called SWF files are in
same domain.
• If the called file is published for Flash Player 6 or earlier, and both the calling and called files
are in same domain (for example, a file in http://www.domain.com is calling a file in https://
www.domain.com), no modification is needed.
• If the called file is published for Flash Player 6, the files are not in same domain, and you don’t
want to port the called file to Flash Player 7, modify the called file to add or change a
System.security.allowDomain or LocalConnection.allowDomain statement, using exact
domain-name matching, as shown in the code examples earlier in this section.
• If the called file is published for Flash Player 6 and you want to port the called file to Flash
Player 7, include
LocalConnection.allowInsecureDomain in the called file, using exact domain-name
matching, as shown in the code examples earlier in this section. This statement is required even
if both files are in same domain.
System.security.allowInsecureDomain or
• If the called file is published for Flash Player 5 or earlier, and both files are not in the same
domain, you can do one of two things. You can either port the called file to Flash Player 6 and
add or change a
matching, as shown in the code examples earlier in this section, or you can port the called file
to Flash Player 7, and include a
called file, using exact domain-name matching, as shown in the code examples earlier in
this section.
System.security.allowDomain statement, using exact domain-name
System.security.allowInsecureDomain statement in the
Server-side policy files for permitting access to data
A Flash document can load data from an external source by using one of the following data
loading calls:
(NetServices.createGatewayConnection). Also, a SWF file can import runtime shared
libraries (RSLs), or assets defined in another SWF file, at runtime. By default, the data or RSL
must reside in the same domain as the SWF file that is loading that external data or media.
To make data and assets in runtime shared libraries available to SWF files in different domains,
you should use a cross-domain policy file. A cross-domain policy file is an XML file that provides a
way for the server to indicate that its data and documents are available to SWF files served from
certain domains, or from all domains. Any SWF file that is served from a domain specified by the
server’s policy file is permitted to access data or RSLs from that server.
20Chapter 1: What’s New in Flash MX 2004 ActionScript
, XMLSocket.connect(), and Macromedia Flash Remoting
If you are loading external data, you should create policy files even if you don’t plan to port any of
your files to Flash Player 7. If you are using RSLs, you should create policy files if either the
calling or called file is published for Flash Player 7.
For more information, see “About allowing cross-domain data loading” on page 190.
ActionScript editor changes
The ActionScript editor has been updated in a number of ways to make it more robust and easier
to use. These changes are summarized in this section.
Word wrapping You can now use the Options pop-up menu in the Script pane, Debugger
panel, and Output panel to enable or disable word wrapping. You can also toggle word wrapping
using the pop-up menu in the Actions panel. The keyboard shortcut is Control+Shift+W
(Windows) or Command+Shift+W (Macintosh).
Viewing context-sensitive help When your pointer is positioned over an ActionScript
language element in the Actions toolbox or in the Script pane, you can use the View Help item in
the context menu to display a help page about that element.
Importing scripts When you select Import Script from the pop-up menu in the Actions panel,
the imported script is copied into the script at the insertion point in your code file. In previous
versions of Flash, importing a script overwrote the contents of the existing script.
Single-click breakpoints To add a debugging breakpoint before a line of code in the Debugger
panel or the Script pane of the Actions panel, you can click in the left margin. In previous
versions of Flash, clicking in the left margin selected a line of code. The new way to select a line of
code is to Control-click (Windows) or Command-click (Macintosh).
Normal and expert modes no longer in Actions panel In previous versions of Flash, you could
work in the Actions panel either in normal mode, in which you filled in options and parameters
to create code, or in expert mode, in which you added commands directly into the Script pane. In
Flash MX 2004 and Flash MX Professional 2004, you can work in the Actions panel only by
adding commands directly to the Script pane. You can still drag commands from the Actions
toolbox into the Script pane or use the Add (+) button above the Script pane to add commands to
a script.
Pinning multiple scripts You can pin multiple scripts within a FLA file along the bottom of the
Script pane in the Actions panel. In previous versions of Flash, you could pin only one script at
atime.
Script navigator The left side of the Actions panel now contains two panes: the Actions toolbox
and a new Script navigator. The Script navigator is a visual representation of the structure of your
FLA file; you can navigate through your FLA file here to locate ActionScript code.
Integrated Script window for editing external files (Flash Professional only) You can use the
ActionScript editor in a Script window (separate from the Actions panel) to write and edit
external script files. Syntax coloring, code hinting, and other preferences are supported in the
Script window, and the Actions toolbox is also available. To display the Script window, use
File > New and then select the type of external file you want to edit. You can have multiple
external files open at the same time; filenames are displayed on tabs across the top of the Script
window. (The tabs appear only in Windows.)
ActionScript editor changes21
Debugging changes
This section describes changes that improve your ability to debug your scripts.
Output window changed to Output panel You can now move and dock the Output panel in
the same way as any other panel in Flash.
Improved error reporting at compile time In addition to providing more robust exception
handling, ActionScript 2.0 provides a number of new compile-time errors. For more information,
see Appendix A, “Error Messages,” on page 783.
Improved exception handlingThe Error class and the throw and try..catch..finally
commands let you implement more robust exception handling.
New object-oriented programming model
The ActionScript language has grown and developed since its introduction several years ago. With
each new release of Flash, additional keywords, objects, methods, and other language elements
have been added to the language. However, unlike earlier releases of Flash, Flash MX 2004 and
Flash MX Professional 2004 introduce several new language elements that implement objectoriented programming in a more standard way than before. Because these language elements
represent a significant enhancement to the core ActionScript language, they represent a new
version of ActionScript itself: ActionScript 2.0.
ActionScript 2.0 is not a new language. Rather, it comprises a core set of language elements that
make it easier to develop object-oriented programs. With the introduction of keywords such as
class, interface, extends, and implements, ActionScript syntax is now easier to learn for
programmers familiar with other languages. New programmers can learn more standard
terminology that they can apply to other object-oriented languages they may study in the future.
ActionScript 2.0 supports all the standard elements of the ActionScript language; it simply
enables you to write scripts that more closely adhere to standards used in other object-oriented
languages, such as Java. ActionScript 2.0 should be of interest primarily to intermediate or
advanced Flash developers who are building applications that require the implementation of
classes and subclasses. ActionScript 2.0 also lets you declare the object type of a variable when you
create it (see “Strict data typing” on page 38) and provides significantly improved compiler errors
(see Appendix A, “Error Messages,” on page 783).
The language elements that are new in ActionScript 2.0 are listed below.
• class
• extends
• implements
• interface
• dynamic
• static
• public
• private
• get
• set
• import
22Chapter 1: What’s New in Flash MX 2004 ActionScript
Key facts about ActionScript 2.0 include the following points:
• Scripts that use ActionScript 2.0 to define classes or interfaces must be stored as external script
files, with a single class defined in each script; that is, classes and interfaces cannot be defined
in the Actions panel.
• You can import individual class files implicitly (by storing them in a location specified by
global or document-specific search paths and then using them in a script) or explicitly (by
using the
import command); you can import packages (collections of class files in a directory)
by using wildcards.
• Applications developed with ActionScript 2.0 are supported by Flash Player 6 and later.
Caution: The default publish setting for new files created in Flash MX 2004 is ActionScript 2.0. If
you plan to modify an existing FLA file to use ActionScript 2
specifies ActionScript 2
although Flash will not generate compiler errors.
.0 in its publish settings. If it does not, your file will compile incorrectly,
For more information on using ActionScript 2.0 to write object-oriented programs in Flash, see
Chapter 9, “Creating Classes with ActionScript 2.0,” on page 155.
.0 syntax, ensure that the FLA file
New object-oriented programming model23
24Chapter 1: What’s New in Flash MX 2004 ActionScript
CHAPTER 2
ActionScript Basics
ActionScript has rules of grammar and punctuation that determine which characters and words
are used to create meaning and in which order they can be written. For example, in English, a
period ends a sentence. In ActionScript, a semicolon ends a statement.
The following general rules apply to all ActionScript. Most ActionScript terms also have
individual requirements; for the rules for a specific term, see its entry in Chapter 12,
“ActionScript Dictionary,” on page 205.
Differences between ActionScript and JavaScript
ActionScript is similar to the core JavaScript programming language. You don’t need to know
JavaScript to use and learn ActionScript; however, if you know JavaScript, ActionScript will
appear familiar.
This manual does not attempt to teach general programming. There are many resources that
provide more information about general programming concepts and the JavaScript language.
• The European Computers Manufacturers Association (ECMA) document ECMA-262 is
derived from JavaScript and serves as the international standard for the JavaScript language.
ActionScript is based on the ECMA-262 specification.
• Netscape DevEdge Online has a JavaScript Developer Central site (http://
developer.netscape.com/tech/javascript/index.html) that contains documentation and articles
useful for understanding ActionScript. The most valuable resource is the Core JavaScript Guide.
Some of the differences between ActionScript and JavaScript are as follows:.
• ActionScript does not support browser-specific objects such as Document, Window,
and Anchor.
• ActionScript does not completely support all the JavaScript built-in objects.
• ActionScript does not support some JavaScript syntax constructs, such as statement labels.
• In ActionScript, the eval() action can perform only variable references.
25
Unicode support for ActionScript
Macromedia Flash MX 2004 and Macromedia Flash MX Professional 2004 support Unicode text
encoding for ActionScript. This means that you can include text in different languages in an
ActionScript file. For example, you could include text in English, Japanese, and French in the
same file.
You can set ActionScript preferences to specify the type of encoding to use when importing or
exporting ActionScript files. You can select either UTF-8 encoding or Default Encoding. UTF-8
is 8-bit Unicode format; Default Encoding is the encoding form supported by the language your
system is currently using, also called the traditional code page.
In general, if you are importing or exporting ActionScript files in UTF-8 format, use the UTF-8
preference. If you are importing or exporting files in the traditional code page in use on your
system, use the Default Encoding preference.
If text in your scripts doesn’t look as expected when you open or import a file, change the import
encoding preference. If you receive a warning message when exporting ActionScript files, you can
change the export encoding preference or turn this warning off in ActionScript preferences.
To select text encoding options for importing or exporting ActionScript files:
1 In the Preferences dialog box (Edit > Preferences), click the ActionScript tab.
2 Under Editing Options, do one or both of the following:
■ For Open/Import, select UTF-8 to open or import using Unicode encoding, or select
Default Encoding to open or import using the encoding form of the language currently
used by your system.
■ For Save/Export, select UTF-8 to save or export using Unicode encoding, or select Default
Encoding to save or export using the encoding form of the language currently used by your
system.
To turn the export encoding warning off or on:
1 In the Preferences dialog box (Edit > Preferences), click the Warnings tab.
2 Select or deselect Warn on Encoding Conflicts When Exporting .as Files.
Caution: The Test Movie command (see “Debugging your scripts” on page 68) will fail if any part of
the SWF file path has characters that cannot be represented using the MBCS encoding scheme. For
example, Japanese paths on an English system will not work. All areas of the application that use the
external player are subject to this limitation.
Terminology
As with any scripting language, ActionScript uses its own terminology. The following list provides
an introduction to important ActionScript terms.
Actions are statements that instruct a SWF file to do something while it is playing. For example,
gotoAndStop() sends the playhead to a specific frame or label. In this manual, the terms action
and statement are interchangeable.
Boolean is a true or false value.
Classes are data types that you can create to define a new type of object. To define a class,
you use the
Actions panel).
class keyword in an external script file (not in a script you are writing in the
26Chapter 2: ActionScript Basics
Constants are elements that don’t change. For example, the constant Key.TAB always has the
same meaning: it indicates the Tab key on a keyboard. Constants are useful for comparing values.
Constructors are functions that you use to define the properties and methods of a class.
By definition, constructors are functions within a class definition that have the same name
as the class. For example, the following code defines a Circle class and implements a
constructor function:
// file Circle.as
class Circle {
private var radius:Number
private var circumference:Number
// constructor
function Circle(radius:Number) {
circumference = 2 * Math.PI * radius;
}
}
The term constructor is also used when you create (instantiate) an object based on a particular
class. The following statements are constructors for the built-in Array class and the custom
Circle class:
my_array:Array = new Array();
my_circle:Circle = new Circle();
Data types
describe the kind of information a variable or ActionScript element can hold. The
ActionScript data types are String, Number, Boolean, Object, MovieClip, Function, null, and
undefined. For more information, see “About data types” on page 34.
Events are actions that occur while a SWF file is playing. For example, different events are
generated when a movie clip loads, the playhead enters a frame, the user clicks a button or movie
clip, or the user types on the keyboard.
Event handlers are special actions that manage events such as mouseDown or load. There are two
kinds of ActionScript event handlers: event handler methods and event listeners. (There are also
two event handlers,
on() and onClipEvent(), that you can assign directly to buttons and movie
clips.) In the Actions toolbox, each ActionScript object that has event handler methods or event
listeners has a subcategory called Events or Listeners. Some commands can be used both as event
handlers and as event listeners and are included in both subcategories.
Expressions are any legal combination of ActionScript symbols that represent a value. An
expression consists of operators and operands. For example, in the expression x + 2, x and 2 are
operands and
Functions are blocks of reusable code that can be passed parameters and can return a value. For
+ is an operator.
more information, see “Creating functions” on page 51.
Identifiers are names used to indicate a variable, property, object, function, or method. The first
character must be a letter, underscore (
_), or dollar sign ($). Each subsequent character must be a
letter, number, underscore, or dollar sign. For example, firstName is the name of a variable.
Instances are objects that belong to a certain class. Each instance of a class contains all the
properties and methods of that class. For example, all movie clips are instances of the MovieClip
class, so you can use any of the methods or properties of the MovieClip class with any movie
clip instance.
Terminology27
Instance names are unique names that let you target movie clip and button instances in scripts.
You use the Property inspector to assign instance names to instances on the Stage. For example, a
master symbol in the library could be called
the SWF file could have the instance names
following code sets a variable called
score inside each movie clip instance by using
counter and the two instances of that symbol in
scorePlayer1_mc and scorePlayer2_mc. The
You can use special suffixes when naming instances so that code hints (see “Using code hints”
on page 63) appear as you type your code. For more information, see “Using suffixes to trigger
code hints” on page 62.
Keywords are reserved words that have special meaning. For example, var is a keyword used to
declare local variables. You cannot use a keyword as an identifier. For example,
var is not a legal
variable name. For a list of keywords, see “Keywords” on page 33.
Methods are functions associated with a class. For example, getBytesLoaded() is a built-in
method associated with the MovieClip class. You can also create functions that act as methods,
either for objects based on built-in classes or for objects based on classes that you create. For
example, in the following code,
clear() becomes a method of a controller object that you
are collections of properties and methods; each object has its own name and is an
instance of a particular class. Built-in objects are predefined in the ActionScript language. For
example, the built-in Date object provides information from the system clock.
Operators are terms that calculate a new value from one or more values. For example, the
addition (
+) operator adds two or more values together to produce a new value. The values that
operators manipulate are called operands.
Parameters (also called arguments) are placeholders that let you pass values to functions.
For example, the following
firstName and hobby:
function welcome(firstName, hobby) {
welcomeText = "Hello, " + firstName + "I see you enjoy " + hobby;
}
Packages
are directories that contain one or more class files, and reside in a designated classpath
welcome() function uses two values it receives in the parameters
directory (see “Understanding the classpath” on page 169).
Properties are attributes that define an object. For example, _visible is a property of all movie
clips that defines whether a movie clip is visible or hidden.
28Chapter 2: ActionScript Basics
Target paths are hierarchical addresses of movie clip instance names, variables, and objects in a
SWF file. You name a movie clip instance in the movie clip Property inspector. (The main
Timeline always has the name
_root.) You can use a target path to direct an action at a movie clip
or to get or set the value of a variable. For example, the following statement is the target path to
the variable
_root.stereoControl.volume
volume inside the movie clip stereoControl:
For more information on target paths, see “Absolute and relative target paths” in Using Flash
Help.
Variables are identifiers that hold values of any data type. Variables can be created, changed, and
updated. The values they store can be retrieved for use in scripts. In the following example, the
identifiers on the left side of the equal signs are variables:
var x = 5;
var name = "Lolo";
var c_color = new Color(mcinstanceName);
For more information on variables, see “About variables” on page 40.
Syntax
As with any language, ActionScript has syntax rules that you must follow in order to create scripts
that can compile and run correctly. This section describes the elements that comprise
ActionScript syntax.
Case sensitivity
In a case-sensitive programming language, variable names that differ only in case (
book and Book)
are considered different from each other. Therefore, it’s good practice to follow consistent
capitalization conventions, such as those used in this manual, to make it easy to identify names of
functions and variables in ActionScript code.
When you publish files for Flash Player 7 or later, Flash implements case sensitivity whether you
are using ActionScript 1 or ActionScript 2.0. This means that keywords, class names, variables,
method names, and so on are all case sensitive. For example:
// In file targeting Flash Player 7
// and either ActionScript 1 or ActionScript 2.0
//
// Sets properties of two different objects
cat.hilite = true;
CAT.hilite = true;
// Creates three different variables
var myVar=10;
var myvar=10;
var mYvAr=10;
// Does not generate an error
var array = new Array();
var date = new Date();
This change also affects external variables loaded with LoadVars.load().
Syntax29
In addition, case sensitivity is implemented for external scripts, such as ActionScript 2.0 class files
or scripts that you import using the
#include command. If you are publishing files for Flash
Player 7 and have previously created external files that you add to your scripts by using the
#include statement, you should review each file and confirm that you used consistent
capitalization throughout. One way to do this is to open the file in the Script window (Flash
Professional only) or, in a new FLA file, set your publish settings to Flash Player 7 and copy the
file’s contents into the Actions panel. Then use the Check Syntax button (see “Checking syntax
and punctuation” on page 66) or publish your file; errors that are caused by naming conflicts
appear in the Output panel.
When Syntax coloring is enabled, language elements written with correct capitalization are blue
by default. For more information, see “Keywords” on page 33 and “Syntax highlighting”
on page 61.
Dot syntax
In ActionScript, a dot (
.) is used to indicate the properties or methods related to an object or
movie clip. It is also used to identify the target path to a movie clip, variable, function, or object.
A dot syntax expression begins with the name of the object or movie clip followed by a dot, and
ends with the element you want to specify.
For example, the
expression
As another example,
movie clip
variable of the instance
_x movie clip property indicates a movie clip’s x axis position on the Stage. The
ballMC._x refers to the _x property of the movie clip instance ballMC.
submit is a variable set in the form movie clip, which is nested inside the
shoppingCart. The expression shoppingCart.form.submit = true sets the submit
form to true.
Expressing a method of an object or movie clip follows the same pattern. For example, the
play() method of the ball_mc movie clip instance moves the playhead in the Timeline of
ball_mc, as shown in the following statement:
ball_mc.play();
Dot syntax also uses two special aliases, _root and _parent. The alias _root refers to the main
Timeline. You can use the
following statement calls the function
_root alias to create an absolute target path. For example, the
buildGameBoard() in the movie clip functions on the
main Timeline:
_root.functions.buildGameBoard();
You can use the alias _parent to refer to a movie clip in which the current object is nested. You
can also use _parent to create a relative target path. For example, if the movie clip dog_mc is
nested inside the movie clip
animal_mc to stop:
animal_mc, the following statement on the instance dog_mc tells
_parent.stop();
Slash syntax
Slash syntax was used in Flash 3 and 4 to indicate the target path of a movie clip or variable. This
syntax is still supported by Flash Player 7, but its use is not recommended, and slash syntax is not
supported in ActionScript 2.0. However, if you are creating content intended specifically for
Flash Player 4, you must use slash syntax. For more information, see “Using slash syntax”
on page 797.
30Chapter 2: ActionScript Basics
Curly braces
ActionScript event handlers, class definitions, and functions are grouped together into blocks
with curly braces (
{}). You can put the opening brace on the same line as your declaration or on
the next line, as shown in the following examples. To make your code easier to read, it’s a good
idea to choose one format and use it consistently.
// Event handler
on(release) {
myDate = new Date();
currentMonth = myDate.getMonth();
}
on(release)
{
myDate = new Date();
currentMonth = myDate.getMonth();
You can check for matching curly braces in your scripts; see “Checking syntax and punctuation”
on page 66.
Semicolons
An ActionScript statement is terminated with a semicolon (
var column = passedDate.getDay();
var row = 0;
;), as shown in these examples:
If you omit the terminating semicolon, Flash still compiles your script successfully. However,
using semicolons is good scripting practice.
Syntax31
Parentheses
When you define a function, place any parameters inside parentheses:
function myFunction (name, age, reader){
// your code here
}
When you call a function, include any parameters passed to the function in parentheses, as
shown here:
myFunction ("Steve", 10, true);
You can also use parentheses to override the ActionScript order of precedence or to make your
ActionScript statements easier to read. (See “Operator precedence and associativity” on page 45.)
You also use parentheses to evaluate an expression on the left side of a dot in dot syntax. For
example, in the following statement, the parentheses cause
new Color(this) to evaluate and
create a Color object:
onClipEvent(enterFrame) {
(new Color(this)).setRGB(0xffffff);
}
If you don’t use parentheses, you must add a statement to evaluate the expression:
onClipEvent(enterFrame) {
myColor = new Color(this);
myColor.setRGB(0xffffff);
}
You can check for matching parentheses in your scripts; see “Checking syntax and punctuation”
on page 66.
Comments
Using comments to add notes to scripts is highly recommended. Comments are useful for
keeping track of what you intended and for passing information to other developers if you work
in a collaborative environment or are providing samples. Even a simple script is easier to
understand if you make notes as you create it.
To indicate that a line or portion of a line is a comment, precede the comment with two forward
slashes (
on(release) {
}
//):
// create new Date object
myDate = new Date();
currentMonth = myDate.getMonth();
// convert month number to month name
monthName = calcMonth(currentMonth);
year = myDate.getFullYear();
currentDate = myDate.getDate();
When Syntax coloring is enabled (see “Syntax highlighting” on page 61), comments are gray by
default. Comments can be any length without affecting the size of the exported file, and they do
not need to follow rules for ActionScript syntax or keywords.
If you want to “comment out” an entire portion of your script, place it in a comment block rather
than adding
// at the beginning of each line. This technique is easier and is useful when you want
to test only parts of a script by commenting out large chunks of it.
32Chapter 2: ActionScript Basics
To create a comment block, place /* at the beginning of the commented lines and */ at the end.
For example, when the following script runs, none of the code in the comment block is executed:
// The code below runs
var x:Number = 15;
var y:Number = 20;
// The code below doesn’t run
/*
on(release) {
// create new Date object
myDate = new Date();
currentMonth = myDate.getMonth();
// convert month number to month name
monthName = calcMonth(currentMonth);
year = myDate.getFullYear();
currentDate = myDate.getDate();
}
*/
// The code below runs
var name:String = "My name is";
var age:Number = 20;
Keywords
ActionScript reserves words for specific use within the language, so you can’t use them
as identifiers, such as variable, function, or label names. The following table lists all
ActionScript keywords:
breakcaseclasscontinue
defaultdeletedynamicelse
extendsforfunctionget
ifimplementsimportin
instanceofinterfaceintrinsicnew
privatepublicreturnset
staticswitchthistypeof
varvoidwhilewith
Constants
A constant is a property whose value never changes.
For example, the constants
BACKSPACE, ENTER, QUOTE, RETURN, SPACE, and TAB are properties of
the Key object and refer to keyboard keys. To test whether the user is pressing the Enter key, you
could use the following statement:
if(Key.getCode() == Key.ENTER) {
alert = "Are you ready to play?";
controlMC.gotoAndStop(5);
}
Syntax33
About data types
A data type describes the kind of information a variable or ActionScript element can hold. There
are two kinds of data types built into Flash: primitive and reference. The primitive data types—
String, Number, and Boolean—have a constant value and therefore can hold the actual value of
the element they represent. The reference data types—MovieClip and Object—have values that
can change and therefore contain references to the actual value of the element. Variables
containing primitive data types behave differently in certain situations than those containing
reference types. (See “Using variables in a program” on page 43.) There are also two special data
types: null and undefined.
In Flash, any built-in object that isn’t a primitive data type or a movie clip data type, such as Array
or Math, is of the Object data type.
Each data type has its own rules and is described in the following topics:
• “String” on page 34
• “Number” on page 35
• “Boolean” on page 35
• “Object” on page 36
• “MovieClip” on page 36
• “Null” on page 36
• “Undefined” on page 36
When you debug scripts, you may need to determine the data type of an expression or variable to
understand why it is behaving a certain way. You can do this with the
“Determining an item’s data type” on page 37).
You can convert one data type to another using one of the following conversion functions:
Array(), Boolean(), Number(), Object(), String().
String
A string is a sequence of characters such as letters, numbers, and punctuation marks. You enter
strings in an ActionScript statement by enclosing them in single or double quotation marks.
Strings are treated as characters instead of as variables. For example, in the following statement,
"L7" is a string:
favoriteBand = "L7";
You can use the addition (+) operator to concatenate, or join, two strings. ActionScript treats
spaces at the beginning or end of a string as a literal part of the string. The following expression
includes a space after the comma:
greeting = "Welcome," + firstName;
typeof operator (see
34Chapter 2: ActionScript Basics
To include a quotation mark in a string, precede it with a backslash character (\). This is called
escaping a character. There are other characters that cannot be represented in ActionScript except
by special escape sequences. The following table provides all the ActionScript escape characters:
Escape sequenceCharacter
\b
\f
\n
\r
\t
\"
\'
\\
\000 - \377
\x00 - \xFF
\u0000 - \uFFFF
Backspace character (ASCII 8)
Form-feed character (ASCII 12)
Line-feed character (ASCII 10)
Carriage return character (ASCII 13)
Tab character (ASCII 9)
Double quotation mark
Single quotation mark
Backslash
A byte specified in octal
A byte specified in hexadecimal
A 16-bit Unicode character specified in hexadecimal
Number
The number data type is a double-precision floating-point number. You can manipulate numbers
using the arithmetic operators addition (
modulo (
%), increment (++), and decrement (--). You can also use methods of the built-in Math
and Number classes to manipulate numbers. The following example uses the
root) method to return the square root of the number 100:
Math.sqrt(100);
For more information, see “Numeric operators” on page 45.
Boolean
A Boolean value is one that is either
and
false to 1 and 0 when appropriate. Boolean values are most often used with logical
true or false. ActionScript also converts the values true
operators in ActionScript statements that make comparisons to control the flow of a script. For
example, in the following script, the SWF file plays if the variable
onClipEvent(enterFrame) {
if (userName == true && password == true){
play();
}
}
password is true:
See “Using built-in functions” on page 51 and “Logical operators” on page 47.
About data types35
Object
An object is a collection of properties. Each property has a name and a value. The value of a
property can be any Flash data type, even the object data type. This allows you to arrange objects
inside each other, or nest them. To specify objects and their properties, you use the dot (
operator. For example, in the following code,
is a property of
employee.weeklyStats.hoursWorked
employee:
hoursWorked is a property of weeklyStats, which
You can use the built-in ActionScript objects to access and manipulate specific kinds of
information. For example, the Math object has methods that perform mathematical operations
on numbers you pass to them. This example uses the
squareRoot = Math.sqrt(100);
sqrt() method:
The ActionScript MovieClip object has methods that let you control movie clip symbol instances
on the Stage. This example uses the
You can also create custom objects to organize information in your Flash application. To add
interactivity to an application with ActionScript, you’ll need many different pieces of
information: for example, you might need a user’s name, the speed of a ball, the names of items in
a shopping cart, the number of frames loaded, the user’s ZIP Code, or the key that was pressed
last. Creating custom objects lets you organize this information into groups, simplify your
scripting, and reuse your scripts.
.)
MovieClip
Movie clips are symbols that can play animation in a Flash application. They are the only data
type that refers to a graphic element. The MovieClip data type allows you to control movie clip
symbols using the methods of the MovieClip class. You call the methods using the dot (
operator, as shown here:
null value can be used in a variety of situations. Here are some examples:
null. This value means “no value”—that is, a lack of data.
• To indicate that a variable has not yet received a value
• To indicate that a variable no longer contains a value
• As the return value of a function, to indicate that no value was available to be returned by
the function
• As a parameter to a function, to indicate that a parameter is being omitted
Undefined
The undefined data type has one value,
assigned a value.
undefined, and is used for a variable that hasn’t been
.)
36Chapter 2: ActionScript Basics
Determining an item’s data type
While testing and debugging your programs, you may discover problems that seem to be related
to the data types of different items. In these cases, you may want to determine an item’s data type.
To do so, use the
trace(typeof(variableName));
typeof operator, as shown in this example:
For more information on testing and debugging, see Chapter 3, “Writing and Debugging
Scripts,” on page 55.
Assigning data types to elements
Flash automatically assigns data types to the following kinds of language elements, as discussed in
the next section, “Automatic data typing”:
• Variables
• Parameters passed to a function, method, or class
• Values returned from a function or method
• Objects created as subclasses of existing classes
However, you can also explicitly assign data types to items, which can help prevent or diagnose
certain errors in your scripts. For more information, see “Strict data typing” on page 38.
Automatic data typing
In Flash, you do not need to explicitly define an item as holding either a number, a string, or
other data type. Flash determines the data type of an item when it is assigned:
var x = 3;
In the expression var x = 3, Flash evaluates the element on the right side of the operator and
determines that it is of the number data type. A later assignment may change the type of
example, the statement
assigned a value has a type of
x = "hello" changes the type of x to a string. A variable that hasn’t been
undefined.
ActionScript converts data types automatically when an expression requires it. For example, when
you pass a value to the
trace() action, trace() automatically converts the value to a string and
sends it to the Output panel. In expressions with operators, ActionScript converts data types as
needed; for example, when used with a string, the
+ operator expects the other operand to be
astring.
"Next in line, number " + 7
ActionScript converts the number 7 to the string "7" and adds it to the end of the first string,
resulting in the following string:
"Next in line, number 7"
x; for
Assigning data types to elements37
Strict data typing
ActionScript 2.0 lets you explicitly declare the object type of a variable when you create it; this is
called strict data typing. Because data type mismatches trigger compiler errors, strict data typing
helps prevent you from assigning the wrong type of data to an existing variable. To assign a
specific data type to an item, specify its type using the
// strict typing of variable or object
var x:Number = 7;
var birthday:Date = new Date();
// strict typing of parameters
function welcome(firstName:String, age:Number){
}
// strict typing of parameter and return value
function square(x:Number):Number {
var squared = x*x;
return squared;
}
var keyword and post-colon syntax:
Because you must use the var keyword when strictly typing variable, you can’t strictly type a
global variable (see “Scoping and declaring variables” on page 41).
You can declare the data type of objects based on built-in classes (Button, Date, MovieClip, and
so on) and on classes and interfaces that you create. For example, if you have a file named
Student.as in which you define the Student class, you can specify that objects you create are of
type Student:
var student:Student = new Student();
You can also specify that objects are of type Function or Void.
Using strict typing helps ensure that you don’t inadvertently assign an incorrect type of value to an
object. Flash checks for typing mismatch errors at compile time. For example, suppose you type
the following code:
// in the Student.as class file
class Student {
var status:Boolean; // property of Student objects
}
// in a script
var studentMaryLago:Student = new Student();
studentMaryLago.status = "enrolled";
When Flash compiles this script, a “Type mismatch” error is generated.
Another advantage of strict data typing is that Flash MX 2004 automatically displays code hints
for built-in objects when they are strictly typed. For more information, see “Strictly typing objects
to trigger code hints” on page 62.
Files published using ActionScript 1 do not respect strict data typing assignments at compile
time. Thus, assigning the wrong type of value to a variable that you have strictly typed doesn’t
generate a compiler error.
var x:String = "abc"
x = 12 ; // no error in ActionScript 1, type mismatch error in ActionScript 2
38Chapter 2: ActionScript Basics
The reason for this is that when you publish a file for ActionScript 1, Flash interprets a statement
such as
var x:String = "abc" as slash syntax rather than as strict typing. (ActionScript 2.0
doesn’t support slash syntax.) This behavior can result in an object that is assigned to a variable of
the wrong type, causing the compiler to let illegal method calls and undefined property references
pass through unreported.
Therefore, if you are implementing strict data typing, make sure you are publishing files for
ActionScript 2.0.
Casting objects
ActionScript 2.0 lets you cast one data type to another. The cast operator that Flash uses takes the
form of a function call and is concurrent with explicit coercion, as specified in the ECMA-262
Edition 4 proposal. Casting lets you assert that an object is of a certain type so that when typechecking occurs, the compiler treats the object as having a set of properties that its initial type
does not contain. This can be useful, for example, when iterating over an array of objects that
might be of differing types.
In files published for Flash Player 7 or later, cast statements that fail at runtime return
null. In
files published for Flash Player 6, no runtime support for failed casts is implemented.
The syntax for casting is
of
item is type. Casting is essentially a function call, and the function call returns null if the cast
type(item), where you want the compiler to behave as if the data type
fails. If the cast succeeds, the function call returns the original object. However, the compiler
doesn’t generate type mismatch errors when you cast items to data types that you created in
external class files, even if the cast fails at runtime.
// in Animal.as
class Animal {}
// in Dog.as
class Dog extends Animal { function bark (){} }
// in Cat.as
class Cat extends Animal { function meow (){} }
// in FLA file
var spot:Dog = new Dog();
var temp:Cat = Cat (spot);// assert that a Dog object is of type Cat
temp.meow(); // doesn't do anything, but no compiler error either
In this situation, you asserted to the compiler that temp is a Cat object, and, therefore, the
compiler assumes that
temp.meow() is a legal statement. However, the compiler doesn’t know
that the cast will fail (that is, that you tried to cast a Dog object to a Cat type), so no compile-time
error occurs. If you include a check in your script to make sure that the cast succeeds, you can
find type mismatch errors at runtime.
var spot:Dog = new Dog();
var temp:Cat = Cat (spot);
trace(temp);// displays null at runtime
You can cast an expression to an interface. If the expression is an object that implements the
interface or has a base class that implements the interface, the object is returned. If not,
is returned.
null
Assigning data types to elements39
The following example shows the results of casting built-in object types. As the first line in the
with(results) block shows, an illegal cast—in this case, casting a string to a movie clip—
returns
var mc:MovieClip;
var arr:Array;
var bool:Boolean;
var num3:Number;
var obj:Object;
var str:String;
_root.createTextField("results",2,100,100,300,300);
with(results){
text = "type MovieClip : "+(typeof MovieClip(str));// returns null
text += "\ntype object : "+(typeof Object(str));// returns object
text += "\ntype Array : "+(typeof Array(num3));// returns object
text += "\ntype Boolean : "+(typeof Boolean(mc));// returns boolean
text += "\ntype String : "+(typeof String(mc));// returns string
text += "\ntype Number : "+(typeof Number(obj));// returns number
text += "\ntype Function : "+(typeof Function(mc));// returns object
text += "\ntype null : "+(typeof null(arr));// returns undefined
text += "\ntype undefined : "+(typeof undefined(obj));// returns undefined
}
//Results in Output panel
type MovieClip : null
type object : object
type Array : object
type Boolean : boolean
type String : string
type Number : number
type Function : object
type null : undefined
type undefined : undefined
null. As the last two lines show, casting to null or undefined returns undefined.
You can’t override primitive data types such as Boolean, Date, and Number with a cast operator of
the same name.
About variables
A variable is a container that holds information. The container itself is always the same, but the
contents can change. By changing the value of a variable as the SWF file plays, you can record and
save information about what the user has done, record values that change as the SWF file plays, or
evaluate whether a condition is true or false.
It’s a good idea always to assign a variable a known value the first time you define the variable.
This is known as initializing a variable and is often done in the first frame of the SWF file.
Initializing a variable helps you track and compare the variable’s value as the SWF file plays.
Variables can hold any type of data (see “About data types” on page 34). The type of data a
variable contains affects how the variable’s value changes when it is assigned in a script.
Typical types of information that you can store in a variable include a URL, a user’s name, the
result of a mathematical operation, the number of times an event occurred, or whether a button
has been clicked. Each SWF file and movie clip instance has a set of variables, with each variable
having a value independent of variables in other SWF files or movie clips.
40Chapter 2: ActionScript Basics
To test the value of a variable, use the trace() action to send the value to the Output panel. For
example,
trace(hoursWorked) sends the value of the variable hoursWorked to the Output panel
in test mode. You can also check and set the variable values in the Debugger in test mode. For
more information, see “Using the trace statement” on page 79 and “Displaying and modifying
variables” on page 72.
Naming a variable
A variable’s name must follow these rules:
• It must be an identifier (see “Terminology” on page 26).
• It cannot be a keyword or an ActionScript literal such as true, false, null, or undefined.
• It must be unique within its scope (see “Scoping and declaring variables” on page 41).
Also, you should not use any element in the ActionScript language as a variable name; doing so
can cause syntax errors or unexpected results. For example, if you name a variable
then try to create a String object using
hello_str = new String();
trace(hello_str.length); // returns 0
String = "hello"; // Giving a variable the same name as a built-in class
hello_str = new String();
trace(hello_str.length); // returns undefined
new String(), the new object is undefined.
String and
The ActionScript editor supports code hints for built-in classes and for variables that are based on
these classes. If you want Flash to provide code hints for a particular object type that is assigned to
a variable, you can strictly type the variable or name the variable using a specific suffix.
For example, suppose you type the following code:
var members:Array = new Array();
members.
As soon as you type the period (.), Flash displays a list of methods and properties available for
Array objects. For more information, see “Writing code that triggers code hints” on page 61.
Scoping and declaring variables
A variable’s scope refers to the area in which the variable is known and can be referenced. There are
three types of variable scope in ActionScript:
• Local variables are available within the function body in which they are declared (delineated by
curly braces).
• Timeline variables are available to any script on that Timeline.
• Global variables and functions are visible to every Timeline and scope in your document.
Note: ActionScript 2.0 classes that you create support public, private, and static variable scopes. For
more information, see “Controlling member access” on page 164 and “Creating class members”
on page 165.
About variables41
Local variables
To declare local variables, use the
var statement inside the body of a function. A local variable is
scoped to the block and expires at the end of the block. A local variable not declared within a
block expires at the end of its script.
For example, the variables
used as a local variable; it exists only inside the function
function makeDays() {
var i;
for( i = 0; i < monthArray[month]; i++ ) {
_root.Days.attachMovie( "DayDisplay", i, i + 2000 );
i and j are often used as loop counters. In the following example, i is
makeDays():
Local variables can also help prevent name conflicts, which can cause errors in your application.
For example, if you use
name as a local variable, you could use it to store a user name in one
context and a movie clip instance name in another; because these variables would run in separate
scopes, there would be no conflict.
It’s good practice to use local variables in the body of a function so that the function can act as an
independent piece of code. A local variable is only changeable within its own block of code. If an
expression in a function uses a global variable, something outside the function can change its
value, which would change the function.
You can assign a data type to a local variable when you define it, which helps prevent you from
assigning the wrong type of data to an existing variable. For more information, see “Strict data
typing” on page 38.
Timeline variables
Timeline variables are available to any script on that Timeline. To declare Timeline variables,
initialize them on any frame in the Timeline. Be sure to initialize the variable before trying to
access it in a script. For example, if you put the code
var x = 10; on Frame 20, a script attached
to any frame before Frame 20 cannot access that variable.
42Chapter 2: ActionScript Basics
Global variables
Global variables and functions are visible to every Timeline and scope in your document. To
create a variable with global scope, use the
not use the
var _global.myName = "George"; // syntax error
_global.myName = "George";
var = syntax. For example, the following code creates the global variable myName:
_global identifier before the variable name, and do
However, if you initialize a local variable with the same name as a global variable, you don’t have
access to the global variable while you are in the scope of the local variable:
_global.counter = 100;
counter++;
trace(counter); // displays 101
function count(){
You must declare a variable in a script before you can use it in an expression. If you use an
undeclared variable, as shown in the following example, the variable’s value will be
undefined, and your script might produce unintended results:
NaN or
var squared = x*x;
trace(squared); // NaN
var x = 6;
In the following example, the statement declaring the variable x must come first so that squared
can be replaced with a value:
var x = 6;
var squared = x*x;
trace(squared); // 36
Similar behavior occurs when you pass an undefined variable to a method or function:
getURL(myWebSite); // no action
var myWebSite = "http://www.macromedia.com";
var myWebSite = "http://www.macromedia.com";
getURL(myWebSite); // browser displays www.macromedia.com
You can change the value of a variable many times in a script. The type of data that the variable
contains affects how and when the variable changes. Primitive data types, such as strings and
numbers, are passed by value. This means that the actual content of the variable is passed to
the variable.
In the following example,
in line 3, the value of
x that it received in line 2.
x is set to 15 and that value is copied into y. When x is changed to 30
y remains 15 because y doesn’t look to x for its value; it contains the value of
var x = 15;
var y = x;
var x = 30;
About variables43
As another example, the variable inValue contains a primitive value, 3, so the actual value is
passed to the
function sqrt(x){
return x * x;
}
var inValue = 3;
var out = sqrt(inValue);
sqrt() function and the returned value is 9:
The value of the variable inValue does not change.
The object data type can contain such a large and complex amount of information that a variable
with this type doesn’t hold the actual value; it holds a reference to the value. This reference is like
an alias that points to the contents of the variable. When the variable needs to know its value,
the reference asks for the contents and returns the answer without transferring the value to
the variable.
The following is an example of passing by reference:
var myArray = ["tom", "josie"];
var newArray = myArray;
myArray[1] = "jack";
trace(newArray);
The above code creates an Array object called myArray that has two elements. The variable
newArray is created and is passed a reference to myArray. When the second element of myArray is
changed, it affects every variable with a reference to it. The
trace() action sends tom, jack to
the Output panel.
In the following example,
zeroArray() by reference. The zeroArray() function changes the content of the array
in
myArray.
function zeroArray (theArray){
var i;
for (i=0; i < theArray.length; i++) {
theArray[i] = 0;
}
}
var myArray = new Array();
myArray[0] = 1;
myArray[1] = 2;
myArray[2] = 3;
zeroArray(myArray);
myArray contains an Array object, so it is passed to function
The function zeroArray() accepts an Array object as a parameter and sets all the elements of
that array to 0. It can modify the array because the array is passed by reference.
44Chapter 2: ActionScript Basics
Using operators to manipulate values in expressions
An expression is any statement that Flash can evaluate and that returns a value. You can create an
expression by combining operators and values or by calling a function.
Operators are characters that specify how to combine, compare, or modify the values of an
expression. The elements that the operator performs on are called operands. For example, in the
following statement, the
foo; foo and 3 are the operands:
foo + 3
This section describes general rules about common types of operators, operator precedence, and
operator associativity. For detailed information on each operator mentioned here, as well as
special operators that don’t fall into these categories, see the entries in Chapter 12, “ActionScript
Dictionary,” on page 205.
Operator precedence and associativity
When two or more operators are used in the same statement, some operators take precedence over
others. ActionScript follows a precise hierarchy to determine which operators to execute first. For
example, multiplication is always performed before addition; however, items in parentheses take
precedence over multiplication. So, without parentheses, ActionScript performs the
multiplication in the following example first:
total = 2 + 4 * 3;
+ operator adds the value of a numeric literal to the value of the variable
The result is 14.
But when parentheses surround the addition operation, ActionScript performs the addition first:
total = (2 + 4) * 3;
The result is 18.
When two or more operators share the same precedence, their associativity determines the order
in which they are performed. Associativity can be either left-to-right or right-to-left. For example,
the multiplication operator has an associativity of left-to-right; therefore, the following two
statements are equivalent:
total = 2 * 3 * 4;
total = (2 * 3) * 4;
For a table of all operators and their precedence and associativity, see Appendix B, “Operator
Precedence and Associativity,” on page 787.
Numeric operators
Numeric operators add, subtract, multiply, divide, and perform other arithmetic operations.
The most common usage of the increment operator is
i++ instead of the more verbose i = i+1.
You can use the increment operator before or after an operand. In the following example,
incremented first and then tested against the number 30:
if (++age >= 30)
age is
In the following example, age is incremented after the test is performed:
if (age++ >= 30)
Using operators to manipulate values in expressions45
The following table lists the ActionScript numeric operators:
OperatorOperation performed
+
*
/
%
-
++
--
Addition
Multiplication
Division
Modulo (remainder of division)
Subtraction
Increment
Decrement
Comparison operators
Comparison operators compare the values of expressions and return a Boolean value (
false). These operators are most commonly used in loops and in conditional statements. In the
following example, if the variable
score is 100, a certain SWF file loads; otherwise, a different
SWF file loads:
if (score > 100){
loadMovieNum("winner.swf", 5);
} else {
loadMovieNum("loser.swf", 5);
}
The following table lists the ActionScript comparison operators:
true or
OperatorOperation performed
<
>
<=
>=
Less than
Greater than
Less than or equal
Greater than or equal
String operators
The
+ operator has a special effect when it operates on strings: it concatenates the two string
operands. For example, the following statement adds "Congratulations," to "Donna!":
"Congratulations, " + "Donna!"
The result is "Congratulations, Donna!" If only one of the + operator’s operands is a string,
Flash converts the other operand to a string.
The comparison operators
>, >=, <, and <= also have a special effect when operating on strings.
These operators compare two strings to determine which is first in alphabetical order.
The comparison operators only compare strings if both operands are strings. If only one of
the operands is a string, ActionScript converts both operands to numbers and performs a
numeric comparison.
46Chapter 2: ActionScript Basics
Logical operators
Logical operators compare Boolean values (
For example, if both operands evaluate to
one or both of the operands evaluate to
true and false) and return a third Boolean value.
true, the logical AND operator (&&) returns true. If
true, the logical OR operator (||) returns true. Logical
operators are often used with comparison operators to determine the condition of an
For example, in the following script, if both expressions are true, the
if (i > 10 && _framesloaded > 50){
play();
}
if action will execute:
The following table lists the ActionScript logical operators:
OperatorOperation performed
&&
||
!
Logical AND
Logical OR
Logical NOT
Bitwise operators
Bitwise operators internally manipulate floating-point numbers to change them into 32-bit
integers. The exact operation performed depends on the operator, but all bitwise operations
evaluate each binary digit (bit) of the 32-bit integer individually to compute a new value.
if action.
The following table lists the ActionScript bitwise operators:
OperatorOperation performed
&Bitwise AND
|Bitwise OR
^Bitwise XOR
~Bitwise NOT
<<Shift left
>>Shift right
>>>Shift right zero fill
Equality operators
You can use the equality (
operands are equal. This comparison returns a Boolean (
==) operator to determine whether the values or identities of two
true or false) value. If the operands are
strings, numbers, or Boolean values, they are compared by value. If the operands are objects or
arrays, they are compared by reference.
It is a common mistake to use the assignment operator to check for equality. For example, the
following code compares x to 2:
if (x == 2)
In that same example, the expression x = 2 is incorrect because it doesn’t compare the operands,
it assigns the value of 2 to the variable
x.
Using operators to manipulate values in expressions47
The strict equality (===) operator is like the equality operator, with one important difference: the
strict equality operator does not perform type conversion. If the two operands are of different
types, the strict equality operator returns
false. The strict inequality (!==) operator returns the
inversion of the strict equality operator.
The following table lists the ActionScript equality operators:
OperatorOperation performed
==
===
!=
!==
Equality
Strict equality
Inequality
Strict inequality
Assignment operators
You can use the assignment (
=) operator to assign a value to a variable, as shown in the
following example:
var password = "Sk8tEr";
You can also use the assignment operator to assign multiple variables in the same expression. In
the following statement, the value of
a = b = c = d;
a is assigned to the variables b, c,and d:
You can also use compound assignment operators to combine operations. Compound operators
perform on both operands and then assign the new value to the first operand. For example, the
following two statements are equivalent:
x += 15;
x = x + 15;
The assignment operator can also be used in the middle of an expression, as shown in the
following example:
// If the flavor is not vanilla, output a message.
if ((flavor = getIceCreamFlavor()) != "vanilla") {
trace ("Flavor was " + flavor + ", not vanilla.");
}
This code is equivalent to the following slightly more verbose code:
flavor = getIceCreamFlavor();
if (flavor != "vanilla") {
trace ("Flavor was " + flavor + ", not vanilla.");
}
The following table lists the ActionScript assignment operators:
OperatorOperation performed
=
+=
-=
*=
48Chapter 2: ActionScript Basics
Assignment
Addition and assignment
Subtraction and assignment
Multiplication and assignment
OperatorOperation performed
%=
/=
<<=
>>=
>>>=
^=
|=
&=
Modulo and assignment
Division and assignment
Bitwise shift left and assignment
Bitwise shift right and assignment
Shift right zero fill and assignment
Bitwise XOR and assignment
Bitwise OR and assignment
Bitwise AND and assignment
Dot and array access operators
You can use the dot operator (
.) and the array access operator ([]) to access built-in or custom
ActionScript object properties, including those of a movie clip.
The dot operator uses the name of an object on its left side and the name of a property or variable
on its right side. The property or variable name can’t be a string or a variable that evaluates to a
string; it must be an identifier. The following examples use the dot operator:
year.month = "June";
year.month.day = 9;
The dot operator and the array access operator perform the same role, but the dot operator takes
an identifier as its property, whereas the array access operator evaluates its contents to a name and
then accesses the value of that named property. For example, the following expressions access the
same variable
rocket.velocity;
rocket["velocity"];
velocity in the movie clip rocket:
You can use the array access operator to dynamically set and retrieve instance names and variables.
For example, in the following code, the expression inside the
result of the evaluation is used as the name of the variable to be retrieved from movie clip
name["mc" + i]
[] operator is evaluated, and the
name:
You can also use the eval() function, as shown here:
eval("mc" + i)
The array access operator can also be used on the left side of an assignment statement. This allows
you to dynamically set instance, variable, and object names, as shown in the following example:
name[index] = "Gary";
Using operators to manipulate values in expressions49
You create multidimensional arrays in ActionScript by constructing an array, the elements of
which are also arrays. To access elements of a multidimensional array, you can nest the array access
operator with itself, as shown in the following example:
var chessboard = new Array();
for (var i=0; i<8; i++) {
chessboard.push(new Array(8));
}
function getContentsOfSquare(row, column){
chessboard[row][column];
}
You can check for matching [] operators in your scripts; see “Checking syntax and punctuation”
on page 66.
Specifying an object’s path
To use an action to control a movie clip or loaded SWF file, you must specify its name and its
address, called a target path.
In ActionScript, you identify a movie clip by its instance name. For example, in the following
statement, the
star._alpha = 50;
To give a movie clip an instance name:
_alpha property of the movie clip named star is set to 50% visibility:
1 Select the movie clip on the Stage.
2 Enter an instance name in the Property inspector.
To identify a loaded SWF file:
• Use _levelX, where X is the level number specified in the loadMovie() action that loaded the
SWF file.
For example, a SWF file loaded into level 5 has the target path
example, a SWF file is loaded into level 5 and its visibility is set to
• In the Actions panel (Window > Development > Actions), click the Insert Target Path button
and select a movie clip from the list that appears.
For more information on target paths, see “Absolute and relative target paths” in Using
Flash Help.
50Chapter 2: ActionScript Basics
Using built-in functions
A function is a block of ActionScript code that can be reused anywhere in a SWF file. If you pass
values as parameters to a function, the function will operate on those values. A function can also
return values.
Flash has built-in functions that let you access certain information and perform certain tasks, such
as getting the version number of Flash Player hosting the SWF file (
that belong to an object are called methods. Functions that don’t belong to an object are called top-level functions and are found in the Functions category of the Actions panel.
Each function has its own characteristics, and some functions require you to pass certain values. If
you pass more parameters than the function requires, the extra values are ignored. If you don’t
pass a required parameter, the empty parameters are assigned the
cause errors when you export a script. To call a function, it must be in a frame that the playhead
has reached.
To call a function, simply use the function name and pass any required parameters:
isNaN(someVar);
getTimer();
eval("someVar");
For more information on each function, see its entry in Chapter 12, “ActionScript Dictionary,”
on page 205.
getVersion()). Functions
undefined data type, which can
Creating functions
You can define functions to execute a series of statements on passed values. Your functions can
also return values. After a function is defined, it can be called from any Timeline, including the
Timeline of a loaded SWF file.
A well-written function can be thought of as a “black box.” If it has carefully placed comments
about its input, output, and purpose, a user of the function does not need to understand exactly
how the function works internally.
Defining a function
Functions, like variables, are attached to the Timeline of the movie clip that defines them, and
you must use a target path to call them. As with variables, you can use the
declare a global function that is available to all Timelines without using a target path. To define a
global function, precede the function name with the identifier
_global, as shown in the
following example:
_global.myFunction = function (x) {
return (x*2)+3;
}
To define a Timeline function, use the function action followed by the name of the function,
any parameters to be passed to the function, and the ActionScript statements that indicate what
the function does.
_global identifier to
The following example is a function named
function areaOfCircle(radius) {
return Math.PI * radius * radius;
}
areaOfCircle with the parameter radius:
Creating functions51
You can also define a function by creating a function literal—an unnamed function that is
declared in an expression instead of in a statement. You can use a function literal to define a
function, return its value, and assign it to a variable in one expression, as shown in the
following example:
area = (function() {return Math.PI * radius *radius;})(5);
When a function is redefined, the new definition replaces the old definition.
Passing parameters to a function
Parameters are the elements on which a function executes its code. (In this manual, the terms
parameter and argument are interchangeable.) For example, the following function takes the
parameters
When the function is called, the required parameters must be passed to the function. The
function substitutes the passed values for the parameters in the function definition. In this
example,
fields in the instance. The following function call assigns the value
and the value
scorecard is the instance name of a movie clip; display and score are input text
"JEB" to the variable display
45000 to the variable score:
fillOutScorecard("JEB", 45000);
The parameter initials in the function fillOutScorecard() is similar to a local variable; it
exists while the function is called and ceases to exist when the function exits. If you omit
parameters during a function call, the omitted parameters are passed as
undefined. If you provide
extra parameters in a function call that are not required by the function declaration, they
are ignored.
Using variables in a function
Local variables are valuable tools for organizing code and making it easy to understand. When a
function uses local variables, it can hide its variables from all other scripts in the SWF file; local
variables are scoped to the body of the function and ceases to exist when the function exits. Any
parameters passed to a function are also treated as local variables.
You can also use global and regular variables in a function. However, if you modify global or
regular variables, it is good practice to use script comments to document these modifications.
52Chapter 2: ActionScript Basics
Returning values from a function
Use the
function and replaces it with the value of the
the
return statement to return values from functions. The return statement stops the
return action. The following rules govern the use of
return statement in functions:
• If you specify a return type other than void for a function, you must include a return
statement in the function.
• If you specify a return type of void, you should not include a return statement.
• If you don’t specify a return type, including a return statement is optional. If you don’t
include one, an empty string is returned.
For example, the following function returns the square of the parameter
returned value must be a Number:
function sqr(x):Number {
return x * x;
}
Some functions perform a series of tasks without returning a value. For example, the following
function initializes a series of global variables:
You can use a target path to call a function in any Timeline from any Timeline, including from
the Timeline of a loaded SWF file. If a function was declared using the
_global identifier, you do
not need to use a target path to call it.
To call a function, enter the target path to the name of the function, if necessary, and pass any
required parameters inside parentheses. For example, the following statement invokes the
function
and stores the result in the variable
var temp = _root.MathLib.sqr(3);
sqr() in the movie clip MathLib on the main Timeline, passes the parameter 3 to it,
temp:
The following example uses an absolute path to call the initialize() function that was defined
on the main Timeline and requires no parameters:
_root.initialize();
The following example uses a relative path to call the list() function that was defined in the
functionsClip movie clip:
_parent.functionsClip.list(6);
Creating functions53
54Chapter 2: ActionScript Basics
CHAPTER 3
Writing and Debugging Scripts
In Macromedia Flash MX 2004 and Macromedia Flash MX Professional 2004, you can write
scripts that are embedded in your FLA file or stored externally on your computer. (If you are
writing ActionScript 2.0 clas
name as the class.) To write embedded scripts, use the Actions panel and attach the action to a
button or movie clip, or to a frame in the Timeline (see “Controlling when ActionScript runs”
on page 56). To write external script files, you can use any text editor or code editor. In Flash
Professional, you can also use the built-in Script window. For more information, see “Using the
Actions panel and Script window” on page 58.
When using the ActionScript editor, you can also check syntax for errors, automatically format
code, and use code hints to help you complete syntax. In addition, the punctuation balance
feature helps you pair parentheses, braces, or brackets. For more information, see “Using the
ActionScript editor” on page 61.
As you work on a document, test it often to ensure that it plays as smoothly as possible and that it
plays as expected. You can use the Bandwidth Profiler to simulate how your document will appear
at different connection speeds (see “Testing document download performance” in Using Flash
Help). To test your scripts, you use a special debugging version of Flash Player that helps you
troubleshoot. If you use good authoring techniques in your ActionScript, your scripts will be
easier to troubleshoot when something behaves unexpectedly. For more information, see
“Debugging your scripts” on page 68.
s files, you must store each class as an external file that has the same
55
Controlling when ActionScript runs
When you write a script, you use the Actions panel to attach the script to a frame on a Timeline,
or to a button or movie clip on the Stage. Scripts attached to a frame run, or execute, when the
playhead enters that frame. However, scripts attached to the first frame of a SWF file may behave
differently from those attached to subsequent frames, because the first frame in a SWF file is
rendered incrementally—objects are drawn on the Stage as they download into Flash Player—and
this can affect when actions execute. All frames after the first frame are rendered all at once, when
every object in the frame is available.
Scripts attached to movie clips or buttons execute when an event occurs. An event is an occurrence
in the SWF file such as a mouse movement, a keypress, or a movie clip being loaded. You can use
ActionScript to find out when these events occur and execute specific scripts depending on the
event. For more information, see Chapter 4, “Handling Events,” on page 83.
To perform an action depending on whether a condition exists, or to repeat an action, you can use
if, else, else if, for, while, do while, for..in, or switch statements, which are briefly
described in the rest of this section.
Checking a condition
Statements that check whether a condition is
true or false begin with the term if. If the
condition exists, ActionScript executes the statement that follows. If the condition doesn’t exist,
ActionScript skips to the next statement outside the block of code.
To optimize your code’s performance, check for the most likely conditions first.
The following statements test three conditions. The term
else if specifies alternative tests to
perform if previous conditions are false.
if (password == null || email == null) {
gotoAndStop("reject");
} else if (password == userID){
gotoAndPlay("startMovie");
}
If you want to check for one of several conditions, you can use the switch statement instead of
using multiple
else if statements.
Repeating an action
ActionScript can repeat an action a specified number of times or while a specific condition exists.
Use the
To repeat an action while a condition exists:
while, do..while, for, and for..in actions to create loops.
• Use the while statement.
A
while loop evaluates an expression and executes the code in the body of the loop if the
expression is
true. After each statement in the body is executed, the expression is evaluated again.
In the following example, the loop executes four times:
i = 4;
while (var i > 0) {
my_mc.duplicateMovieClip("newMC" + i, i );
i--;
}
56Chapter 3: Writing and Debugging Scripts
You can use the do..while statement to create the same kind of loop as a while loop. In a
do..while loop, the expression is evaluated at the bottom of the code block so the loop always
runs at least once, as shown in the following example:
i = 4;
do {
my_mc.duplicateMovieClip("newMC" +i, i );
i--;
} while (var i > 0);
To repeat an action using a built-in counter:
• Use the for statement.
Most loops use a counter of some kind to control how many times the loop executes. Each
execution of a loop is called an iteration. You can declare a variable and write a statement that
increases or decreases the variable each time the loop executes. In the
the statement that increments the counter are part of the action. In the following example, the
first expression (
second expression (
third expression (
for (var i = 4; i > 0; i--){
myMC.duplicateMovieClip("newMC" + i, i + 10);
}
To loop through the children of a movie clip or object:
var i = 4) is the initial expression that is evaluated before the first iteration. The
i > 0) is the condition that is checked each time before the loop runs. The
i--) is called the post expression and is evaluated each time after the loop runs.
for action, the counter and
• Use the for..in statement.
Children include other movie clips, functions, objects, and variables. The following example uses
the
trace statement to print its results in the Output panel:
myObject = { name:'Joe', age:25, city:'San Francisco' };
for (propertyName in myObject) {
trace("myObject has the property: " + propertyName + ", with the value: " +
myObject[propertyName]);
}
This example produces the following results in the Output panel:
myObject has the property: name, with the value: Joe
myObject has the property: age, with the value: 25
myObject has the property: city, with the value: San Francisco
You may want your script to iterate over a particular type of child—for example, over only movie
clip children. You can do this with
for (name in myMovieClip) {
if (typeof (myMovieClip[name]) == "movieclip") {
trace("I have a movie clip child named " + name);
}
}
For more information on each action, see individual entries in Chapter 12, “ActionScript
Dictionary,” on page 205.
for..in in conjunction with the typeof operator.
Controlling when ActionScript runs57
Using the Actions panel and Script window
You can embed Flash scripts in your FLA file or store them as external files. It’s a good idea to
store as much of your ActionScript code in external files as possible. This makes it easier to reuse
code in multiple FLA files. Then, in your FLA file, create a script that uses
to access the code you’ve stored externally. Use the .as suffix to identify your scripts as
ActionScript (AS) files. (If you are writing custom class files, you must store them as external
AS files.)
Note: ActionScript code in external files is compiled into a SWF file when you publish, export, test, or
debug a FLA file. Therefore, if you make any changes to an external file, you must save the file and
recompile any FLA files that use it.
When you embed ActionScript code in your FLA file, you can attach code to Frames and to
objects. Try to attach embedded ActionScript to the first frame of the Timeline whenever
possible. That way, you won’t have to search through a FLA file to find all your code; it is
centralized in one location. Create a layer called “Actions” and place your code there. That way,
even if you do place code on other Frames or attach it to objects, you’ll have to look at only one
layer to find it all.
To create scripts that are part of your document, you enter ActionScript directly into the Actions
panel. To create external scripts, use your preferred text editor or, in Flash Professional, you can
use the Script window. When you use the Actions panel or Script window, you are using the same
ActionScript editor, and are typing your code in the Script pane at the right side of the panel or
window. To reduce the amount of typing you have to do, you can also select or drag actions from
the Actions toolbox to the Script pane.
#include statements
To display the Actions panel, do one of the following:
• Select Window > Development Panels > Actions.
• Press F9.
(Flash Professional only) To display the Script window, do one of the following:
• To begin writing a new script, select File > New > ActionScript File.
• To open an existing script, select File > Open, and then open an existing AS file.
• To edit a script that is already open, click the document tab that displays the script’s name.
(Document tabs are supported only in Microsoft Windows.)
About the ActionScript editor environment
The ActionScript editor environment consists of two sections. The section on the right is the
Script pane, the area where you type your code. The section on the left is an Actions toolbox that
contains an entry for each ActionScript language element.
58Chapter 3: Writing and Debugging Scripts
In the Actions panel, the Actions toolbox also contains a Script navigator, which is a visual
I
th*
representation of the locations in the FLA file that have associated ActionScript; you can navigate
through your FLA file here to locate ActionScript code. If you click an item in the Script
navigator, the script associated with that item appears in the Script pane, and the playhead moves
to that position on the Timeline. If you double-click an item in the Script navigator, the script
gets pinned (see “Managing scripts in a FLA file” on page 60).
Actions toolboxScript navigator*Pop-up menu*
* Actions panel only
There are also several buttons above the Script pane:
nsert target pa
Add item to script
Find
Replace
* Actions panel only
Check Syntax
Auto Format
Show Code Hint
Reference
Debug Options*
View Options pop-up menu
You edit actions, enter parameters for actions, or delete actions directly in the Script pane. You
can also double-click on an item in the Actions toolbox or the Add (+) button above the Script
pane to add actions to the Script pane.
Using the Actions panel and Script window59
Managing scripts in a FLA file
If you don’t centralize all your code within a FLA file in one location, you can pin (lock in place)
multiple scripts in the Actions panel to make it easier to move among them. In the following
figure, the script associated with the current location on the Timeline is on Frame 1 of the layer
named Cleanup. (The tab at the far left always follows your location along the Timeline.) That
script is also pinned (it is shown as the rightmost tab). Two other scripts are pinned; one on
Frame 1 and the other on Frame 15 of the layer named Intro. You can move among the pinned
scripts by clicking on the tabs or by using keyboard shortcuts. Moving among pinned scripts does
not change your current position on the Timeline.
Tip: If the content displayed in the Script pane isn’t changing to reflect the location that you are
selecting on the Timeline, the Script pane is probably displaying a pinned script. Click the leftmost tab
at the lower left of the Script pane to display the ActionScript associated with your location along
the Timeline.
To pin a script:
1 Position your pointer on the Timeline so the script appears in a tab at the lower left of the Script
pane in the Actions panel.
2 Do one of the following:
■ Click the pushpin icon to the right of the tab. (If the pushpin looks like the icon at the far
left, the script is already pinned; clicking that icon unpins it.)
■ Right-click (Windows) or Control-click (Macintosh) on the tab, and select Pin Script.
■ Select Pin Script from the Options pop-up menu (at the upper right of the panel).
To unpin one or more scripts:
• Do one of the following:
■ If a pinned script appears in a tab at the lower left of the Script pane in the Actions panel,
click the pushpin icon to the right of the tab. (If the pushpin looks like the icon on the far
left, the script is already unpinned; clicking that icon pins it.)
■ Right-click (Windows) or Control-click (Macintosh) on a tab, and select Close Script or
Close All Scripts.
■ Select Close Script or Close All Scripts from the Options pop-up menu (at the upper right
of the panel).
To use keyboard shortcuts with pinned scripts:
• You can use the following keyboard shortcuts to work with pinned scripts:
ActionWindows shortcut keyMacintosh shortcut key
Pin scriptControl-= (equal sign)Command-=
Unpin scriptControl-- (minus sign)Command--
Move focus to tab on the right Control-Shift-. (period)Command-Shift-.
60Chapter 3: Writing and Debugging Scripts
ActionWindows shortcut keyMacintosh shortcut key
Move focus to tab on the leftControl-Shift-, (comma)Command-Shift-,
Unpin all scriptsControl-Shift-- (minus)Command-Shift--
Using the ActionScript editor
Flash MX 2004 and Flash MX Professional 2004 provide several tools to help you write
syntactically correct code and lets you set preferences for code formatting and other options.
These capabilities are discussed in this section.
Syntax highlighting
In ActionScript, as in any language, syntax is the way elements are put together to create meaning.
If you use incorrect ActionScript syntax, your scripts will not work.
When you write scripts in Flash MX 2004 and Flash MX Professional 2004, commands that are
not supported by the version of the player you are targeting appear in yellow in the Actions
toolbox. For example, if the Flash Player SWF version is set to Flash 6, ActionScript that is
supported only by Flash Player 7 appears in yellow in the Actions toolbox. (For information on
setting the Flash Player SWF version, see “Setting publish options for the Flash SWF file format”
in Using Flash Help.)
You can also set a preference to have Flash “color-code” parts of your scripts as you write them, to
bring typing errors to your attention. For example, suppose you set your Syntax coloring
preference to have keywords appear in deep green. While you are typing code, if you type
word
var appears in green. However, if you mistakenly type vae, the word vae remains black,
providing you with an immediate clue that you made a typing error.
var, the
To set preferences for syntax coloring as you type, do one of the following:
• Select Edit > Preferences, and specify Syntax coloring settings on the ActionScript tab.
• In the Actions panel, select Preferences from the Options pop-up menu (at the upper right of
the panel) and specify Syntax coloring settings on the ActionScript tab.
Writing code that triggers code hints
When you work in the ActionScript editor (either in the Actions panel or Script window), Flash
can detect what action you are entering and display a code hint—a tooltip that contains the
complete syntax for that action, or a pop-up menu that lists possible method or property names.
Code hints appear for parameters, properties, and events when you strictly type or name your
objects so that the ActionScript editor knows which code hints to display, as discussed in the rest
of this section. For information on using code hints when they appear, see “Using code hints”
on page 63.
Note: Code hinting is enabled automatically for native classes that don’t require you to create and
name an object of the class, such as Math, Key, Mouse, and so on.
Using the ActionScript editor61
Strictly typing objects to trigger code hints
When you use ActionScript 2.0, you can strictly type a variable that is based on a built-in class,
such as Button, Array, and so on. If you do so, the ActionScript editor displays code hints for the
variable. For example, suppose you type the following:
var names:Array = new Array();
names.
As soon as you type the period (.), Flash displays a list of methods and properties available for
Array objects, because you have typed the variable as an array. For more information on data
typing, see “Strict data typing” on page 38. For information on using code hints when they
appear, see “Using code hints” on page 63.
Using suffixes to trigger code hints
If you use ActionScript 1 or you want to display code hints for objects you create without strictly
typing them (see “Strictly typing objects to trigger code hints” on page 62), you must add a
special suffix to the name of each object when you create it. For example, the suffixes that trigger
code hinting for the Array class and the Camera class are
_array and _cam, respectively. If you
type the following code:
var my_array = new Array();
var my_cam = Camera.get();
and then type either of the following (the variable name followed by a period), code hints for the
Array and Camera object, respectively, appear.
my_array.
my_cam.
For objects that appear on the Stage, use the suffix in the Instance Name text box in the Property
inspector. For example, to display code hints for MovieClip objects, use the Property inspector to
assign instance names with the suffix
_mc to all MovieClip objects. Then, whenever you type the
instance name followed by a period, code hints appear.
Although suffixes are not required for triggering code hints when you strictly type an object, using
them consistently helps you and others understand your scripts.
The following table lists the suffixes required for support of automatic code hinting:
Object typeVariable suffix
Array_array
Button_btn
Camera_cam
Color_color
ContextMenu_cm
ContextMenuItem_cmi
Date_date
Error_err
LoadVars_lv
62Chapter 3: Writing and Debugging Scripts
Object typeVariable suffix
LocalConnection_lc
Microphone_mic
MovieClip_mc
MovieClipLoader_mcl
PrintJob_pj
NetConnection_nc
NetStream_ns
SharedObject_so
Sound_sound
String_str
TextField_txt
TextFormat_fmt
Video_video
XML_xml
XMLNode_xmlnode
XMLSocket_xmlsocket
For information on using code hints when they appear, see “Using code hints” on page 63.
Using comments to trigger code hints
You can also use ActionScript comments to specify an object’s class for code hinting. The
following example tells ActionScript that the class of the instance
If you were to enter
mc followed by a period after these comments, a code hint would display the
list of MovieClip methods and properties; if you were to enter
theObject is Object, and so on.
theArray followed by a period, a
code hint would display a list of Array methods and properties; and so on.
However, Macromedia recommends using strict data typing (see “Strictly typing objects to trigger
code hints” on page 62) or suffixes (see “Using suffixes to trigger code hints” on page 62) instead
of this technique, because those techniques enable code hinting automatically and make your
code more understandable.
Using code hints
Code hints are enabled by default. By setting preferences, you can disable code hints or determine
how quickly they appear. When code hints are disabled in preferences, you can still display a code
hint for a specific command.
Using the ActionScript editor63
To specify settings for automatic code hints, do one of the following:
• Select Edit > Preferences, and then enable or disable Code Hints on the ActionScript tab.
• In the Actions panel, select Preferences from the Options pop-up menu (at the upper right of
the panel) and enable or disable Code Hints on the ActionScript tab.
If you enable code hints, you can also specify a delay in seconds before the code hints should
appear. For example, if you are new to ActionScript, you might prefer no delay so that code hints
always appear immediately. However, if you usually know what you want to type and only need
hints when you use unfamiliar language elements, you can specify a delay so that code hints don’t
appear when you don’t plan to use them.
To work with tooltip-style code hints:
1 Display the code hint by typing an open parenthesis [(] after an element that requires
parentheses, such as a method name, a command such as
The code hint appears.
if or do while, and so on.
Note: If a code hint doesn’t appear, make sure you haven’t disabled code hints on the ActionScript
tab. If you want to display code hints for a variable or object you created, make sure that you have
named your variable or object correctly (see “Using suffixes to trigger code hints” on page 62) or
that you have strictly typed your variable or object (see “Strictly typing objects to trigger code
hints” on page 62).
2 Enter a value for the parameter. If there is more than one parameter, separate the values
with commas.
Overloaded commands such as
gotoAndPlay() or for (that is, functions or methods that can
be invoked with different sets of parameters) display an indicator that allows you to select the
parameter you want to set. Click the small arrow buttons or press Control+Left Arrow and
Control+Right Arrow to select the parameter.
3 To dismiss the code hint, do one of the following:
■ Type a closing parenthesis [)].
■ Click outside the statement.
■ Press Escape.
64Chapter 3: Writing and Debugging Scripts
To work with menu-style code hints:
1 Display the code hint by typing a period after the variable or object name.
The code hint menu appears.
Note: If a code hint doesn’t appear, make sure you haven’t disabled code hints on the ActionScript
tab. If you want to display code hints for a variable or object you created, make sure that you have
named your variable or object correctly (see “Using suffixes to trigger code hints” on page 62) or
that you have strictly typed your variable or object (see “Strictly typing objects to trigger code
hints” on page 62).
2 To navigate through the code hints, use the Up and Down Arrow keys.
3 To select an item in the menu, press Return or Tab, or double-click the item.
4 To dismiss the code hint, do one of the following:
■ Select one of the menu items.
■ Click outside the statement.
■ Type a closing parenthesis [)] if you’ve already typed an open parenthesis.
■ Press Escape.
To manually display a code hint:
1 Click in a code location where code hints can appear. Here are some examples:
■ After the dot following a statement or command, where a property or method must
be entered
■ Between parentheses in a method name
2 Do one of the following:
■ Click the Show Code Hint button above the Script pane.
■ Press Control+Spacebar (Windows) or Command+Spacebar (Macintosh).
■ If you are working in the Actions panel, open the pop-up menu (at the right side of the title
bar), and select Show Code Hint.
Using Escape shortcut keys
You can add many elements to a script by using shortcut keys—pressing the Escape key and then
two other keys. (These shortcuts are different from the keyboard shortcuts that initiate certain
menu commands.) For example, if you are working in the Script pane and type Escape+d+o, the
following code is placed in your script, and the insertion point is placed immediately following
the word
do {
} while ();
while, so you can begin typing your condition:
Using the ActionScript editor65
Similarly, if you type Escape+c+h, the following code is placed in your script, and the insertion
point is placed between the parentheses, so you can begin typing your condition:
catch () {
}
If you want to learn (or be reminded) which commands have Escape shortcut keys, you can
display them next to elements in the Actions panel.
To display or hide Escape shortcut keys:
• From the View Options pop-up menu, enable or disable View Escape Shortcut Keys.
Checking syntax and punctuation
To thoroughly determine whether the code you wrote performs as planned, you need to publish
or test the file. However, you can do a quick check of your ActionScript code without leaving the
FLA file. Syntax errors are listed in Output panel. (When you check syntax, only the current
script is checked; other scripts that may be in the FLA file are not checked.) You can also check to
see if a set of parentheses, curly braces, or brackets (array access operators) around a block of code
is balanced.
To check syntax, do one of the following:
• Click the Check Syntax button above the Script pane.
• In the Actions panel, display the pop-up menu (at the upper right of the panel) and select
Check Syntax.
• Press Control+T (Windows) or Command+T (Macintosh).
66Chapter 3: Writing and Debugging Scripts
To check for punctuation balance:
1 Click between braces ({}), array access operators ([]), or parentheses (()) in your script.
2 Press Control+' (Windows) or Command+' (Macintosh) to highlight the text between braces,
brackets, or parentheses.
The highlighting helps you check whether opening punctuation has correct corresponding
closing punctuation.
Formatting code
You can specify settings to determine if your code is formatted and indented automatically or
manually. You can also choose whether to view line numbers and whether to wrap long lines
of code.
To set format options:
1 Do one of the following
■ In the Actions panel, select Auto Format Options from the Options pop-up menu (at the
upper right of the panel).
■ (Flash Professional only) In an external script file, choose Edit > Auto Format Options.
The Auto Format Options dialog box appears.
2 Select any of the check boxes. To see the effect of each selection, look in the Preview pane.
After you set Auto Format Options, your settings are applied automatically to code you write, but
not to existing code. To apply your settings to existing code, you must do so manually. You might
use this procedure to format code that was formatted using different settings, that you imported
from another editor, and so on.
To format code according to Auto Format Options settings, do one of the following:
• Click the Auto Format button above the Script pane.
• Select Auto Format from the Actions panel pop-up menu.
• Press Control+Shift+F (Windows) or Command+Shift+F (Macintosh).
To use automatic indentation:
• Automatic indentation is turned on by default. To turn it off, deselect Automatic Indentation
in ActionScript preferences.
When automatic indentation is turned on, the text you type after
( or { is automatically
indented according to the Tab Size setting in ActionScript preferences. To indent another line,
select the line and press Tab. To remove the indent, press Shift+Tab.
To enable or disable line numbers and word wrap:
• From the View Options pop-up menu, enable or disable View Line Numbers and Word Wrap.
Using the ActionScript editor67
Debugging your scripts
Flash provides several tools for testing ActionScript in your SWF files. The Debugger, discussed
in the rest of this section, lets you find errors in a SWF file while it’s running in Flash Player. Flash
also provides the following additional debugging tools:
• The Output panel, which displays error messages and lists of variables and objects (see “Using
the Output panel” on page 77)
• The trace statement, which sends programming notes and values of expressions to the
Output panel (see “Using the trace statement” on page 79
)
• The throw and try..catch..finally statements, which let you test and respond to runtime
errors from within your script
• The availability of comprehensive compiler error messages, which let you diagnose and fix
problems more readily (see Appendix A, “Error Messages,” on page 783)
You must be viewing your SWF file in a special version of Flash Player called Flash Debug Player.
When you install the authoring tool, Flash Debug Player is installed automatically. So if you
install Flash and browse a website that has Flash content, or do a Test Movie, then you’re using
Flash Debug Player. You can also run the installer in the <app_dir>\Players\Debug\ directory, or
launch the stand-alone Flash Debug Player from the same directory.
When you use the Test Movie command to test movies that implement keyboard controls
(tabbing, keyboard shortcuts created using
Disable Keyboard Shortcuts. Selecting this option prevents the authoring environment from
“grabbing” keystrokes, and lets them pass through to the player. For example, in the authoring
environment, Control+U opens the Preferences dialog box. If your script assigns Control+U to an
action that underlines text onscreen, when you use Test Movie, pressing Control+U will open the
Preferences dialog box instead of running the action that underlines text. To let the Control+U
command pass through to the player, you must select Control > Disable Keyboard Shortcuts.
Key.addListener(), and so on), select Control >
Caution: The Test Movie command fails if any part of the SWF file path has characters that cannot
be represented using the MBCS encoding scheme. For example, Japanese paths on an English
system do not work. All areas of the application that use the external player are subject to
this limitation.
The Debugger shows a hierarchical display list of movie clips currently loaded in Flash Player.
Using the Debugger, you can display and modify variable and property values as the SWF file
plays, and you can use breakpoints to stop the SWF file and step through ActionScript code line
by line.
You can use the Debugger in test mode with local files, or you can use it to test files on a web
server in a remote location. The Debugger lets you set breakpoints in your ActionScript that stop
Flash Player and step through the code as it runs. You can then go back to your scripts and edit
them so that they produce the correct results.
After it’s activated, the Debugger status bar displays the URL or local path of the file, tells
whether the file is running in test mode or from a remote location, and shows a live view of the
movie clip display list. When movie clips are added to or removed from the file, the display list
reflects the changes immediately. You can resize the display list by moving the horizontal splitter.
68Chapter 3: Writing and Debugging Scripts
To activate the Debugger in test mode:
• Select Control > Debug Movie.
This opens the Debugger. It also opens the SWF file in test mode.
Status bar
Display listCode view
Watch list
Debugging a SWF file from a remote location
You can debug a remote SWF file using the stand-alone, ActiveX, or plug-in versions of Flash
Player. When exporting a SWF file, you can enable debugging in your file and create a debugging
password. If you don’t enable debugging, the Debugger will not activate.
To ensure that only trusted users can run your SWF files in the Flash Debug Player, you can
publish your file with a debugging password. As in JavaScript or HTML, it’s possible for users to
view client-side variables in ActionScript. To store variables securely, you must send them to a
server-side application instead of storing them in your file. However, as a Flash developer, you
may have other trade secrets, such as movie clip structures, that you do not want to reveal. You
can use a debugging password to protect your work.
When you export, publish, or test a movie, Flash creates a SWD file that contains debug
information. To debug remotely, you must place the SWD file in the same directory as the SWF
file on the server.
Debugging your scripts69
To enable remote debugging of a Flash movie:
1 Select File > Publish Settings.
2 On the Flash tab of the Publish Settings dialog box, select Debugging permitted.
3 To set a password, enter a password in the Password box.
After you set this password, no one can download information to the Debugger without the
password. However, if you leave the Password box blank, no password is required.
4 Close the Publish Settings dialog box, and select one of the following commands:
■ Control > Debug Movie
■ File > Export Movie
■ File > Publish Settings > Publish
Flash creates a debugging file with the .swd extension and saves it alongside the SWF file. The
SWD file contains information that allows you to use breakpoints and step through code.
5 Place the SWD file in the same directory as the SWF file on the server.
If the SWD file is not in the same directory as the SWF file, you can still debug remotely, but
the Debugger ignores breakpoints and you can’t step through code.
6 In Flash, select Window > Development Panels > Debugger.
• In the Debugger, select Enable Remote Debugging from the Options pop-up menu (at the
upper right of the panel).
70Chapter 3: Writing and Debugging Scripts
To activate the Debugger from a remote location:
1 Open the Flash authoring application.
2 In a browser or in the stand-alone player, open the published SWF file from the
remote location.
The Remote Debug dialog box appears.
If that dialog box doesn’t appear, Flash can’t find the SWD file. In this case, right-click
(Windows) or Control-click (Macintosh) in the SWF file to display the context menu, and
select Debugger.
3 In the Remote Debug dialog box, select Localhost or Other Machine:
■ Select Localhost if the Debug player and the Flash authoring application are on the
same computer.
■ Select Other Machine if the Debug player and the Flash authoring application are not
on the same computer. Enter the IP address of the computer running the Flash
authoring application.
4 When a connection is established, a password prompt appears. Enter your debugging password
if you set one.
The display list of the SWF file appears in the Debugger.
Debugging your scripts71
Displaying and modifying variables
The Variables tab in the Debugger displays the names and values of any global and Timeline
variables in the SWF file. If you change the value of a variable on the Variables tab, you can see
the change reflected in the SWF file while it runs. For example, to test collision detection in a
game, you can enter the variable value to position a ball in the correct location next to a wall.
The Locals tab in the Debugger displays the names and values of any local variables that are
available wherever the SWF file has stopped at a breakpoint or anywhere else within a userdefined function.
To display a variable:
1 Select the movie clip containing the variable from the display list.
To display global variables, select the
2 Click the Variables tab.
_global clip in the display list.
The display list updates automatically as the SWF file plays. If a movie clip is removed from the
SWF file at a specific frame, that movie clip, along with its variable and variable name, is also
removed from the display list in the Debugger. However, if you mark a variable for the Watch list
(see “Using the Watch list” on page 73), that variable is not removed.
To modify a variable value:
• Double-click the value, and enter a new value.
The value cannot be an expression. For example, you can use
www.macromedia.com"
, and you cannot use x + 2 or eval("name:" +i). The value can be a
string (any value surrounded by quotation marks), a number, or a Boolean value (
Note: To write the value of an expression to the Output panel in test mode, use the trace statement.
See “Using the trace statement” on page 79.
72Chapter 3: Writing and Debugging Scripts
"Hello", 3523, or "http://
true or false).
Using the Watch list
To monitor a set of critical variables in a manageable way, you can mark variables to appear in the
Watch list. The Watch list displays the absolute path to the variable and the value. You can also
enter a new variable value in the Watch list the same way as in the Variables tab.
If you add a local variable to the Watch list, its value appears only when Flash Player is stopped at
a line of ActionScript where that variable is in scope. All other variables appear while the SWF file
is playing. If the Debugger can’t find the value of the variable, the value is listed as Undefined.
The Watch list can display only variables, not properties or functions.
Variables marked for the Watch list and variables in the Watch list
To add variables to the Watch list, do one of the following:
• On the Variables or Locals tab, right-click (Windows) or Control-click (Macintosh) a selected
variable and then select Watch from the context menu. A blue dot appears next to the variable.
• On the Watch tab, right-click (Windows) or Control-click (Macintosh) and select Add from
the context menu. Enter the target path to the variable name and the value in the fields.
To remove variables from the Watch list:
• On the Watch tab, right-click (Windows) or Control-click (Macintosh) and select Remove
from the context menu.
Debugging your scripts73
Displaying movie clip properties and changing editable properties
The Debugger’s Properties tab displays all the property values of any movie clip on the Stage. You
can change a value and see its effect in the SWF file while it runs. Some movie clip properties are
read-only and cannot be changed.
To display a movie clip’s properties in the Debugger:
1 Select a movie clip from the display list.
2 Click the Properties tab in the Debugger.
To modify a property value:
• Double-click the value, and enter a new value.
The value cannot be an expression. For example, you can enter
cannot enter
x + 50. The value can be a string (any value surrounded by quotation marks), a
number, or a Boolean value (true or false). You can’t enter object or array values (for example,
{id: "rogue"} or [1, 2, 3]) in the Debugger.
For more information, see “String operators” on page 46 and “Using operators to manipulate
values in expressions” on page 45.
Note: To write the value of an expression to the Output panel in test mode, use the trace statement.
See “Using the trace statement” on page 79.
Setting and removing breakpoints
A breakpoint lets you stop a SWF file running in Flash Player at a specific line of ActionScript.
You can use breakpoints to test possible trouble spots in your code. For example, if you’ve written
a set of
if..else if statements and can’t determine which one is executing, you can add a
breakpoint before the statements and step through them one by one in the Debugger.
50 or "clearwater", but you
74Chapter 3: Writing and Debugging Scripts
You can set breakpoints in the Actions panel or in the Debugger. (To set breakpoints in external
scripts, you must use the Debugger.) Breakpoints set in the Actions panel are saved with the Flash
document (FLA file). Breakpoints set in the Debugger are not saved in the FLA file and are valid
only for the current debugging session.
To set or remove a breakpoint in the Actions panel, do one of the following:
• Click in the left margin. A red dot indicates a breakpoint.
• Click the Debug options button above the Script pane.
• Right-click (Windows) or Control-click (Macintosh) to display the context menu, and select
Breakpoint, Remove Breakpoint, or Remove All Breakpoints.
• Press Control+Shift+B (Windows) or Command+Shift+B (Macintosh).
Note: In previous versions of Flash, clicking in the left margin of the Script pane selected the line of
code; now it adds or removes a breakpoint. To select a line of code, use Control-click (Windows) or
Command-click (Macintosh).
To set and remove breakpoints in the Debugger, do one of the following:
• Click in the left margin. A red dot indicates a breakpoint.
• Click the Toggle Breakpoint or Remove All Breakpoints button above the code view.
• Right-click (Windows) or Control-click (Macintosh) to display the context menu, and select
Breakpoint, Remove Breakpoint, or Remove All Breakpoints.
• Press Control+Shift+B (Windows) or Command+Shift+B (Macintosh).
Once Flash Player is stopped at a breakpoint, you can step into, step over, or step out of that
line of code. If you set a breakpoint in a comment or on an empty line in the Actions panel, the
breakpoint is ignored.
Stepping through lines of code
When you start a debugging session, Flash Player is paused. If you set breakpoints in the Actions
panel, you can simply click the Continue button to play the SWF file until it reaches a
breakpoint. For example, in the following code, suppose a breakpoint is set inside a button on the
line
myFunction():
on(press){
myFunction();
}
When you click the button, the breakpoint is reached and Flash Player pauses. You can now step
in to bring the Debugger to the first line of myFunction() wherever it is defined in the
document. You can also step through or out of the function.
If you didn’t set breakpoints in the Actions panel, you can use the jump menu in the Debugger to
select any script in the movie. Once you’ve selected a script, you can add breakpoints to it. After
adding breakpoints, you must click the Continue button to start the movie. The Debugger stops
when it reaches the breakpoint.
Debugging your scripts75
As you step through lines of code, the values of variables and properties change in the Watch list
and in the Variables, Locals, and Properties tabs. A yellow arrow along the left side of the
Debugger’s code view indicates the line at which the Debugger stopped. Use the following
buttons along the top of the code view:
Continue
Stop Debugging
Toggle Breakpoint
Remove All Breakpoints
Step Out
Step In
Step Over
Step In advances the Debugger (indicated by the yellow arrow) into a function. Step In works
only for user-defined functions.
In the following example, if you place a breakpoint at line 7 and click Step In, the Debugger
advances to line 2, and a subsequent click of Step In will advance you to line 3. Clicking Step In
for lines that do not have user-defined functions in them advances the Debugger over a line of
code. For example, if you stop at line 2 and select Step In, the Debugger advances to line 3, as
shown in the following example:
1 function myFunction() {
2 x = 0;
3 y = 0;
4 }
5
6 mover = 1;
7 myFunction();
8 mover = 0;
Step Out
advances the Debugger out of a function. This button works only if you are currently
stopped in a user-defined function; it moves the yellow arrow to the line after the one where that
function was called. In the example above, if you place a breakpoint at line 3 and click Step Out,
the Debugger moves to line 8. Clicking Step Out at a line that is not within a user-defined
function is the same as clicking Continue. For example, if you stop at line 6 and click Step Out,
the player continues executing the script until it encounters a breakpoint.
Step Over advances the Debugger over a line of code. This button moves the yellow arrow to the
next line in the script and ignores any user-defined functions. In the example above, if you are
stopped at line 7 and click Step Over, you go directly to line 8, and
Continue leaves the line at which the player is stopped and continues playing until a breakpoint
myFunction() is ignored.
is reached.
Stop Debugging makes the Debugger inactive but continues to play the SWF file in Flash Player.
76Chapter 3: Writing and Debugging Scripts
Using the Output panel
In test mode, the Output panel displays information to help you troubleshoot your SWF file.
Some information, such as syntax errors, is displayed automatically. You can display other
information by using the List Objects and List Variables commands. (See “Listing a SWF file’s
objects” on page 77 and “Listing a SWF file’s variables” on page 78.)
If you use the
trace statement in your scripts, you can send specific information to the Output
panel as the SWF file runs. This could include notes about the SWF file’s status or the value of an
expression. (See “Using the trace statement” on page 79.)
To display the Output panel, select Window > Development Panels > Output or press F2.
Note: If there are syntax errors in a script, the Output panel appears automatically when you check
syntax or test your SWF file.
To work with the contents of the Output panel, use the Options pop-up menu in the upper
right corner.
Listing a SWF file’s objects
In test mode, the List Objects command displays the level, frame, object type (shape, movie clip,
or button), target paths, and instance names of movie clips, buttons, and text fields in a
hierarchical list. This is especially useful for finding the correct target path and instance name.
Unlike the Debugger, the list does not update automatically as the SWF file plays; you must select
the List Objects command each time you want to send the information to the Output panel.
The List Objects command does not list all ActionScript data objects. In this context, an object is
considered to be a shape or symbol on the Stage.
To display a list of objects in a movie:
1 If your movie is not running in test mode, select Control > Test Movie.
2 Select Debug > List Objects.
A list of all the objects currently on the Stage is displayed in the Output panel, as shown in
this example:
Level #0: Frame=1 Label="Scene_1"
Button: Target="_level0.myButton"
Shape:
Movie Clip: Frame=1 Target="_level0.myMovieClip"
Shape:
Edit Text: Target="_level0.myTextField" Text="This is sample text."
Using the Output panel77
Listing a SWF file’s variables
In test mode, the List Variables command displays a list of all the variables currently in the SWF
file. This is especially useful for finding the correct variable target path and variable name. Unlike
the Debugger, the list does not update automatically as the SWF file plays; you must select the
List Variables command each time you want to send the information to the Output panel.
The List Variables command also displays global variables declared with the
_global identifier.
The global variables are displayed at the top of the List Variables output in a “Global Variables”
section, and each variable is prefixed with
_global.
In addition, the List Variables command displays getter/setter properties—properties that are
created with the
Object.addProperty() method and invoke get or set methods. A getter/
setter property is displayed alongside any other properties in the object it belongs to. To make
these properties easily distinguishable from ordinary variables, the value of a getter/setter property
is prefixed with the string
determined by evaluating the
To display a list of variables in a SWF file:
1 If your SWF file is not running in test mode, select Control > Test Movie.
2 Select Debug > List Variables.
[getter/setter]. The value displayed for a getter/setter property is
get function of the property.
A list of all the variables currently in the SWF file is displayed in the Output panel, as shown in
this example:
To get debugging information about TextField objects, you can use the Debug > List Variables
command in test movie mode. The Output panel uses the following conventions in displaying
TextField objects:
• If a property is not found on the object, it is not displayed.
• No more than four properties are displayed on a line.
• A property with a string value is displayed on a separate line.
• If there are any other properties defined for the object after the built-in properties are
processed, they are added to the display using the rules in the second and third points above.
• Color properties are displayed as hexadecimal numbers (0x00FF00).
• The properties are displayed in the following order: variable, text, htmlText, html,
The Debug > List Objects command in test mode lists TextField objects. If an instance name is
specified for a text field, the Output panel displays the full target path including the instance
name in the following form:
Target = "target path"
Using the trace statement
When you use the
trace statement in a script, you can send information to the Output panel.
For example, while testing a movie or scene, you can send specific programming notes to the
panel or have specific results appear when a button is pressed or a frame is played. The
statement is similar to the JavaScript
When you use the
trace statement in a script, you can use expressions as parameters. The value
alert statement.
trace
of an expression is displayed in the Output panel in test mode, as shown here:
The
trace statement returns values that appear in the Output panel.
onClipEvent(enterFrame){
trace("onClipEvent enterFrame " + enterFrame++)
}
Updating Flash Player for testing
You can download the latest version of Flash Player from the Macromedia Support Center at
www.macromedia.com/support/flash and use it to test your SWF files with the most recent
version of Flash Player.
Updating Flash Player for testing79
80Chapter 3: Writing and Debugging Scripts
PART II
Handling Events and Creating Interaction
Events can be user-generated, such as mouse clicks or keypresses, or can occur as a result of some
other process, such as an XML file loading over the network. The first chapter in this part
describes the different types of events in Macromedia Flash and discusses how to handle them in
ActionScript. The second chapter shows how to apply these principles to create simple interactive
presentations, applications, and animations.
An event is a software or hardware occurrence that requires a response from a Macromedia Flash
application. For example, an event such as a mouse click or a keypress is called a user event, since it
occurs as a result of direct user interaction. An event generated automatically by Flash Player, such
as the initial appearance of a movie clip on the Stage, is called a system event, because it isn’t
generated directly by the user.
In order for your application to react to events, you must use event handlers—ActionScript code
associated with a particular object and event. For example, when a user clicks a button on the
Stage, you might advance the playhead to the next frame. Or when an XML file finishes loading
over the network, you might display the contents of that file in a text field.
ActionScript provides a few different ways to handle events: event handler methods, event
listeners, and button and movie clip event handlers.
Using event handler methods
An event handler method is a class method that is invoked when an event occurs on an instance of
that class. For example, the Button class defines an
whenever the mouse is pressed on a Button object. Unlike other methods of a class, however, you
don’t invoke an event handler directly; Flash Player invokes it automatically when the appropriate
event occurs.
By default, event handler methods are undefined: when a particular event occurs, its
corresponding event handler is invoked, but your application doesn’t respond further to the event.
To have your application respond to the event, you define a function with the function statement
and then assign that function to the appropriate event handler. The function you assign to the
event handler is then automatically invoked whenever the event occurs.
An event handler consists of three parts: the object to which the event applies, the name of the
object’s event handler method, and the function you assign to the event handler. The following
example shows the basic structure of an event handler.
object.eventMethod = function () {
// Your code here, responding to event
}
onPress event handler that is invoked
83
For example, suppose you have a button named next_btn on the Stage. The following code
assigns a function to the button’s
onPress event handler; this function advances the playhead to
the next frame in the Timeline.
next_btn.onPress = function ()
nextFrame();
}
In the above code, the nextFrame() function is assigned directly to onPress. You can also assign
a function reference (name) to an event handler method and then define the function later.
// Assign a function reference to button’s onPress event handler method
next_btn.onPress = goNextFrame;
// Define doSubmit() function
function goNextFrame() {
nextFrame();
}
Notice that you assign the function reference, not the function’s return value, to the onPress
event handler.
The following ActionScript classes define event handlers: Button, ContextMenu,
ContextMenuItem, Key, LoadVars, LocalConnection, Mouse, MovieClip, MovieClipLoader,
Selection, SharedObject, Sound, Stage, TextField, XML, and XMLSocket. For more information
about the event handlers they provide, see these class entries in Chapter 12, “ActionScript
Dictionary,” on page 205.
You can also assign functions to event handlers for objects you create at runtime. For example, the
following code creates a new movie clip instance (
newclip_mc) and then assigns a function to the
clip’s onPress event handler.
_root.attachMovie("symbolID", "newclip_mc", 10);
newclip_mc.onPress = function () {
trace("You pressed me");
}
For more information, see “Creating movie clips at runtime” on page 126.
84Chapter 4: Handling Events
Using event listeners
Event listeners let an object, called a listener object, receive events generated by another object,
called a broadcaster object. The broadcaster object registers the listener object to receive events
generated by the broadcaster. For example, you could register a movie clip object to receive
onResize notifications from the Stage, or a button instance could receive onChanged
notifications from a text field object. You can register multiple listener objects to receive events
from a single broadcaster, and you can register a single listener object to receive events from
multiple broadcasters.
The event model for event listeners is similar to that of event handlers (see “Using event handler
methods” on page 83), with two main differences:
• The object to which you assign the event handler is not the object that emits the event.
• You call a special method of the broadcaster object, addListener(), which registers the
listener object to receive its events.
To use event listeners, you create a listener object with a property that has the name of the event
being generated by the broadcaster object. You then assign a function to the event listener that
responds in some way to the event. Lastly, you call
broadcasting the event, passing it the name of the listener object. The following code outlines the
event listener model.
listenerObject.eventName = function(){
// your code here
};
broadcastObject.addListener(listenerObject);
addListener() on the object that’s
The specified listener object can be any object, such as a movie clip or button instance on the
Stage, or an instance of any ActionScript class. The event name is an event that occurs on
broadCastObject, which then broadcasts the event to listenerObject. You can register
multiple listeners to one event broadcaster.
The following example shows how to use the
Selection.onSetFocus event listener to create a
simple focus manager for a group of input text fields. In this case, the border of the text field that
receives keyboard focus is enabled (displayed), and the border of the text field that lost focus
is disabled.
Using event listeners85
To create a simple focus manager with event listeners:
1 Using the Text tool, create a text field on the Stage.
2 Select the text field and, in the Property inspector, select Input from the Text Type pop-up
menu, and select the Show Border Around Text option.
3 Create another input text field below the first one.
Make sure the Show Border Around Text option is not selected for this text field. Continue to
create input text fields if desired.
4 Select Frame 1 in the Timeline and open the Actions panel (Window > Development
Panels > Actions).
5 To create an object that listens for focus notification from the Selection class, enter the following
This code creates a new (generic) ActionScript object named focusListener. This object
defines for itself an
onSetFocus property, to which it assigns a function. The function takes
two parameters: a reference to the text field that lost focus, and one to the text field that gained
focus. The function sets the
the
border property of the text field that gained focus to true.
6 To register the focusListener object to receive events from the Selection object, add the
border property of the text field that lost focus to false, and sets
following code to the Actions panel:
Selection.addListener(focusListener);
7 Test the movie (Control > Test Movie), click in the first text field, and press Tab to switch focus
between fields.
To unregister a listener object from receiving events, you call the
removeListener() method of
the broadcaster object, passing it the name of the listener object.
broadcastObject.removeListener(listenerObject);
Event listeners are available to objects of the following ActionScript classes: Key, Mouse,
MovieClipLoader, Selection, TextField, and Stage. For a list of event listeners available to each
class, see these class entries in Chapter 12, “ActionScript Dictionary,” on page 205.
86Chapter 4: Handling Events
Using button and movie clip event handlers
You can attach event handlers directly to a button or movie clip instance by using the
onClipEvent() and on() handlers. The onClipEvent() handler handles movie clip events, and
the
on() handler handles button events. You can also use on() with movie clips to create movie
clips that receive button events. For more information, see “Creating movie clips with button
states” on page 88.
To us e an
on() or onClipEvent() handler, attach it directly to an instance of a button or movie
clip on the Stage and specify the event you want to handle for that instance. For example, the
following
on() event handler executes whenever the user clicks the button that the handler is
attached to.
on(press) {
trace("Thanks for pressing me.");
}
You can specify two or more events for each on() handler, separated by commas. The
ActionScript in a handler executes when either of the events specified by the handler occurs. For
example, the following
on() handler attached to a button executes whenever the mouse rolls over
out of the button.
on(rollOver, rollOut) {
trace("You rolled over, or rolled out");
}
You can also attach more than one handler to an object if you want different scripts to run when
different events occur. For example, you could attach the following
onClipEvent() handlers to
the same movie clip instance. The first executes when the movie clip first loads (or appears on the
Stage); the second executes when the movie clip is unloaded from the Stage.
onClipEvent(load) {
trace("I've loaded");
}
onClipEvent (unload) {
trace("I've unloaded");
}
For a complete list of events supported by the on() and onClipEvent() event handlers, see on()
on page 583 and
Event handling through
onClipEvent() on page 584.
on() and onClipEvent() doesn’t conflict with event handling through
event handler methods that you define. For example, suppose you have a button in a SWF file;
the button can have an
on(press) handler that tells the SWF file to play, and the same button
can have an onPress method, for which you define a function that tells an object on the Stage to
rotate. When the button is clicked, the SWF file plays and the object rotates. Depending on your
preference, you can use
on() and onClipEvent(), event handler methods, or both types of event
handling. However, the scope of variables and objects in on() and onClipEvent() handlers is
different than in event handler and event listeners. (See “Event handler scope” on page 88.)
You can attach
the Stage during authoring. You cannot attach
that are created at runtime (using the
onClipEvent() and on() only to movie clip instances that have been placed on
onClipEvent() or on() to movie clip instances
attachMovie() method, for example). To attach event
handlers to objects created at runtime, use event handler methods or event listeners. (See “Using
event handler methods” on page 83 and “Using event listeners” on page 85.)
Using button and movie clip event handlers87
Creating movie clips with button states
When you attach an on() handler to a movie clip, or assign a function to one of the MovieClip
mouse event handlers for a movie clip instance, the movie clip responds to mouse events in the
same way as a button does. You can also create automatic button states (Up, Over, and Down) in
a movie clip by adding the frame labels
_up, _over, and _down to the movie clip’s Timeline.
When the user moves the mouse over the movie clip or clicks it, the playhead is sent to the frame
with the appropriate frame label. To designate the hit area used by a movie clip, you use the
hitArea property of the MovieClip class.
To create button states in a movie clip:
1 Select a frame in a movie clip’s Timeline to use as a button state (Up, Over, or Down).
2 Enter a frame label in the Property inspector (_up, _over, or _down).
3 To add additional button states, repeat steps 1–2.
4 To make the movie clip respond to mouse events, do one of the following:
■ Attach an on() event handler to the movie clip instance, as discussed in “Using button and
movie clip event handlers” on page 87.
■ Assign a function to one of the movie clip object’s mouse event handlers (onPress,
onRelease, and so forth), as discussed in “Using event handler methods” on page 83.
Event handler scope
The scope, or context, of variables and commands that you declare and execute within an event
handler depends on the type of event handler you’re using: event handlers or event listeners, or
on() and onClipEvent() handlers.
Functions assigned to event handler methods and event listeners (like all ActionScript functions
that you write) define a local variable scope, but
For example, consider the following two event handlers. The first is an
associated with a movie clip named
clip_mc. The second is an on() handler attached to the same
on() and onClipEvent() handlers do not.
onPress event handler
movie clip instance.
// Attached to clip_mc’s parent clip Timeline:
clip_mc.onPress = function () {
var color; // local function variable
color = "blue";
}
// on() handler attached to clip_mc:
on(press) {
var color; // no local variable scope
color = "blue";
}
Although both event handlers contain the same code, they have different results. In the first case,
the color variable is local to the function defined for onPress. In the second case, because the
on() handler doesn’t define a local variable scope, the variable scopes to the Timeline of the movie
clip
clip_mc.
For on() event handlers attached to buttons, rather than to movie clips, variables (as well as
function and method calls) are scoped to the Timeline that contains the button instance.
88Chapter 4: Handling Events
For instance, the following on() event handler will produce different results depending on
whether it’s attached to a movie clip or button object. In the first case, the
starts the playback head of the Timeline that contains the button; in the second case, the
play() function call
play()
function call starts the Timeline of the movie clip to which the handler is attached.
// Attached to button
on(press) {
play(); // plays parent Timeline
}
// Attached to movie clip
on(press) {
play(); // plays movie clip’s Timeline
}
That is, when attached to a button object, the play() method call applies to the Timeline that
contains the button—that is, the button’s parent Timeline. But when the same handler is attached
to a movie clip object, then the
play() applies to the movie clip that bears the handler.
Within an event handler or event listener function definition, the same
play() function would
apply to the Timeline that contains the function definition. For example, suppose the following
MovieClip.onPress event handler function were declared on the Timeline that contains the
movie clip instance
// Function defined on movie clip Timeline:
myMovieClip.onPress = function () {
play(); // plays Timeline that contains the function definition
}
myMovieClip.
If you want to play the movie clip that defines the onPress event handler, then you have to refer
explicitly to that clip using the
myMovieClip.onPress = function () {
this,play(); // plays Timeline of clip that defines the onPress handler
}
this keyword, as follows:
Event handler scope89
Scope of the “this” keyword
The this keyword refers to the object in the currently executing scope. Depending on what type
of event handler technique you’re using,
Within an event handler or event listener function, this refers to the object that defines the
event handler or event listener method. For example, in the following code
myClip itself.
// onPress() event handler attached to _level0.myClip:
myClip.onPress = function () {
trace(this); // displays '_level0.myClip'
}
this can refer to different objects.
this refers to
Within an on() handler attached to a movie clip
on() handler is attached.
// Attached to movie clip named 'myClip'
on(press) {
trace(this); displays '_level0.myClip'
}
Within an on() handler attached to a button
, this refers to the Timeline that contains the
button.
// Attached to button on main Timeline
on(press) {
trace(this); // displays '_level0'
}
, this refers to the movie clip to which the
90Chapter 4: Handling Events
CHAPTER 5
Creating Interaction with ActionScript
In simple animation, Macromedia Flash Player plays the scenes and frames of a SWF file
sequentially. In an interactive SWF file, your audience uses the keyboard and mouse to jump to
different parts of a SWF file, move objects, enter information in forms, and perform many other
interactive operations.
You use ActionScript to create scripts that tell Flash Player what action to perform when an event
occurs. Some events that can trigger a script occur when the playhead reaches a frame, when a
movie clip loads or unloads, or when the user clicks a button or presses a key.
A script can consist of a single command, such as instructing a SWF file to stop playing, or a
series of commands and statements, such as first evaluating a condition and then performing an
action. Many ActionScript commands are simple and let you create basic controls for a SWF file.
Other actions require some familiarity with programming languages and are intended for
advanced development.
About events and interaction
Whenever a user clicks the mouse or presses a key, an event is generated. These types of events are
generally called user events, because they are generated in response to some action by the end user.
You can write ActionScript to respond to, or handle, these events. For example, when a user clicks
a button, you might want to send the playhead to another frame in the SWF file or load a new
web page into the browser.
In a SWF file, buttons, movie clips, and text fields all generate events to which you can respond.
ActionScript provides three ways to handle events: event handler methods, event listeners, and
on() and onClipEvent() handlers. For more information about events and handling events, see
Chapter 4, “Handling Events,” on page 83.
91
Controlling SWF file playback
The following ActionScript functions let you control the playhead in the Timeline and load a new
web page into a browser window:
• The gotoAndPlay() and gotoAndStop() functions send the playhead to a frame or scene.
These are global functions that you can call from any script. You can also use the
MovieClip.gotoAndPlay() and MovieClip.gotoAndStop() methods to navigate the
Timeline of a specific movie clip object.
• The play() and stop() actions play and stop movies.
• The getURL() action jumps to a different URL.
Jumping to a frame or scene
To jump to a specific frame or scene in the SWF file, you can use the
gotoAndStop() global functions or the equivalent gotoAndPlay() and gotoAndStop()
gotoAndPlay() and
methods of the MovieClip class. Each function or method lets you specify a frame to jump to in
the current scene. If your document contains multiple scenes, you can specify a scene and frame
to jump to.
The following example uses the global
onRelease event handler to send the playhead of the Timeline that contains the button to
gotoAndPlay() function within a button object’s
Frame 10.
jump_btn.onRelease = function () {
gotoAndPlay(10);
}
In the next example, the MovieClip.gotoAndStop() method sends the Timeline of a movie clip
named
gotoAndPlay() and gotoAndStop(), you must specify an instance to which the method.
jump_btn.onPress = function () {
}
categories_mc to Frame 10 and stops. When you use the MovieClip methods
categories_mc.gotoAndStop(10);
Playing and stopping movie clips
Unless instructed otherwise, after a SWF file starts, it plays through every frame in the Timeline.
You can stop or start a SWF file by using the
equivalent MovieClip methods. For example, you can use
play() and stop() global functions or the
stop() to stop a SWF file at the end of
a scene before proceeding to the next scene. After a SWF file stops, it must be explicitly started
again by calling
play().
You can use the
play() and stop() functions or MovieClip methods to control the main
Timeline or the Timeline of any movie clip or loaded SWF file. The movie clip you want to
control must have an instance name and must be present in the Timeline.
The following
on(press) handler attached to a button starts the playhead moving in the SWF
file or movie clip that contains the button object.
// Attached to a button instance
on(press) {
// Plays the Timeline that contains the button
play();
}
92Chapter 5: Creating Interaction with ActionScript
This same on() event handler code will produce a different result when attached to a movie clip
object rather than a button. When attached to a button object, statements made within an
on()
handler are applied to the Timeline that contains the button, by default. However, when attached
to a movie clip object, statements made within an
which the
on() handler is attached.
on() handler are applied to the movie clip to
For example, the following
on() handler code stops the Timeline of the movie clip to which the
handler is attached, not the Timeline that contains the movie clip.
on(press) {
stop();
}
The same conditions apply to onClipEvent() handlers attached to movie clip objects. For
instance, the following code stops the Timeline of the movie clip that bears the
onClipEvent()
handler when the clip first loads or appears on the Stage.
onClipEvent(load) {
stop();
}
Jumping to a different URL
To open a web page in a browser window, or to pass data to another application at a defined URL,
you can use the
getURL() global function or the MovieClip.getURL() method. For example,
you can have a button that links to a new website, or you can send Timeline variables to a CGI
script for processing in the same way as you would an HTML form. You can also specify a target
window, just as you would when targeting a window with an HTML anchor (
<a></a>) tag.
For example, the following code opens the macromedia.com home page in a blank browser
window when the user clicks the button instance named
homepage_btn.onRelease = function () {
getURL("http://www.macromedia.com", _blank);
}
homepage_btn.
You can also send variables along with the URL, using GET or POST. This is useful if the page you
are loading from an application server, like a ColdFusion Server (CFM) page, expects to receive
form variables. For example, suppose you want to load a CFM page named addUser.cfm that
expects two form variables,
variables_mc that defines those two variables, as shown below.
To create interactivity and other visual effects, you need to understand the following techniques:
• Creating a custom mouse pointer
• Getting the mouse position
• Capturing keypresses
• Setting color values
• Creating sound controls
• Detecting collisions
• Creating a simple line drawing tool
Creating a custom mouse pointer
A standard mouse pointer is the operating system’s onscreen representation of the position of the
user’s mouse. By replacing the standard mouse pointer with one you design in Flash, you can
integrate the user’s mouse movement within the SWF file more closely. The sample in this section
uses a custom pointer that looks like a large arrow. The power of this feature, however, lies in your
ability to make the custom pointer look like anything—for example, a football to be carried to the
goal line or a swatch of fabric pulled over a couch to change its color.
To create a custom pointer, you design the pointer movie clip on the Stage. Then, in
ActionScript, you hide the standard pointer and track its the movement. To hide the standard
pointer, you use the
custom pointer, you use the
Mouse.hide() method of the built-in Mouse class. To use a movie clip as the
startDrag() action.
To create a custom pointer:
1 Create a movie clip to use as a custom pointer, and place an instance of the clip on the Stage.
2 Select the movie clip instance on the Stage.
3 Select Window > Development Panels > Actions to open the Actions panel if it is not
already visible.
4 Type the following in the Actions panel:
onClipEvent (load) {
Mouse.hide();
startDrag(this, true);
}
onClipEvent(mouseMove){
updateAfterEvent();
}
The first onClipEvent() handler hides the mouse when the movie clip first appears on the
Stage; the second handler calls
The
updateAfterEvent function immediately refreshes the screen after the specified event
updateAfterEvent whenever the user moves the mouse.
occurs, rather than when the next frame is drawn, which is the default behavior. (See
updateAfterEvent() on page 743.)
5 Select Control > Test Movie to test your custom pointer.
94Chapter 5: Creating Interaction with ActionScript
Buttons still function when you use a custom pointer. It’s a good idea to put the custom pointer
on the top layer of the Timeline so that it moves in front of buttons and other objects as you move
the mouse in the SWF file. Also, the tip of a custom mouse pointer is the registration point of the
movie clip you’re using as the custom pointer. Therefore, if you want a certain part of the movie
clip to act as the mouse tip, set the registration point coordinates of the clip to be that point.
For more information about the methods of the Mouse class, see the Mouse class entry in
Chapter 12, “ActionScript Dictionary,” on page 205.
Getting the mouse position
You can use the
(cursor) in a SWF file. Each Timeline has an
_xmouse and _ymouse properties to find the location of the mouse pointer
_xmouse and _ymouse property that returns the
location of the mouse within its coordinate system. The position is always relative to the
registration point. For the main Timeline (
_level0), the registration point is the upper
left corner.
The _xmouse and _ymouse properties within the main Timeline and a movie clip Timeline
The following procedures show two ways to get the mouse position.
To get the current mouse position within the main Timeline:
1 Create two dynamic text boxes, and name them x_pos and y_pos.
2 Select Window > Development Panels > Actions to open the Actions panel if it is not
already visible.
3 To return the mouse position within the main Timeline, add the following code to any frame
in the
x_pos = _root._xmouse;
y_pos = _root._ymouse;
_level0 SWF file:
The variables x_pos and y_pos are used as containers to hold the values of the mouse positions.
You could use these variables in any script in your document. In the following
handler, the values of
onClipEvent(mouseMove){
x_pos = _root._xmouse;
y_pos = _root._ymouse;
}
x_pos and y_pos update every time the user moves the mouse.
Creating interactivity and visual effects95
onClipEvent()
To get the current mouse position within a movie clip:
1 Create a movie clip.
2 Select the movie clip instance on the Stage. Using the Property inspector, name it myMovieClip.
3 Select Window > Development Panels > Actions to open the Actions panel if it is not
already visible.
4 Use the movie clip’s instance name to return the mouse position within the main Timeline.
For example, the following statement could be placed on any Timeline in the
file to return the
For more information about the _xmouse and _ymouse properties, see MovieClip._xmouse
on page 541 and
MovieClip._ymouse on page 543.
Capturing keypresses
You can use the methods of the built-in Key class to detect the last key pressed by the user. The
Key class does not require a constructor function; to use its methods, you simply call the methods
on the class itself, as shown in the following example:
Key.getCode();
You can obtain either virtual key codes or ASCII (American Standard Code for Information
Interchange) values of keypresses:
• To obtain the virtual key code of the last key pressed, use the getCode() method.
• To obtain the ASCII value of the last key pressed, use the getAscii() method.
A virtual key code is assigned to every physical key on a keyboard. For example, the Left Arrow
key has the virtual key code 37. By using a virtual key code, you ensure that your SWF file’s
controls are the same on every keyboard, regardless of language or platform.
ASCII values are assigned to the first 127 characters in every character set. ASCII values provide
information about a character on the screen. For example, the letter “A” and the letter “a” have
different ASCII values.
To decide which keys to use and determine their virtual key codes, use one of these approaches:
• See the list of key codes in Appendix C, “Keyboard Keys and Key Code Values,” on page 789.
• Use a Key class constant. (In the Actions toolbox, click the Built-in Classes category, click
Movie, click Key, and click Constants.)
96Chapter 5: Creating Interaction with ActionScript
• Assign the following onClipEvent() handler to a movie clip, then select Control > Test Movie
and press the desired key.
onClipEvent(keyDown) {
trace(Key.getCode());
}
The key code of the desired key appears in the Output panel.
A common place to use Key class methods is within an event handler. In the following example,
the user moves the car using the arrow keys. The
key being pressed is the right, left, up, or down arrow. The event handler,
determines the
Key.isDown(keyCode) value from the if statements. Depending on the value,
the handler instructs Flash Player to update the position of the car and to display the direction.
Key.isDown() method indicates whether the
onEnterFrame,
The input from the keyboard keys moves the car.
The following procedure shows how to capture keypresses to move a movie clip up, down, left, or
right on the Stage, depending on which corresponding arrow key (up, down, left, or right) is
currently pressed. The movie clip is confined to an arbitrary area that is 400 pixels wide and 300
pixels high. Also, a text field displays the name of the pressed key.
Creating interactivity and visual effects97
To create a keyboard-activated movie clip:
1 On the Stage, create a movie clip that will move in response to keyboard arrow activity.
In this example, the movie clip instance name is
car.
2 On the Stage, create a dynamic text box that will be updated with the direction of the car. Using
the Property inspector, give it an instance name of
Note: Don’t confuse variable names with instance names. For more information, see “About text
field instance and variable names” on page 136.
display_txt.
3 Select Frame 1 in the Timeline; then select Window > Development Panels > Actions to open
the Actions panel if it is not already visible.
4 To set how far the car moves across the screen with each keypress, define a distance variable
and set its initial value to 10.
var distance = 10;
5 To create the event handler for the car movie clip that checks which arrow key (left, right, up,
or down) is currently pressed, add the following code to the Actions panel:
car.onEnterFrame = function() {
}
6 Add a with statement to the body of the onEnterFrame handler, and specify car as the object
of the
with statement.
Your code should look like this:
var distance = 10;
car.onEnterFrame = function() {
with (car) {
}
}
7 To check if the Right Arrow key is being pressed, and to move the car movie clip accordingly,
add code to the body of the with statement. Your code should look like this:
distance = 10;
car.onEnterFrame = function() {
with (car) {
if (Key.isDown(Key.RIGHT)) {
_x += distance;
if (_x >= 400) {
_x = 400;
}
_root.display_txt.text = "Right";
}
}
}
If the Right Arrow key is down, the car’s _x property is increased by the amount specified by
the
distance variable. The next if statement tests if the value of the clip’s _x property is
greater than or equal to 400 (if(_x >=400)); if so, its position is fixed at 400. Also, the word
Right should appear in the SWF file.
98Chapter 5: Creating Interaction with ActionScript
8 Use similar code to check if the Left Arrow, Up Arrow, or Down Arrow key is being pressed.
Your code should look like this:
var distance = 10;
car.onEnterFrame = function() {
with (car) {
if (Key.isDown(Key.RIGHT)) {
_x += distance;
if (_x >= 400) {
_x = 400;
}
_root.display_txt.text = "Right";
} else if (Key.isDown(Key.LEFT)) {
_x -= distance;
if (_x < 0) {
_x = 0;
}
_root.display_txt.text = "Left";
} else if (Key.isDown(Key.UP)) {
_y -= distance;
if (_y < 0) {
_y = 0 ;
}
_root.display_txt.text = "Up";
} else if (Key.isDown(Key.DOWN)) {
_y += distance;
if (_y > 300) {
_y = 300;
}
_root.display_txt.text = "Down";
}
}
}
9 Select Control > Test Movie to test the file.
For more information about the methods of the Key class, see the Key class entry in Chapter 12,
“ActionScript Dictionary,” on page 205.
Creating interactivity and visual effects99
Setting color values
You can use the methods of the built-in Color class to adjust the color of a movie clip. The
setRGB() method assigns hexadecimal RGB (red, green, blue) values to the movie clip. The
following example uses
setRGB() to change an object’s color based on user input.
The button action creates a Color object and changes the color of the car based on user input.
To set the color value of a movie clip:
1 Select a movie clip on the Stage.
2 In the Property inspector, enter carColor as the instance name.
3 Create a button named color chip, place four instances of the button on the Stage, and name
them
red, green, blue, and black.
4 Select Frame 1 in the main Timeline, and select Window > Development Panels > Actions.
5 To create a Color object that targets the carColor movie clip, add the following code to the
Actions panel:
myColor = new Color(_root.carColor);
6 To make the blue button change the color of the carColor movie clip to blue, add the following
code to the Actions panel:
_root.blue.onRelease = function(){
myColor.setRGB(0x0000ff)
}
The hexadecimal value 0x0000ff is blue. The following table displays the other colors you’ll use
and their hexadecimal values:
100Chapter 5: Creating Interaction with ActionScript
Loading...
+ hidden pages
You need points to download manuals.
1 point = 1 manual.
You can buy points or you can get point for every manual you upload.