Learning ActionScript 2.

0 in Flash

Trademarks 1 Step RoboPDF, ActiveEdit, ActiveTest, Authorware, Blue Sky Software, Blue Sky, Breeze, Breezo, Captivate, Central, ColdFusion, Contribute, Database Explorer, Director, Dreamweaver, Fireworks, Flash, FlashCast, FlashHelp, Flash Lite, FlashPaper, Flash Video Encoder, Flex, Flex Builder, Fontographer, FreeHand, Generator, HomeSite, JRun, MacRecorder, Macromedia, MXML, RoboEngine, RoboHelp, RoboInfo, RoboPDF, Roundtrip, Roundtrip HTML, Shockwave, SoundEdit, Studio MX, UltraDev, and WebHelp 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. Opera ® browser Copyright © 1995-2002 Opera Software ASA and its suppliers. All rights reserved. Macromedia Flash 8 video is powered by On2 TrueMotion video technology. © 1992-2005 On2 Technologies, Inc. All Rights Reserved. http://www.on2.com. Visual SourceSafe is a registered trademark or trademark of Microsoft Corporation in the United States and/or other countries. Copyright © 2005 Macromedia, Inc. All rights reserved. This manual may not be copied, photocopied, reproduced, translated, or converted to any electronic or machine-readable form in whole or in part without written approval from Macromedia, Inc. Notwithstanding the foregoing, the owner or authorized user of a valid copy of the software with which this manual was provided may print out one copy of this manual from an electronic version of this manual for the sole purpose of such owner or authorized user learning to use such software, provided that no part of this manual may be printed out, reproduced, distributed, resold, or transmitted for any other purposes, including, without limitation, commercial purposes, such as selling copies of this documentation or providing paid-for support services. Acknowledgments Project Management: Sheila McGinn Writing: Jen deHaan; Peter deHaan, Joey Lott Managing Editor: Rosana Francescato Lead Editor: Lisa Stanziano Editing: Linda Adler, Geta Carlson, Evelyn Eldridge, John Hammett, Mary Kraemer, Noreen Maher, Jessie Wood, Anne Szabla Production Management: Patrice O’Neill, Kristin Conradi, Yuko Yagi Media Design and Production: Adam Barnett, Aaron Begley, Paul Benkman. John Francis, Geeta Karmarkar, Masayo Noda, Paul Rangel, Arena Reed, Mario Reynoso Special thanks to Jody Bleyle, Mary Burger, Lisa Friendly, Stephanie Gowin, Bonnie Loo, Mary Ann Walsh, Erick Vera, the beta testers, and the entire Flash and Flash Player engineering and QA teams. First Edition: September 2005 Macromedia, Inc. 601 Townsend St. San Francisco, CA 94103

Contents
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 Intended audience . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 System requirements. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 Updating Flash XML files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 About the documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 Additional resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 Chapter 1: What’s New in Flash 8 ActionScript . . . . . . . . . . . . . . 19 New in ActionScript 2.0 and Flash 8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 Changes to security model for locally installed SWF files. . . . . . . . . . 28 Chapter 2: Writing and Editing ActionScript 2.0 . . . . . . . . . . . . . 31 About ActionScript and events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 Organizing ActionScript code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 Using the Actions panel and Script window . . . . . . . . . . . . . . . . . . . . . . 35 About the Actions panel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36 About the Script window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .37 About coding in the Actions panel and Script window. . . . . . . . . . . . . 38 About Actions panel features. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58 About behaviors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61 About ActionScript publish settings. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62 Chapter 3: About ActionScript . . . . . . . . . . . . . . . . . . . . . . . . . . . .67 What is ActionScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68 About choosing between ActionScript 1.0 and ActionScript 2.0 . . . 69 Understanding ActionScript and Flash Player . . . . . . . . . . . . . . . . . . . .70 Chapter 4: Data and Data Types. . . . . . . . . . . . . . . . . . . . . . . . . . . 71 About data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71 About data types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .72 About variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86 Organizing data in objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .108 About casting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110

3

Chapter 5: Syntax and Language Fundamentals . . . . . . . . . . . . 113 About syntax, statements, and expressions . . . . . . . . . . . . . . . . . . . . . .114 About dot syntax and target paths. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118 About language punctuators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124 About constants and keywords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135 About statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .141 About arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163 About operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176 Chapter 6: Functions and Methods . . . . . . . . . . . . . . . . . . . . . . . 201 About functions and methods. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201 Understanding methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .222 Chapter 7: Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225 About object-oriented programming and Flash . . . . . . . . . . . . . . . . . .226 Writing custom class files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .235 About working with custom classes in an application . . . . . . . . . . . . .238 Example: Writing custom classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .263 Example: Using custom class files in Flash . . . . . . . . . . . . . . . . . . . . . . 276 Assigning a class to symbols in Flash . . . . . . . . . . . . . . . . . . . . . . . . . . .279 Compiling and exporting classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280 Understanding classes and scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .283 About top-level and built-in classes . . . . . . . . . . . . . . . . . . . . . . . . . . . .286 About working with built-in classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . .296 Chapter 8: Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301 About inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301 About writing subclasses in Flash . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303 Using polymorphism in an application . . . . . . . . . . . . . . . . . . . . . . . . . 308 Chapter 9: Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313 About interfaces. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313 Creating interfaces as data types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 318 Understanding inheritance and interfaces . . . . . . . . . . . . . . . . . . . . . . 320 Example: Using interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321 Example: Creating a complex interface . . . . . . . . . . . . . . . . . . . . . . . . .323

4

Contents

Chapter 10: Handling Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329 Using event handler methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330 Using event listeners . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332 Using event listeners with components . . . . . . . . . . . . . . . . . . . . . . . . . 335 Using button and movie clip event handlers . . . . . . . . . . . . . . . . . . . . . 337 Broadcasting events from component instances . . . . . . . . . . . . . . . . 342 Creating movie clips with button states . . . . . . . . . . . . . . . . . . . . . . . . . 342 Event handler scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343 Scope of the this keyword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347 Using the Delegate class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347 Chapter 11: Working with Movie Clips. . . . . . . . . . . . . . . . . . . . . . 351 About controlling movie clips with ActionScript . . . . . . . . . . . . . . . . . 352 Calling multiple methods on a single movie clip . . . . . . . . . . . . . . . . . 354 Loading and unloading SWF files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355 Changing movie clip position and appearance . . . . . . . . . . . . . . . . . . 357 Dragging movie clips . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359 Creating movie clips at runtime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 360 Adding parameters to dynamically created movie clips. . . . . . . . . . . 364 Managing movie clip depths . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 366 About caching and scrolling movie clips with ActionScript . . . . . . . 369 Using movie clips as masks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376 Handling movie clip events. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 378 Assigning a class to a movie clip symbol. . . . . . . . . . . . . . . . . . . . . . . . 378 Initializing class properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 379 Chapter 12: Working with Text and Strings . . . . . . . . . . . . . . . . . 381 About text fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 383 About loading text and variables into text fields . . . . . . . . . . . . . . . . . 392 Using fonts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 398 About font rendering and anti-alias text . . . . . . . . . . . . . . . . . . . . . . . . 406 About text layout and formatting. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .414 Formatting text with Cascading Style Sheet styles . . . . . . . . . . . . . . .421 Using HTML-formatted text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 436 Example: Creating scrolling text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 449 About strings and the String class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 450

Contents

5

Chapter 13: Animation, Filters, and Drawings. . . . . . . . . . . . . . 469 Scripting animation with ActionScript 2.0 . . . . . . . . . . . . . . . . . . . . . .470 About bitmap caching, scrolling, and performance . . . . . . . . . . . . . 480 About the Tween and TransitionManager classes . . . . . . . . . . . . . . . 481 Using filter effects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 498 Working with filters using ActionScript . . . . . . . . . . . . . . . . . . . . . . . . 505 Manipulating filter effects with code . . . . . . . . . . . . . . . . . . . . . . . . . . . 530 Creating bitmaps with the BitmapData class . . . . . . . . . . . . . . . . . . . .534 About blending modes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 537 About operation order . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 540 Drawing with ActionScript. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 540 Understanding scaling and slice guides . . . . . . . . . . . . . . . . . . . . . . . . .556 Chapter 14: Creating Interaction with ActionScript . . . . . . . . . . 561 About events and interaction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .562 Controlling SWF file playback . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .562 Creating interactivity and visual effects . . . . . . . . . . . . . . . . . . . . . . . . .566 Creating runtime data bindings using ActionScript . . . . . . . . . . . . . . .579 Deconstructing a sample script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .588 Chapter 15: Working with Images, Sound, and Video . . . . . . . . 591 About loading and working with external media . . . . . . . . . . . . . . . . 592 Loading external SWF and image files. . . . . . . . . . . . . . . . . . . . . . . . . 593 About loading and using external MP3 files . . . . . . . . . . . . . . . . . . . . .598 Assigning linkage to assets in the library . . . . . . . . . . . . . . . . . . . . . . . 602 About using FLV video . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 603 About creating progress animations for media files. . . . . . . . . . . . . . .624 Chapter 16: Working with External Data . . . . . . . . . . . . . . . . . . 633 Sending and loading variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .634 Using HTTP to connect to server-side scripts . . . . . . . . . . . . . . . . . . .638 About file uploading and downloading . . . . . . . . . . . . . . . . . . . . . . . . . 644 About XML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .652 Sending messages to and from Flash Player . . . . . . . . . . . . . . . . . . . .663 About the External API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 667 Chapter 17: Understanding Security. . . . . . . . . . . . . . . . . . . . . . .677 About compatibility with previous Flash Player security models . . . 677 About local file security and Flash Player. . . . . . . . . . . . . . . . . . . . . . . .679 About domains, cross-domain security, and SWF files . . . . . . . . . . 694 Server-side policy files for permitting access to data . . . . . . . . . . . . .702 HTTP to HTTPS protocol access between SWF files . . . . . . . . . . . . 707

6

Contents

Chapter 18: Debugging Applications . . . . . . . . . . . . . . . . . . . . . . 711 Debugging your scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 711 Using the Output panel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 724 Chapter 19: Best Practices and Coding Conventions for ActionScript 2.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 731 Naming conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Using comments in your code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ActionScript coding conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ActionScript and Flash Player optimization . . . . . . . . . . . . . . . . . . . . . Formatting ActionScript syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 732 742 745 762 764

Appendix A: Error Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . .773 Appendix B: Deprecated Flash 4 operators . . . . . . . . . . . . . . . 779 Appendix C: Keyboard Keys and Key Code Values . . . . . . . . . . 781 Appendix D: Writing Scripts for Earlier Versions of Flash Player . . . . . . . . . . . . . . . . . . . . . . . . . . .787 About targeting earlier versions of Flash Player . . . . . . . . . . . . . . . . . 787 Using Flash 8 to create content for Flash Player 4 . . . . . . . . . . . . . . 788 Appendix E: Object-Oriented Programming with ActionScript 1.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 791 About ActionScript 1.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 792 Creating a custom object in ActionScript 1.0 . . . . . . . . . . . . . . . . . . . . 794 Assigning methods to a custom object in ActionScript 1.0. . . . . . . . 795 Defining event handler methods in ActionScript 1.0 . . . . . . . . . . . . . 796 Creating inheritance in ActionScript 1.0 . . . . . . . . . . . . . . . . . . . . . . . . 798 Adding getter/setter properties to objects in ActionScript 1.0 . . . . . 800 Using Function object properties in ActionScript 1.0 . . . . . . . . . . . . . .801 Appendix F: Terminology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 803 Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 811

Contents

7

8

Contents

Introduction
Macromedia Flash Basic 8 and Macromedia Flash Professional 8 are the professional standard authoring tools for producing high-impact web experiences. ActionScript is the language you use to add interactivity to Flash applications, whether your applications are simple animated SWF files or more complex rich Internet applications. You don’t have to use ActionScript to use Flash, but if you want to provide basic or complex 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. For more information, see the following topics:
Intended audience . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 Updating Flash XML files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 System requirements. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 About the documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 Additional resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

Intended audience
This manual assumes that you have already installed Flash Basic 8 or Flash Professional 8 and know how to use the user interface.You should know how to place objects on the Stage and manipulate them in the Flash authoring environment. If you have used a scripting language before, ActionScript will seem familiar. But if you’re new to programming, ActionScript basics are easy to learn. You can start with simple commands and build more complexity as you progress. You can add a lot of interactivity to your files without having to learn (or write) a lot of code.

9

System requirements
ActionScript 2.0 does not have any system requirements in addition to Flash 8. This manual assumes that you are using the default publishing settings for your Flash files: Flash Player 8 and ActionScript 2.0. If you change either of these settings, explanations and code samples in the documentation might not work correctly. If you develop applications for earlier versions of Flash Player, see Appendix D, “Writing Scripts for Earlier Versions of Flash Player,” on page 787.

Updating Flash XML files
It is important that you always have the latest Flash XML files installed. Macromedia sometimes introduces features in dot releases (minor releases) of Flash Player. When such a release is available, you should update your version of Flash to get the latest XML files. Otherwise, the Flash 8 compiler might generate errors if you use new properties or methods that were unavailable in the version of Flash Player that came with your Flash installation. For example, Flash Player 7 (7.0.19.0) contained a new method for the System object, System.security.loadPolicyFile. To access this method, you must use the Player Updater installer to update all the Flash players that are installed with Flash. Otherwise, the Flash compiler displays errors. Remember that you can install a Player Updater that is one or more major versions ahead of your version of Flash. By doing this, you will get the XML files that you need but shouldn’t have any compiler errors when you publish to older versions of Flash Player. Sometimes new methods or properties are available to older versions, and having the latest XML files minimizes the compiler errors you get when you try to access older methods or properties.

About the documentation
This manual provides an overview of ActionScript syntax and information on how to use ActionScript when working with different types of objects. For details on the syntax and usage of every language element, see the ActionScript 2.0 Language Reference. For more information, see the following topics:
■ ■ ■ ■

“Learning ActionScript 2.0 book overview” on page 11 “About the sample files” on page 14 “Terms used in this document” on page 13 “Copy and paste code” on page 13

10

Introduction

Learning ActionScript 2.0 book overview
The following list summarizes the contents of this manual:

Chapter 1, “What’s New in Flash 8 ActionScript,” describes features that are new in ActionScript, changes to the compiler and debugger, and the new programming model for the ActionScript 2.0 language. Chapter 2, “Writing and Editing ActionScript 2.0,” describes features of the ActionScript editor within Flash that make it easier to write code. Chapter 3, “About ActionScript,” outlines what the ActionScript language is and details how to choose between which version of ActionScript to use. Chapter 4, “Data and Data Types,” describes the terminology and basic concepts about data, data types, and variables. You use these concepts throughout the manual. Chapter 5, “Syntax and Language Fundamentals,” describes the terminology and basic concepts of the ActionScript language. You use these concepts throughout the manual. Chapter 6, “Functions and Methods,” describes how to write different kinds of functions and methods and how to use them in your application. Chapter 7, “Classes,” describes how to create custom classes and objects in ActionScript. This chapter also lists the built-in classes in ActionScript and provides a brief overview of how you use them to access powerful features in ActionScript. Chapter 8, “Inheritance,” describes inheritance in the ActionScript language and describes how to extend built-in or custom classes. Chapter 9, “Interfaces,” describes how to create and work with interfaces in ActionScript. Chapter 10, “Handling Events,” describes a few different ways to handle events: event handler methods, event listeners, and button and movie clip event handlers. Chapter 11, “Working with Movie Clips,” describes movie clips and the ActionScript you can use to control them. Chapter 12, “Working with Text and Strings,” describes the different ways you can control text and strings in Flash and includes information on text formatting and FlashType (advanced text rendering, such as anti-alias text). Chapter 13, “Animation, Filters, and Drawings,” describes how to create code-based animation and images, add filters to objects, and draw using ActionScript. Chapter 14, “Creating Interaction with ActionScript,” describes some simple ways in which you can create more interactive applications, including controlling when SWF files play, creating custom pointers, and creating sound controls.

■ ■

About the documentation

11

Chapter 15, “Working with Images, Sound, and Video,” describes how to import external media files, such as bitmap images, MP3 files, Flash Video (FLV) files, and other SWF files, in your Flash applications. This chapter also provides an overview of how to work with video in your applications, and how to create progress bar loading animations. Chapter 16, “Working with External Data,” describes how to process data from external sources using server- or client-side scripts in your applications. This chapter describes how to integrate data with your applications. Chapter 17, “Understanding Security,” explains security in Flash Player, as it pertains to working with SWF files locally on your hard disk. This chapter also explains cross-domain security issues, and how to load data from servers, or across domains. Chapter 18, “Debugging Applications,” describes the ActionScript debugger within Flash that makes it easier to write applications. Chapter 19, “Best Practices and Coding Conventions for ActionScript 2.0,” explains the best practices for using Flash and writing ActionScript. This chapter also lists standardized coding conventions, such as naming variables, and other conventions. Appendix A, “Error Messages,” lists the error messages that the Flash compiler can generate. Appendix B, “Deprecated Flash 4 operators,” lists all the deprecated Flash 4 operators and their associativity. Appendix C, “Keyboard Keys and Key Code Values,” lists all the keys on a standard keyboard and the corresponding ASCII key code values that are used to identify the keys in ActionScript. Appendix D, “Writing Scripts for Earlier Versions of Flash Player,” provides guidelines to help you write scripts that are syntactically correct for the player version you are targeting. Appendix E, “Object-Oriented Programming with ActionScript 1.0,” provides information on using the ActionScript 1.0 object model to write scripts. Appendix F, “Terminology,” lists commonly used terminology when working with the ActionScript language and provides descriptions for the terms.

This manual explains how to use the ActionScript language. For information on the language elements themselves, see the ActionScript 2.0 Language Reference.

Typographical conventions
This manual uses the following typographical conventions:

Code font indicates

ActionScript code.

12

Introduction

Bold code font, typically within a procedure, indicates code that you need to modify or add to code you have already added to your FLA file. In some case, it might be used to highlight code to look at.

Boldface text indicates data you need to type into the user interface, such as a filename or instance name. Italic text indicates a new term defined in the text that follows. In a file path, it might indicate a value that should be replaced (for example, with a directory name on your own hard disk).

Terms used in this document
The following terms are used in this manual:
■ ■ ■ ■

You refers to the developer who is writing a script or application. The user refers to the person who is 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 Appendix F, “Terminology,” on page 803.

Copy and paste code
When you paste ActionScript from the Help panel into your FLA or ActionScript file, you have to be careful about special characters. Special characters include special quotation marks (also called curly quotation marks or smart quotation marks). These characters are not interpreted by the ActionScript editor, so your code throws an error if you try to compile it in Flash. You can determine that your quotation mark characters are special characters if they do not color-code correctly. That is, if all your strings do not change in color in the code editor, you need to replace the special characters with regular straight quotation mark characters. If you type a single or double quotation mark character directly into the ActionScript editor, you always type a straight quotation mark character. The compiler (when you test or publish a SWF file) throws an error and lets you know if there are the wrong kind (special quotation marks or curly quotation marks) of characters in your code.
You might also encounter special quotation marks if you paste ActionScript from other locations, such as a web page or a Microsoft Word document.
N OT E

About the documentation

13

Be cautious of proper line breaks when you copy and paste code. If you paste your code from some locations, the line of code might break in an improper location. Make sure that the color coding of your syntax is correct in the ActionScript editor if you think line breaks might be a problem. You might want to compare your code in the Actions panel to that in the Help panel to see if it matches. Try turning on Word Wrap in the ActionScript editor to help solve surplus line breaks in your code (select View > Word Wrap in the Script window, or Word Wrap from the Actions panel pop-up menu.)

Additional resources
In addition to this manual about ActionScript, there are manuals on other Flash topics, such as components and Macromedia Flash Lite. You can access each manual in the Help panel (Help > Flash Help), by viewing the default Table of Contents. Click the Clear button to see each manual that’s available; for more information, see “Where to find documentation on other subjects” on page 17. For more information about other available resources, see the following topics:
■ ■ ■ ■ ■

“About the sample files” on page 14 “Where to find PDF files or printed documentation” on page 15 “About LiveDocs” on page 15 “Additional online resources” on page 16 “Where to find documentation on other subjects” on page 17

About the sample files
There are numerous ActionScript-based sample files available that install with Flash. These sample files show you how code works in a FLA file; this is often a useful learning tool. The chapters in this manual often reference these files, but we recommend that you also check out the sample files folder on your hard disk. The sample files include application FLA files that use common Flash functionality installed with Flash. These applications were designed to introduce new Flash developers to the capabilities of Flash applications, as well as show advanced developers how Flash features work in context.

14

Introduction

You can find the ActionScript-focused sample source files in the Samples folder on your hard disk.

In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\ Samples and Tutorials\Samples\ActionScript\. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/ Samples and Tutorials/Samples/ActionScript/.

You might find the following components-focused sample files useful, because they contain a lot of ActionScript code. They’re also in the Samples folder on your hard disk:

In Windows, browse to boot drive\Program Files\Macromedia\Flash 8\ Samples and Tutorials\Samples\Components\. On the Macintosh, browse to Macintosh HD/Applications/Macromedia Flash 8/ Samples and Tutorials/Samples/Components/.

You can also find additional sample files for download on the Internet. The following web page contains links and descriptions of additional sample files: www.macromedia.com/go/ flash_samples/.

Where to find PDF files or printed documentation
If you prefer to read documentation in printed format, the PDF versions of each Help manual are available for downloading. Go to www.macromedia.com/support/documentation/ and select the product you’re interested in. You can view or download the PDF or link to the LiveDocs version of the manual. Often, you can also purchase printed documentation. For updated information, go to the Documentation support site and select Flash Basic 8 or Flash Professional 8.

About LiveDocs
You can access documentation at the LiveDocs website, in addition to accessing it from the Help panel. The LiveDocs website contains all of the Flash Help pages and might contain comments that clarify, update, or correct parts of the documentation. Click View Comments on LiveDocs at the bottom of a page in the Help panel to display the equivalent page on the LiveDocs website. Go to http://livedocs.macromedia.com to see a list of all of the available documentation in the LiveDocs format.

Additional resources

15

Technical writers monitor the LiveDocs website. One of the advantages of LiveDocs is seeing comments that clarify the documentation or correct any errata or issues that arise after a software release. LiveDocs is not the place to make help requests, such as asking questions about your code that doesn’t work, comment on problems with software or installation, or ask how to create something with Flash. It is the correct place to provide feedback about the documentation (for example, you notice a sentence or paragraph that could be clarified). When you click the button to add a comment on LiveDocs, there are several points about the kinds of comments that are acceptable on the system. Please read these guidelines closely, or your comment might be removed from the website. If you have a question about Flash, please ask it on the Macromedia web forums: www.macromedia.com/support/forums/. The web forums are the best place to ask questions, because there are many Macromedia employees, Team Macromedia volunteers, Macromedia user group managers and members, and even technical writers who monitor these forums. Engineers do not monitor the LiveDocs system but do monitor the Flash wish list. If you think you have found a bug in the software, or you would like to request an enhancement to Flash, please fill out the wishform at www.macromedia.com/go/wish. If you report your bug or enhancement request on LiveDocs, it will not be officially added to the bug database. You must use the wishform instead, if you want an engineer to see your bug or request. Remember to be careful about special characters and line breaks when you paste from the web, including LiveDocs. Macromedia has made every effort to remove all special characters from code samples, but if you have problems pasting code, see “Copy and paste code” on page 13.

Additional online resources
There are several resources online that offer a wealth of instruction, help, and guidance to help you learn Macromedia Flash 8. Check the following websites often for updates:
The Macromedia Developer Center website

(www.macromedia.com/devnet) is updated regularly with the latest information on Flash, plus advice from expert users, advanced topics, examples, tips, tutorials (including multipart tutorials), 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.

The Macromedia Weblogs website (http://weblogs.macromedia.com) provides a list of both

Macromedia employee and community weblogs (also known as blogs).

16

Introduction

com) provides numerous forums for asking specific questions about Flash. or how to solve a problem. your applications.The Macromedia web forums (http://webforums.com/community) regularly hosts Macrochats. Where to find documentation on other subjects The following manuals offer additional information on subjects commonly associated with ActionScript 2. see How to Use Help.0: ■ For information about the elements that compose the ActionScript language. For information about working in the Flash authoring environment. The Macromedia Community website (www. see Using Components.macromedia. Check the website often for updates and to register for Macrochats. or the ActionScript language. The forums are monitored by Team Macromedia volunteers and often visited by Macromedia employees as well. see the ActionScript 2.macromedia. If you’re not sure where to go. a Flash forum is a good place to start. ■ ■ Additional resources 17 .0 Language Reference. For information about working with components. a series of live presentations on a variety of topics by Macromedia employees or community members.

18 Introduction .

such as filters and blending modes. . . changes to the security model. . . . . . . The new features. see “Additions to the ActionScript language” on page 22. methods. . include new language elements (see “Additions to the ActionScript language” on page 22).CHAPTER 1 What’s New in Flash 8 ActionScript Macromedia Flash Basic 8 and Macromedia Flash Professional 8 provide several enhancements that make it easy for you to write robust scripts using the ActionScript (AS) language. . Flash Basic 8 and Flash Professional 8 introduce several new language elements for expressive features. . see the following topics: New in ActionScript 2. . . . 19 . . . . . .0. . . . . . For more information. . . additional keywords. . objects. . . .0 and Flash 8 . With each new release of Flash. . . such as JavaScript integration (ExternalInterface) and file input and output (FileReference and FileReferenceList). you must target Flash Player 8 (the default) when you publish your documents. . This section provides an overview of the ActionScript language elements and classes that are new or changed in Flash 8 and ActionScript-related improvements to the authoring tool. and application development. . . . . . which are discussed in this chapter. 19 Changes to security model for locally installed SWF files. . . . There are also ActionScript-related improvements to the Flash 8 authoring environments. For a list of specific additions to ActionScript 2. 28 1 New in ActionScript 2. . . .0 and Flash 8 The ActionScript language has grown and developed since its introduction several years ago. . . . . . . . . and other language elements were added to ActionScript. improved editing tools (see “ActionScript editing changes” on page 27). . To use any of the new language elements in your scripts. and other ActionScript-related improvements to the authoring tool. . . . . . . .

See “Configuration files that install with Flash 8” on page 65 for details. ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ 20 What’s New in Flash 8 ActionScript . see “Showing hidden characters” on page 53. and overwriting newer script files. as well as the Actions panel. The Configuration directory that includes XML files and Class files is reorganized. which means that you can attach images to the Stage or work with these assets in shared libraries. You can set a preference to reload modified script files when working on an application. for ActionScript files. see “About 9-slice scaling and movie clip symbols” on page 79 in Using Flash. You can add a name and description to your FLA file using the dialog box to help increase online search visibility. For more information. You can now add metadata information to your FLA files in the Publish Settings dialog box. The Script window feature is available in Flash Basic 8 and Flash Professional 8. or in the Flash 8 authoring tool.The following features were added to both Flash Basic 8 and Flash Professional 8 (unless noted otherwise): ■ ActionScript editor enhancements let you show hidden characters in your scripts. which include progressive JPEG images. For more information. Debug options are now available in the Script window. The Strings panel is improved to include multiline support in the String field and a language XML file. That means you can now create an ActionScript file in either program. and performance” on page 480. For more information. For information about accessing 9-slice scaling in the authoring tool. Script Assist (similar to Normal Mode in earlier editions of Flash) helps you code without needing to understand syntax. see “About bitmap caching. You can use ActionScript code to access this feature in Flash Basic 8 and Flash Professional 8. the first frame of the animation appears. For more information. For more information on Script Assist. see “About ActionScript preferences” on page 42. scrolling. which helps you avoid working with older versions of script files. see “About Script Assist” on page 58. You can load new kinds of image files at runtime. 9-slice scaling lets you scale movie clip instances without widening the strokes that outline the movie clip. You can use ActionScript code to access this property. see “About the Strings panel” on page 452. and non-animated GIF and PNG files. For more information. You can assign linkage identifiers to bitmap and sound files stored in the Library. If you load an animated file. see “Working with 9-slice scaling in ActionScript” on page 558. Bitmap caching lets you improve the performance of your applications at runtime by caching a bitmap representation of your instances.

tabIndex (MovieClip. which uses an incremental collector to improve performance.geom. see “Using complex gradient fills” on page 547. for additional safety when running SWF files on your hard disk. For more information on tab index.0 Language Reference. see “Working with filters using ActionScript” on page 505. see “About local file security and Flash Player” on page 679. you can use the Drawing API to create more complex gradients that you fill shapes with. For more information. and properties added to ActionScript 2. For more information. You can delete ASO files when you test your application. properties. The workflow for creating accessible applications is improved. You can use the FileReference and FileReferenceList API to upload files to a server. For information on filters and ActionScript. For information on local file security. For information on new line styles. Using ActionScript code. see “About font rendering and anti-alias text” on page 406.0 and Flash 8 21 . see TextField and TextFormat in the ActionScript 2. Flash Player has improved local file security. and parameters in the TextField and TextFormat classes.0 in Flash 8.ColorTransform) in the ActionScript 2. Select Control > Delete ASO files or Control > Delete ASO files and Test Movie in the authoring tool. For more information. Flash Player 8 no longer requires developers to add all objects to the tab index for content to be read correctly by a screen reader.0 Language Reference. New in ActionScript 2. ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ For a list of specific classes. including new options. see “Using ASO files” on page 282. You can use ActionScript code to apply many filters to objects on the Stage (such as movie clip instances). language elements. see “Using line styles” on page 548.tabIndex property). you can use the Drawing API to control the line style of strokes that you draw. methods. and tabIndex (TextField. You can use ActionScript code to access advanced anti-aliasing features (FlashType). see tabIndex (Button. Numerous improvements are made to text handling. For information on gradient fills. For information.■ A new garbage collector is built into Flash Player. see “Additions to the ActionScript language” on page 22. see “Setting color values” on page 572 and ColorTransform (flash.tabIndex property) in the ActionScript 2.0 Language Reference. see “About file uploading and downloading” on page 644.tabIndex property). Using ActionScript code. For more information. You can use ActionScript code to access new and advanced ways of applying and manipulating colors.

The BitmapFilter class (in flash. The following classes and language elements are new additions or newly supported in Flash Player 8. The FileReferenceList class (in the flash.display package) lets you create and manipulate arbitrarily sized transparent or opaque bitmap images.filters package) lets you apply transformations to ARGB colors and alpha values.display package) is a base class for filter effects. The BlurFilter class lets you apply blurs to objects in Flash.filters package) lets you add gradient bevels to objects.filters package) lets you add glow effects to objects.filters package) lets you add drop shadows to objects.net package) lets you upload and download files between the user’s computer and a server. The ColorTransform class (in the flash.net package) lets you select one or more files to upload.0 in Flash 8: ■ ■ The BevelFilter class (in flash. The DropShadowFilter class (in the flash. TheGradientGlowFilter class (in the flash. such as a browser with JavaScript. The BitmapData class (in flash. The FileReference class (in the flash. or the desktop application). The GradientBevelFilter class (in the flash. The IME class (in the System class) lets you manipulate the operating system’s input method editor (IME) within Flash Player. ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ 22 What’s New in Flash 8 ActionScript . The ExternalInterface class (in the flash.filters package) lets you use pixel values from a BitmapData object to perform displacement on an object.filters package) lets you apply matrix convolution filter effects.filters package) lets you add bevel effects to objects. The DisplacementMapFilter class (in the flash. The GlowFilter class (in the flash. The ConvolutionFilter class (in the flash.filters package) lets you add gradient glow effects to objects. The ColorMatrixFilter class (in flash. The following classes were added to ActionScript 2. The Color class is deprecated in favor of this class.Additions to the ActionScript language This section lists additions to ActionScript language elements and classes that are new or changed in Flash 8.geom package) lets you adjust color values in movie clips.external package) lets you communicate by using ActionScript with the Flash Player container (the system holding the Flash application.

Official support is added for the AsBroadcaster class in Flash 8. which is the rectangular region that defines nine scaling regions for the instance. depending on security restrictions. The getUTCYear property in the Date class. NO TE ■ ■ ■ ■ ■ New language elements. The function has the player show what was redrawn. which returns the year of this date.text package) provides functionality for anti-aliasing embedded fonts. which lets you cache the object as an internal bitmap representation of the instance. but does not let you control redraw regions. The isAccessible() method in the Key class returns a Boolean value that indicates whether the last key pressed may be accessed by other SWF files.lang package) lets you control how multilanguage text appears in a SWF file. according to universal time. The blendMode property in the Button class. The Rectangle class (in the flash. The Transform class (in the flash. which indicates if the system has an IME installed. The scale9Grid property in the Button class.geom package) represents a transformation matrix that determines how to map points from one coordinate space to another. The Matrix class (in the flash. which sets the blending mode for the button instance. which is an indexed array that contains each filter object associated with the button. The hasIME property in the System. The filters property in the Button class. The TextRenderer class (in the flash. ■ ■ ■ ■ ■ ■ ■ New in ActionScript 2. dirty regions that are being updated). and y represents the vertical axis).geom package) collects data about color transformations and coordinates manipulations that you apply to a MovieClip instance.geom package) lets you create and modify Rectangle objects.capabilities class.0 and Flash 8 23 . and functions added to existing classes in ActionScript include: ■ The showRedrawRegions global function provides the ability for the debugger player to outline the regions of the screen that are being redrawn (that is.geom package) represents a location in a two-dimensional coordinate system (x represents the horizontal axis. The Point class (in the flash. methods. The cacheAsBitmap property in the Button class.■ The Locale class (in the mx.

0 Language Reference.display. which is the rectangular region that defines nine scaling regions for the instance. see the BitmapData (flash.0 Language Reference. which lets you quickly scroll movie clip content and have a window viewing larger content. which is an indexed array that contains each filter object that’s currently associated with the instance.BitmapData) in the ActionScript 2. These parameters specify kinds of line styles you can use when drawing lines. For more information. The transform property of the MovieClip class. the value 404 for page not found). color transform. The attachBitmap() method of the MovieClip class. The opaqueBackground property of the MovieClip class. jointStyle. The blendMode property of the MovieClip class.Transform) in the ActionScript 2. The scale9Grid property of the MovieClip class. which attaches a bitmap image to a movie clip. The getRect() method of the MovieClip class. and the bitmap can be repeated or tiled to fill the area. ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ 24 What’s New in Flash 8 ActionScript . which lets you set the blending mode for the instance. The cacheAsBitmap property of the MovieClip class. The lineGradientStyle() method of the MovieClip class. For information. which returns properties that are the minimum and maximum coordinate values of the specified instance. The pixelHinting. The filters property of the MovieClip class. see Transform (flash. and pixel bounds.■ The onHTTPStatus event handler of the LoadVars class returns the status code that’s returned from the server (for example. interpolationMethod. For more information. which specifies a gradient line style that Flash uses when drawing a path. which lets you cache the object as an internal bitmap representation of the instance.onHTTPStatus handler) in the ActionScript 2. noScale.geom. which sets the color of the movie clip’s opaque (not transparent) background to the color that the RGB hexadecimal value specifies. The spreadMethod. This method fills a drawing area with a bitmap image. capsStyle. which fills a movie clip with a bitmap image.0 Language Reference. and miterLimit parameters of the lineStyle() method in the MovieClip class. The beginBitmapFill() method of the MovieClip class. see onHTTPStatus (LoadVars. which lets you make settings regarding a movie clip’s matrix. and focalPointRatio parameters of the beginGradientFill() method in the MovieClip class. The scrollRect property of the MovieClip class.

sandboxType property) in the ActionScript 2. which lets you use negative leading.0 and Flash 8 25 . which lets you use negative values. The kerning property in the TextFormat class. see sandboxType (security.getLocal method) in the ActionScript 2.gridFitType.■ The status parameter of the MovieClipLoader. the value 404 for page not found). which is an indexed array that contains each filter object that’s currently associated with the TextField instance. This lets you put lines of text close together in your applications. The filters property in the TextField class. You must set the antiAliasType() method to advanced if you use this property. see gridFitType (TextField.0 Language Reference. The justify value for the align property of the TextFormat class. which sets the type of anti-aliasing that you use for the TextField instance. The secure parameter of the SharedObject. so the space between lines is less than the text height. which sets the type of grid fitting that you use for the instance.security class indicates the type of security sandbox in which the calling SWF file is operating.0 Language Reference. see getLocal (SharedObject. which lets you justify a specified paragraph.onLoadComplete event handler returns the status code that’s returned from the server (for example. The indent property of the TextFormat class.0 Language Reference.getLocal() method determines whether access to this shared object is restricted to SWF files delivered over an HTTPS connection. The onLoadError event handler of the MovieClipLoader class is invoked when a file loaded with MovieClipLoader. ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ New in ActionScript 2. The sharpness property in the TextField class. The sandboxType property of the System. see onLoadComplete (MovieClipLoader.onLoadComplete event listener) in the ActionScript 2. The gridFitType property in the TextField class. The thickness property in the TextField class. For more information. For more information.gridFitType property) in the ActionScript 2. The antiAliasType property in the TextField class. For more information. You must set the antiAliasType() method to advanced if you use this property. which sets the thickness of the glyph edges in the TextField instance.loadClip() fails to load. The leading property of the TextFormat class. which lets you turn kerning on or off for the TextFormat object. which sets the sharpness of the glyph edges for the TextField instance.0 Language Reference. For information on grid fitting and TextField.

The _xscale property in the Video class. The _parent property in the Video class. which indicates the instance name of the video.0 Language Reference. which lets you set the y coordinate of the video instance. The _ymouse property in the Video class. which lets you set the amount of rotation of the video instance in degrees. The localName property of the XMLNode class. The _height property in the Video class. which lets you set the x coordinate of the video instance. For more information. For more information. which indicates the height of the video instance.■ The letterSpacing property in the TextFormat class. which lets you set the horizontal scale percentage of the video instance. see namespaceURI (XMLNode. The onHTTPStatus event handler in the XML class returns the status code that’s returned from the server (for example. ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ 26 What’s New in Flash 8 ActionScript . which lets you set the vertical scale percentage of the video instance. The _name property in the Video class. the value 404 for page not found). which is the specified amount of transparency for the video object. which returns the full name of the XML node object (including both the prefix and the local name). The _visible property in the Video class. The namespaceURI property of the XMLNode class. see onHTTPStatus (XML. The _xmouse property in the Video class. which reads the URI of the namespace to which the XML node’s prefix resolves. which indicates the movie clip instance or object that contains the video instance. The _alpha property in the Video class. The _rotation property in the Video class. The _y property in the Video class. which lets you specify the amount of space that is uniformly distributed between characters. The _width property in the Video class. The _x property in the Video class. which lets you set the y coordinate of the mouse pointer position. which lets you set the width of the video instance.0 Language Reference. which lets you set the x coordinate of the mouse pointer position. which lets you set the visibility of a video instance.onHTTPStatus handler) in the ActionScript 2.namespaceURI property) in the ActionScript 2. The _yscale property in the Video class.

which reads the prefix of the node name. For information on this feature. which returns the prefix associated with a specified namespace URI for the node. or in expert mode. The changes are summarized in this section. “Creating a startDrag/stopDrag event using Script Assist” in Using Flash. which is similar to (and more robust than) normal mode. “Writing ActionScript with Script Assist” in Using Flash. The getNamespaceForPrefix() method of the XMLNode class. see Chapter 13. For information on Script Assist. you could work in the Actions panel either in normal mode.0 and Flash 8 27 . New in ActionScript 2. you can work in Script Assist mode. and alternatives to use in Flash Player 8.0 Language Reference: ■ ■ ■ ■ Deprecated Class summary Deprecated Function summary Deprecated Property summary Deprecated Operator summary ActionScript editing changes The ActionScript editor in the Actions panel and Script window has been updated in several ways to make it more robust and easier to use than earlier versions of the tool. For a list of deprecated language elements. see “Showing hidden characters” on page 53. see the following sections in the ActionScript 2. View hidden characters You can now use the Options pop-up menu in the Script pane.■ ■ The prefix property of the XMLNode class. The getPrefixForNamespace method of the XMLNode class. in which you filled in options and parameters to create code. in Flash Basic 8 and Flash Professional 8. These options were not available in Flash MX 2004 or Flash MX Professional 2004. which returns the namespace URI associated with the specified prefix for the node. ■ About deprecated language elements Some language elements are deprecated in Flash Player 8. However. Debugger panel. Script assist added to Actions panel In previous versions of Flash. and Output panel to view or hide hidden characters when you’re writing script files in the Actions panel or Script window. in which you added commands directly into the Script pane. For a tutorial on Script Assist. see Chapter 13.

rather than run from a remote web server. In Flash Player 8. This feature is particularly beneficial to teams working on applications at the same time. you could test a Flash application that runs locally and also accesses the Internet. a SWF file cannot make connections to the local file system and the network (such as the Internet) in the same application without making a security setting. prompting you to reload the modified script files associated with the application you’re working on. and does not include projector (EXE) files. In Flash Player 8. N OT E 28 In previous versions of Flash Player. or overwriting newer versions of a script. What’s New in Flash 8 ActionScript . your file is trusted because it is in the test environment. For more information. a local SWF file is a SWF file that is locally installed on a user’s computer. When you develop a Flash application. not served from a website. In this description. so a SWF file cannot read files on your hard disk and then send the contents of those files across the Internet. Using the Flash MX 2004 or earlier authoring tool. A warning message appears. in that it helps you avoid working with outdated scripts. When you test a file on your hard disk. local SWF files could interact with other SWF files and load data from any remote or local computer without configuring security settings. you must indicate whether a SWF file is allowed to communicate with a network or with a local file system. Changes to security model for locally installed SWF files Flash Player 8 has a new. improved security model in which Flash applications and SWF files on a local computer can communicate with the Internet and the local file system.Reload modified files You can reload modified script files when working on an application. see “About ActionScript preferences” on page 42. a warning message appears and prompts you to save the files as necessary. this application now prompts the user for permission to communicate with the Internet. whether it’s legacy content (a FLA file created in an earlier version of Flash) or created in Flash 8. If you create the file in the Flash authoring environment (for example. there are several steps to determine whether the file is a local trusted (safe) document or a potentially untrusted (unsafe) document. This is for your safety. If a script file was moved or deleted. when you select Control > Test Movie). This security restriction affects all locally deployed content.

“Understanding Security. see “About local file security and Flash Player” on page 679. There are also minor changes to System. ■ ■ For more details about each level of permission.security.” Changes to security model for locally installed SWF files 29 . read from and write to any server that grants it permission. The local SWF file can access the network only (such as the Internet) and not the local file system where the SWF file is installed. Access to both the local file system and the network. local SWF files can have three levels of permission: ■ Access the local file system only (the default level). The local SWF file can read from the local file system where the file is installed.allowInsecureDomain. and can cross-script other SWF files on either the network or the local file system that grant it permission. The local SWF file can read from the local file system and universal naming convention (UNC) network paths and cannot communicate with the Internet.security. For more information on local file security. In Flash Player 8.allowDomain and improvements to System. see Chapter 17. Access the network only. local SWF files had permissions to access both the local file system and the network.In Flash Player 7 and earlier.

30 What’s New in Flash 8 ActionScript .

2 31 .0 When you write ActionScript code in Macromedia Flash Basic 8 or Macromedia Flash Professional 8. These tools include the Actions toolbox.) In the Script window. code formatting. which gives you quick access to the core ActionScript language elements. see “About behaviors” on page 61. The Actions panel contains the ActionScript editor in a Script pane and supporting tools to make writing scripts easier. debugging. and support for Unicode in two different views. For more information about behaviors. You can use one of two methods to write ActionScript code in Flash. When you write scripts inside a FLA file. see “About Script Assist” on page 58. in which you are prompted for the elements needed to create scripts. syntax highlighting. The Actions panel and Script window contain a full-featured code editor (called the ActionScript editor) that includes code hinting and coloring. Behaviors are predefined ActionScript functions that you can attach to objects in your Flash document without having to create the ActionScript code yourself. syntax checking. For more information about Script Assist. You cannot use the Actions panel to write external scripts. or you can write external scripts (scripts or classes that are stored in external files). syntax checking. you use the Actions panel or Script window. Flash offers further scripting assistance through behaviors. You can write scripts that are part of your Flash document (that is. line numbers. For more information about the Script window. see “About the Actions panel” on page 36. For more information about the ActionScript editor. the ActionScript editor includes code-assistance features like code hinting and coloring. For more information about the Actions panel. see “About the Script window” on page 37. word wrapping. see “Using the Actions panel and Script window” on page 35. the Script navigator. which helps you navigate between all of the scripts in your document. and Script Assist mode. you use the ActionScript editor in the Script window to create a new ActionScript file. (You can also use your favorite text editor to create an external AS file. and so on just like the Actions panel. scripts that are embedded in the FLA file). When you need to create an external script.CHAPTER 2 Writing and Editing ActionScript 2. you use the ActionScript editor in the Actions panel.

. which occur when a user interacts with your Flash application through the mouse and keyboard. . . . . 62 About ActionScript and events In Macromedia Flash Basic 8 and Macromedia Flash Professional 8. . . . . . . . . . . . . . see the following sections: About ActionScript and events . . . . . . . . . . . . . . 35 About the Actions panel . . . the on(keyPress) event occurs. . . . when a keyframe on the timeline is entered. . . . . . . . . . . . . . . . . . . . . . 37 About coding in the Actions panel and Script window. . . . . . . . . . . . . . and frame events. . . . . . . . . .0 . . . Events can be triggered either by the user or by the system. . and so on). . . .onRelease event occurs. . Understanding when and where events occur will help you to determine how and where you will respond to the event with an action. . . . . . . . . . . You can write code on a frame or attach scripts to an instance to handle these events and add all the interactivity you desire. . . . Users click mouse buttons and press keys. . . . . . . . . . . . . . or when the user clicks a button. . . . . . . . . . . . . . . . . . . . . . . Events can be grouped into a number of categories: mouse and keyboard events. . . . . . . . . if a key on the keyboard is pressed. . . see “About writing scripts to handle events” on page 35. . . . . . . . . . . . . . . 36 About the Script window . . . . . . . 61 About ActionScript publish settings. . . . . . . . . For example. . . . . . . . . . . . . . . . the Button. . . . . . . . . . . . . . . . . . . .onRollOver or on(rollOver) event occurs. . . . For information about the kinds of scripts you can write to handle events. . . . . . . Mouse and keyboard events A user interacting with your SWF file or application triggers mouse and keyboard events. . . . . . . . . . . . . . . . . . . . 32 Organizing ActionScript code . see “About writing scripts to handle events” on page 35. . . . the timeline reaches a certain frame. . . . . . . . . . . . . . . . . . . .For more information on handling events. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38 About Actions panel features. . . . . . . . . . . . . . . . which occur within frames on the timeline. . . . . . . . . . . . . . when a movie clip is loaded. . . . . . . . 58 About behaviors . . . . and which ActionScript tools to use in each case. . the system triggers events when specific conditions are met or processes completed (the SWF file loads. . 32 Writing and Editing ActionScript 2. . . you write an event handler to respond to the event with an action. ActionScript code is executed when an event occurs: for example. . . . . . . . . . which occur within movie clips. . . clip events. . . . . . . . the Button. . . . . . . . . . . . . . when the user rolls over a button. when the user clicks a button. . . When an event occurs. . . . . . . . . . . . . . . . . 33 Using the Actions panel and Script window . For more information. . . . a graphic finishes downloading. . .

Organizing ActionScript code You may attach scripts to keyframes and to object instances (movie clips. for example.Clip events Within a movie clip. and other symbols). Therefore. You might. Frame events On a main or movie clip timeline. it’s important to follow best practices for coding when you create ActionScript in Flash. you may react to a number of clip events that are triggered when the user enters or exits the scene or interacts with the scene by using the mouse or keyboard. However. This is done with the stop() function. and so on. You could. use a frame script to dynamically update the value of a label. A script attached to a frame is called a frame script. When you’ve stopped the SWF file at a certain keyframe. One of the most common uses of frame scripts is to stop the playback when a certain keyframe is reached. for example. or allow the user’s mouse movements to reposition elements in the scene. to manage the interaction of elements on the Stage. it is executed when the keyframe is reached during playback. a system event occurs when the playhead enters a keyframe—this is known as a frame event. debugging your application will be much more difficult. When you add a script to a keyframe. It will also be difficult to share your code between different Flash applications. you need to take some action. if your ActionScript code is scattered over many keyframes and object instances. load an external SWF file or JPG image into the movie clip when the user enters the scene. Organizing ActionScript code 33 . buttons. You select a keyframe and then add the stop() function as a script element in the Actions panel. Frame events are useful for triggering actions based on the passage of time (moving through the timeline) or for interacting with elements that are currently visible on the Stage.

If sharing your code between other Flash applications is important to you./core/Functions. you’re embedding all your code in the FLA file. movie clips. You must store custom classes in external AS files and use import statements in a script to get the classes exported into the SWF file. see “Writing custom class files” on page 235 and “About importing class files” on page 239 about importing class files. you use the Actions panel. such as UI elements and scripts. An external file aids debugging and also source control management if you’re working on a project with other developers. if you make any changes to an external file. For more information on writing class files. you should respond to events by calling functions that reside in a central location. export. you create a script within the FLA file and then use the #include statement to access the code you’ve stored externally. see “ActionScript coding conventions” on page 745. When you use the Actions panel or Script window is dictated by how you respond to events. test.Rather than attaching your scripts to elements like keyframes.. most importantly. the Script window. For more information about coding best practices and conventions. this convenience becomes much more useful than you might imagine. A common practice is to create a layer called actions and place your ActionScript code there. You can also use components (prebuilt movie clips) to share code and functionality. as shown in the following example: #include ". One method is to attach embedded ActionScript to the first or second frame of a timeline whenever possible so you don’t have to search through the FLA file to find all your code. and buttons. and. you make your code more modular and well organized. Writing and Editing ActionScript 2. coding best practices.as" You can also use ActionScript 2. you must save the file and recompile any FLA files that use it. or both. how you organize your code. When you attach all your scripts to individual elements. instead of using #include statements. Therefore.0 .0 to create custom classes. To use the ActionScript code contained in an external AS file. As your project grows. or debug a FLA file. use the Script window or your favorite text editor to create an external ActionScript (AS) file. N OT E 34 When you write ActionScript in Flash 8. By creating an external file. ActionScript code in external files is compiled into a SWF file when you publish.

Instead. format. The interactivity of your SWF file or application can be scattered over the many elements in your project. do one of the following: ■ ■ ■ To begin writing a new script. Macromedia recommends that you do not add scripts directly to these elements (keyframes and objects). To create external scripts that you include or import into your application. To display the Script window. and then open an existing AS file. which are predefined ActionScript functions (see “About behaviors” on page 61). you are using features of the ActionScript editor to write. Both the Actions panel and Script window have the Script pane (which is where you type your code) and the Actions toolbox. you enter ActionScript directly into the Actions panel. do one of the following: ■ ■ Select Window > Actions. select File > Open. buttons. Flash offers these features in the Actions panel because they are especially useful in the context of editing ActionScript within a FLA file. To display the Actions panel. and edit your code. see the following topics: ■ ■ Using the Actions panel and Script window 35 . you should respond to events by calling functions that reside in a central location. as described in “Organizing ActionScript code”. To edit a script that is already open. other workflow and code organization issues must be considered. However. When you use the Actions panel or Script window. select File > New and then select ActionScript File. “About the Actions panel” on page 36 “About the Script window” on page 37 For more information.When you use behaviors. and you may be tempted to add scripts directly to these elements. you can use the Script window (File > New and then select ActionScript File) or your preferred text editor. The Actions panel offers a few more code-assistance features than the Script window. To open an existing script. and components). click the document tab that shows the script’s name. Using the Actions panel and Script window To create scripts within a FLA file. Press F9. About writing scripts to handle events Writing code for events can be categorized into two major groups: events that occur on the timeline (in keyframes) and those that occur on object instances (move clips.

the script gets pinned (locked in place). The Actions panel consists of three panes.About the Actions panel You use the Actions panel to create ActionScript in a Flash document (a FLA file). 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. and so on) and then insert them into the Script pane. see “About the Actions panel and Script window toolbars” on page 39. You can also add language elements to your scripts by using the Add (+) button on the Actions panel toolbar. types. Actions toolbox Script navigator Script pane Pop-up menu Actions toolbox Use the Actions toolbox to browse a categorical list of ActionScript language elements (functions. each of which supports you in creating and managing scripts. You can insert a script element into the Script pane either by double-clicking or dragging it directly into the Script pane. frames. classes. For more information. and buttons) that contain scripts.0 . Use the Script navigator to move quickly between all the scripts in your Flash document. For more information. see “Pinning scripts in the Actions panel” on page 59. If you doubleclick an item in the Script navigator. Script navigator The Script navigator displays a hierarchical list of Flash elements (movie clips. 36 Writing and Editing ActionScript 2.

code hinting. Depending upon the type of external script file you create. the Actions toolbox provides you with a complete list of the language elements available for each. You can create external ActionScript. About the Script window 37 . see “Using the Actions panel and Script window” on page 35. see the following topics: ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ “About the Actions panel and Script window toolbars” on page 39 “About ActionScript editing options” on page 41 “About code hinting in Flash” on page 44 “Formatting code” on page 50 “Using syntax highlighting” on page 51 “Using line numbers and word wrap” on page 52 “Using Escape shortcut keys” on page 52 “Showing hidden characters” on page 53 “Using the Find tool” on page 54 “Checking syntax and punctuation” on page 55 “Importing and exporting scripts” on page 56 About the Script window You can write and edit ActionScript in the Script window when you create a new ActionScript. code hinting. see “About coding in the Actions panel and Script window” on page 38. and behaviors are unavailable. and Flash JavaScript files in the Script window. For more information on features in the Actions panel.Script pane The Script pane is where you type your code. or Flash JavaScript file. and other features that simplify creating scripts. The Script pane provides you with tools to create scripts in a full-featured editor (called the ActionScript editor) that includes code syntax formatting and checking. When you use the Script window. not for creating an external script file. debugging. code coloring. You use the Script window to write and edit external script files. Script Assist mode. you’ll notice that some of the other code-assistance features like Script navigator. ActionScript communication. Flash Communication. and other editor options are supported in the Script window. This is because these features are only useful in the context of creating a Flash document. For more information. Syntax coloring. For information on each of the buttons in the Actions panel toolbar.

filenames are displayed on tabs across the top of the Script window. Features that help you edit code are accessible from the toolbar in the Actions panel or Script window. through the menu system. The Script window supports the following editor options: the Actions toolbox. hidden characters. find and replace. automatic formatting. 2. and debug options (ActionScript files only). Flash Communication file. The Actions panel and Script window offer basic script editing and codeassistance features like code hinting. see the following topics: ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ “About the Actions panel and Script window toolbars” on page 39 “About ActionScript editing options” on page 41 “About code hinting in Flash” on page 44 “Formatting code” on page 50 “Using syntax highlighting” on page 51 “Using line numbers and word wrap” on page 52 “Using Escape shortcut keys” on page 52 “Showing hidden characters” on page 53 “Using the Find tool” on page 54 “Checking syntax and punctuation” on page 55 “Importing and exporting scripts” on page 56 About coding in the Actions panel and Script window The Script pane. To display the Script window: 1. the Script window supports displaying line numbers. You can have multiple external files open at the same time. Select File > New. is the primary element of both the Actions panel and the Script window. or Flash JavaScript file). code hinting. where you edit code. For more information on features in the Script window. Additionally. syntax checking. automatic formatting. 38 Writing and Editing ActionScript 2. and word wrap.0 . coloring. and in the Script pane itself. and so on.You will also notice that many of the options available in the Actions panel are unavailable in the Script window. Select the type of external file you want to create (ActionScript file.

The following topics present the many features of the ActionScript editor (Actions panel and Script window): ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ “About the Actions panel and Script window toolbars” on page 39 “About ActionScript editing options” on page 41 “About ActionScript preferences” on page 42 “About code hinting in Flash” on page 44 “Formatting code” on page 50 “Using syntax highlighting” on page 51 “Using line numbers and word wrap” on page 52 “Using Escape shortcut keys” on page 52 “Showing hidden characters” on page 53 “Using the Find tool” on page 54 “Checking syntax and punctuation” on page 55 “Importing and exporting scripts” on page 56 For features specific only to the Actions panel. such as script pinning and the Script navigator. see “About Actions panel features” on page 58. About the Actions panel and Script window toolbars The Actions panel and Script window toolbars contain links to the code-assistance features that help simplify and streamline coding in ActionScript. The toolbars are different depending on whether you are using the ActionScript editor in the Actions panel or the Script pane. Add a new item to the script Find Insert target path * Debug Options * Script Assist * Pop-up menu * Show Code Hint Auto Format Check Syntax Reference * Actions panel only About coding in the Actions panel and Script window 39 . The marked options are only available in the Actions panel. The following image displays features found in the Actions panel toolbar.

This option is disabled for ActionScript Communication and Flash JavaScript files. see “Setting and removing breakpoints” on page 720. Format your script for proper coding syntax and improved readability. you can use Show Code Hint to manually display a code hint for the line of code you’re working on. but only for ActionScript files. Reference Script Assist Writing and Editing ActionScript 2. Find NO TE 40 Find and replace text in your ActionScript code. Insert target path Actions panel only. see “Checking syntax and punctuation” on page 55. Syntax errors are listed in the Output panel. see “Using the Find tool” on page 54.0 . For more information. For more information. Selecting an item from the categorized list of language elements adds it to the script. see “About Script Assist” on page 58. In Script Assist mode. Actions panel only. Debug options are now available in the Script window as well as the Actions panel. A quick summary of the buttons you find on the toolbars of both the Actions panel and the Script window follows. Check Syntax Check for syntax errors in the current script. For more information about debugging your Flash documents. Display a reference Help topic for the ActionScript language element that is selected in the Script pane. Add a new item to the script Display all of the language elements that are also in the ActionScript toolbox.The features you find in the toolbar are discussed in detail in “Using the Actions panel and Script window” on page 35. You can set autoformatting preferences in the Preferences dialog box. For more information. if you click an import statement and then click Reference. the Help topic for import appears in the Help panel. see “About Script Assist” on page 58. you are prompted to enter the elements needed to create scripts. These features are marked Actions panel only. Show Code Hint If you’ve turned off automatic code hinting. see “Formatting code” on page 50. which is available from the Edit menu or from the Actions panel pop-up menu. For information about setting and removing breakpoints. Debug Options Auto Format Set and remove breakpoints in your script so that when you debug your Flash document. For more information. you can stop and then proceed line by line through your script. see “Debugging your scripts” on page 711. Some of the following options are found in the Actions panel only. For more information. For more information. Assists you in setting an absolute or relative target path for an action in the script. see “Inserting target paths” on page 60. For example.

The Actions panel provides more options than are available in the Script window. If you customize the Script assist mode by writing custom methods. these options are available in the toolbar and the Flash menu system. see “Using the Find tool” on page 54. see “About ActionScript editing options” on page 41. Contains the many commands and preferences that apply to the Actions panel or Script window. The following options are available from the Actions panel pop-up menu. For more information. When you edit ActionScript in the Script window. and import or export scripts. Locates and highlights the specified line in the Script pane. For more information. Find again Repeats the find action for the last search string that you entered in the Find tool. For example. For information about which of these options are available in the Script window. you can set line numbers and word wrapping in the ActionScript editor. About ActionScript editing options The Script window and Actions panel provide you with many code-assistance features—tools that make writing and maintaining your scripts much easier. Close all scripts Go to line Find and replace Finds and replaces text within your scripts in the Script pane.Pop-up menu Actions panel only. These tool options are available from the Actions panel or Script window toolbar and the Actions panel pop-up menu. see “Using the Find tool” on page 54. The options that are available in the Script window and Actions panel are discussed in “About the Actions panel and Script window toolbars” on page 39. Pins (locks in place) the script currently displayed in the Script pane. About coding in the Actions panel and Script window 41 . Actions panel only. but not when writing external ActionScript files. This is because these additional options are useful in the context of creating ActionScript embedded into a Flash document. access the ActionScript preferences. For more information. Actions panel only. Closes all currently open scripts. These features are marked Actions panel only. Some of the following options are found in the Actions panel only. and from a variety of menus in the Script window. NO T E Actions panel only. see “About the Script window” on page 37. see “Pinning scripts in the Actions panel” on page 59. For more information. Closes the currently open script. Close script Pin script Reload code hints Actions panel only. you can reload code hints without restarting Flash 8.

tabs. For example.0 . You can. Hidden characters are spaces. the Actions panel pop-up menu includes the Print. and line breaks. for example. For more information. In addition. Displays line numbers in the Script pane. code hinting and coloring. select Word Wrap from the View menu. and click ActionScript in the Category list. About ActionScript preferences Whether you edit code in the Actions panel or the Script window. control automatic indentation. Displays the ActionScript preferences dialog box. the gotoAndPlay() function is inserted into the script. For more information. Hidden characters Line numbers View hidden characters in your script. and panel resizing commands. Help. see “Using line numbers and word wrap” on page 52. For more information. For more information. When you select the Esc Shortcut Keys option from the Actions panel pop-up menu. see “Using Escape shortcut keys” on page 52.Import script Allows you to import a script file (ActionScript) into the Script pane. When you are using the Script window. and a number of other basic code editing features. see “Import and export preferences” on page 57. see “About ActionScript preferences” on page 42. all of the available Escape shortcut keys appear in the Actions toolbox. To access ActionScript preferences: 1. To access ActionScript preferences in a FLA file with the Actions panel. Preferences Actions panel only. select Word Wrap from the Actions panel pop-up menu. For more information. when you press Esc+g+p in the Script pane. or Edit > Preferences (Windows) or Flash > Preferences (Macintosh). For more information. Group Actions with Actions panel only. Export script Exports the current script to an external ActionScript (AS) file. select Preferences from the pop-up menu. see “Import and export preferences” on page 57. Esc shortcut keys Quickly enter common language elements and syntax structures into your scripts. see “Using line numbers and word wrap” on page 52. For more information. see “Showing hidden characters” on page 53. Allows you to group the Actions panel (which includes the Actions toolbox and the Script navigator) with other panels within the Flash authoring environment. 42 Writing and Editing ActionScript 2. you can set and modify a single set of preferences. Word wrap To wrap the lines of your script that exceed the current size of the Script window.

To access ActionScript preferences in the Script window. About coding in the Actions panel and Script window 43 . see “About code hinting in Flash” on page 44. You can set the following preferences: Automatic indentation When automatic indentation is turned on. see “Formatting code” on page 50. select Edit > Preferences and then click ActionScript (Windows) or Flash > Preferences and then click ActionScript (Macintosh). Tab size Enables code hinting in the Script pane. For more information about using code hinting. For more information. the text you type after an opening parenthesis [(] or opening curly brace ({) is automatically indented according to the Tab Size setting in ActionScript preferences. Specifies the font used in the Script pane. The following image shows the ActionScript settings you can change in Flash 8. Delay Font Code hints Specifies the delay (in seconds) before code hints are displayed. Specifies the number of characters a new line is offset by when automatic indentation is turned on.2.

Use dynamic font mapping Checks to ensure that the selected font family has the necessary glyphs to render each character. you can select the colors to be displayed in the Script pane. Prompt Never ■ When building applications that involve external script files. Never. Flash substitutes a font family that contains the necessary characters.0 . The following sections show you how to write code that uses these features. (Default) Warning is displayed when a change is detected. About code hinting in Flash When you use the Actions panel or the Script window. or publishing the application with older versions of scripts. Reload modified files Lets you select when to see warnings about whether a script file is modified. For more information. If not. or Prompt. and the file is automatically reloaded. Code hints help you write code quickly and accurately. moved. importing. and you can choose whether or not to reload the file. and exporting ActionScript files. saving. Code hinting includes tooltips that contain correct syntax. see “Importing and exporting scripts” on page 56. Encoding Specifies the character encoding used when opening. For more information. see “Modifying the classpath” on page 63. Specifies the colors for code coloring in your scripts. Language Syntax colors Opens the ActionScript Settings dialog box. The warnings let you automatically close a script. this feature helps you avoid overwriting a script that a team member has modified since you opened the application. Select between Always. ■ Always No warning is displayed when a change is detected. see “Formatting code” on page 50. and the file remains in the current state. and reopen the newer. you can use several features to help you write syntactically correct code. ■ No warning is displayed when a change is detected. With code coloring enabled. For more information. and menus that let you select method and property names. modified version. ■ ■ ■ ■ ■ “About triggering code hints” on page 45 “Using code hints” on page 45 “About typing objects to trigger code hints” on page 48 “About using suffixes to trigger code hints” on page 48 “About using comments to trigger code hints” on page 50 44 Writing and Editing ActionScript 2. or deleted.

do one of the following: In the Actions panel or Script window. you might prefer no delay. you can still display a code hint for a specific command.About triggering code hints When you work in the Actions panel or Script window. such as Math. you can specify a delay so that code hints don’t appear when you don’t plan to use them. if you usually know what you want to type and need hints only when you use unfamiliar language elements. To specify settings for automatic code hints. The two different styles of code hint are a tooltip that contains the complete syntax for that action. If you enable code hints. select Preferences from the pop-up menu (at the upper-right of the Actions panel) and enable or disable Code Hints in the ActionScript preferences. Using code hints Code hints are enabled by default. and events when you use strict typing or naming for your objects. and then enable or disable Code Hints. Key. select Edit > Preferences (Windows) or Flash > Preferences (Macintosh). and a pop-up menu that lists possible method or property names (sometimes referred to as a form of code completion). By setting preferences. For example. click ActionScript in the Category list. Mouse. Flash can detect what action you are entering and display a code hint. However. A pop-up menu appears for parameters. For information on using code hints when they appear. About coding in the Actions panel and Script window 45 . as discussed in the rest of this section. see “About the Actions panel” on page 36. NO TE ■ ■ To ensure that code hints are enabled. you can also specify a delay in seconds before the code hints should appear. For more information. and so on. properties. Code hinting is enabled automatically for native classes that don’t require you to create and name an instance of the class. When code hints are disabled in preferences. the Code Hints options must be selected in the ActionScript Preferences dialog box. see “Using code hints” on page 45. Code hints sometimes appear if you double-click an item in the Actions toolbox or click Add (+) in the Actions panel or Script window toolbar to add actions to the Script pane. if you are new to ActionScript. so that code hints always appear immediately. In the Actions panel. you can disable code hints or determine how quickly they appear.

To work with tooltip-style code hints: 1. If a code hint doesn’t appear. and so on). Click the small arrow buttons or press Control+Left Arrow and Control+Right Arrow to select the parameter. select Edit > Preferences (Windows) or Flash > Preferences (Macintosh) from the main menu. Display the code hint by typing an opening parenthesis [(] after an element that requires parentheses (for example. such as the for loop.0 . 2. separate the parameters with semicolons.. 46 Writing and Editing ActionScript 2. 3. Enter a value for the parameter. make sure you didn’t disable Code Hints in the ActionScript preferences (Edit > Preferences (Windows) or Flash > Preferences (Macintosh) and then click ActionScript in the Category list). In the Actions panel or Script window. make sure that you named your variable or object correctly (see “About using suffixes to trigger code hints” on page 48) or that you use strict typing for your variable or object (see “About typing objects to trigger code hints” on page 48). If more than one parameter is present. N OT E 2. Use the slider to select an amount of delay. The amount of delay is in seconds. after a method name. Overloaded commands (functions or methods that can be invoked with different sets of parameters) such as gotoAndPlay() or for display an indicator that lets you select the parameter you want to set.while. Click ActionScript in the Category list. a command such as if or do.To specify a delay for code hints: 1. To display code hints for a variable or object you created. For functions or statements. separate the values with commas. The code hint appears.

make sure that you named your variable or object correctly (see “About using suffixes to trigger code hints” on page 48) or that you used strict typing for your variable or object (see “About typing objects to trigger code hints” on page 48). Press Escape. Click in a code location where code hints can appear. To select an item in the menu. 4. do one of the following: ■ ■ ■ Type a closing parens [)]. or double-click the item. where a property or method must be entered Between parentheses [()] in a method name ■ About coding in the Actions panel and Script window 47 . Press Escape. The code hint menu appears. To dismiss the code hint. To work with menu-style code hints: 1. Type a closing parens [)] if you’ve already typed an opening parens [(]. NO T E 2. Click above or below the menu window. To navigate through the code hints. Click outside the statement. such as in the following locations: ■ After the dot (. To display code hints for a variable or object you created. Display the code hint by typing a period after the variable or object name. make sure you didn’t disable code hints in the ActionScript preferences (Edit > Preferences (Windows) or Flash > Preferences (Macintosh) and then click ActionScript in the Category list). press Enter or Tab. If a code hint doesn’t appear.3. To dismiss the code hint. use the Up and Down Arrow keys. To manually display a code hint: 1.) following a statement or command. 3. do one of the following: ■ ■ ■ ■ Select one of the menu items.

get(). you must add a special suffix to the name of each object when you create it. For example. respectively. because you have typed the variable as an array. If you do so.0 . code hints appear.2. For information on using code hints when they appear. Array. Press Control+Spacebar (Windows) or Command+Spacebar (Macintosh). About typing objects to trigger code hints When you use ActionScript 2. For example. 48 Writing and Editing ActionScript 2. About 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 “About typing objects to trigger code hints” on page 48). the suffixes that trigger code hinting for the Array class and the Camera class are _array and _cam. Code hints for the Array and Camera objects will appear. For more information on data typing. names. Flash displays a list of methods and properties available for Array objects in a pop-up menu. use the suffix in the Instance Name text box in the Property inspector. For example. and so on. see “About assigning data types and strict data typing” on page 81. Although suffixes are not required for triggering code hints when you use strict typing for an object. you can use strict typing for a variable that is based on a built-in class. For example. Then. the Script pane displays code hints for the variable. if you type the following code var my_array = new Array(). var my_cam = Camera.). suppose you type the following code: var names:Array = new Array(). For objects that appear on the Stage. As soon as you type the period (. select Show Code Hint from the pop-up menu. Do one of the following: ■ ■ ■ Click Show Code Hint in the Actions panel or Script window toolbar.0. to display code hints for MovieClip objects. my_cam. you can type either of the following (the variable name followed by a period): my_array. see “Using code hints” on page 45. such as Button. If you are working in the Actions panel. use the Property inspector to assign instance names with the _mc suffix to all MovieClip objects. using suffixes consistently helps make your code understandable. whenever you type the instance name followed by a period.

About coding in the Actions panel and Script window 49 .The following table lists the suffixes required for support of automatic code hinting: Object type Array Button Camera Color ContextMenu ContextMenuItem Date Error LoadVars LocalConnection Microphone MovieClip MovieClipLoader PrintJob NetConnection NetStream SharedObject Sound String TextField TextFormat Video XML XMLNode XMLSocket Variable suffix _array _btn _cam _color _cm _cmi _date _err _lv _lc _mic _mc _mcl _pj _nc _ns _so _sound _str _txt _fmt _video _xml _xmlnode _xmlsocket For information on using code hints when they appear. see “Using code hints” on page 45.

Macromedia recommends that instead of this technique. code that you imported from another editor. For more information on using code hints. 50 Writing and Editing ActionScript 2. in the Script window. and so on. see “Using code hints” on page 45. To see the effect of each selection. // Object theObject. // MovieClip theMc. and so on. 2. which ensures that the correct fonts are used when working with multilingual text. Alternatively. However. code hints that display the list of MovieClip methods and properties would appear. select Edit > Preferences (Windows) or Flash > Preferences (Macintosh). // Array theArray. You must manually format code that was formatted using different settings. select Auto Format. If you were to enter mc followed by a period after these comments. Formatting code You can specify settings to determine if your code is formatted and indented automatically or manually. After you set Auto Format options. select Preferences from the pop-up menu (at the upper right of the Actions panel). but not to existing code. In the Preferences dialog box. a menu that displays a list of Array methods and properties would appear. If you were to enter theArray followed by a period. you can select whether to use dynamic font mapping. your settings are applied automatically to code you write. To set format options: 1. look in the Preview pane. select Auto Format. The following example tells ActionScript that the class of the theObject instance is Object. In addition. In the Actions panel. you use strict data typing (see “About typing objects to trigger code hints” on page 48) or suffixes (see “About using suffixes to trigger code hints” on page 48) because these techniques enable code hints automatically and make your code more understandable. you must apply your settings to existing code manually.0 .About using comments to trigger code hints You can also use ActionScript comments to specify an object’s class for code hints. In the Preferences dialog box. Select any of the Auto Format options. and so on.

In your scripts. However. syntax is the way elements are put together to create meaning. Using syntax highlighting In ActionScript. About coding in the Actions panel and Script window 51 . which shows that you made a typing error. For information on keywords. see “About keywords” on page 138. “Setting publish options for the Flash SWF file format” in Using Flash. (For information on setting the Flash Player SWF file version. In the Actions panel. as in any language. do one of the following: ■ ■ ■ ■ Click the Auto Format button in the Actions panel or Script window toolbar. When automatic indentation is turned on. For example. select or deselect Automatic indentation in the Preferences dialog box. When you write scripts in Flash Basic 8 and Flash Professional 8. For example. select Tools > Auto Format. To use dynamic font mapping: ■ To turn dynamic font mapping on or off. which brings attention to typing errors. select Auto Format from the pop-up menu. ActionScript that is supported only by Flash Player 8 appears in yellow in the Actions toolbox. your scripts cannot work. you can indent a line by selecting the line and pressing Tab. To use automatic indentation: ■ To turn automatic indentation on or off. turn on dynamic font mapping because it helps to ensure that the correct fonts are used. the word var appears in blue. commands that are not supported by the version of the player you are targeting appear in yellow in the Actions toolbox. You can also set a preference to have Flash color-code parts of your scripts as you write them. Dynamic font mapping is turned off by default because it increases performance time when you are scripting. see Chapter 17. To remove the indent. suppose you set the Syntax coloring preference to make keywords appear in deep blue. if the Flash Player SWF file version is set to Flash 7. select the line and press Shift+Tab. if you mistakenly type vae. the text you type after an opening parenthesis [(] or opening curly brace ({) is automatically indented according to the Tab size setting in ActionScript preferences.To format code according to Auto Format settings. If you use incorrect ActionScript syntax. If you are working with multilingual text. In the Script window. select or deselect Use dynamic font mapping in the Preferences dialog box. While you type code. the word vae remains black. if you type var. Press Control+Shift+F (Windows) or Command+Shift+F (Macintosh).

select Word Wrap from the pop-up menu. click ActionScript in the Category list. N OT E 52 Writing and Editing ActionScript 2. For information on commenting. select Preferences from the pop-up menu (at the upper right of the Actions panel) and specify Syntax coloring settings in ActionScript preferences. and strings. you should enable line numbers and word wrap to make editing code much easier.To set preferences for syntax coloring as you type. To enable or disable line numbers. and then two other keys). ■ ■ You can change the color settings for keywords.0 . and specify Syntax coloring settings. In the Actions panel. press Control-U (Windows) or Command-U (Macintosh). Using line numbers and word wrap You can select whether to view line numbers and whether to wrap long lines of code. select Tools > Line Numbers. Using Escape shortcut keys You can add many elements to a script by using Escape shortcut keys (pressing the Escape key. To enable or disable line word wrap. select Line Numbers from the pop-up menu. identifiers. These shortcuts are different from the keyboard shortcuts that initiate certain menu commands. see “About comments” on page 131. Typically. comments. see “Terminology” on page 803 and “String data type” on page 79. In the Script window. Press Control+Shift+W (Windows) or Command+Shift+W (Macintosh). or at low screen resolutions). Line numbers make code easier to scroll and parse when you’re editing or modifying the code. For information on identifiers and strings. select Tools > Word Wrap. do one of the following: ■ Select Edit > Preferences (Windows) or Flash > Preferences (Macintosh). do one of the following: ■ ■ ■ In the Actions panel. In the Script window. Press Control+Shift+L (Windows) or Command+Shift+L (Macintosh). do one of the following: ■ ■ ■ In the Actions panel. With the mouse pointer focused in the Script pane. Word wrap helps you avoid horizontally scrolling long lines of code (especially when you work in the authoring environment.

However. Showing hidden characters As you write and format ActionScript code. the following code is placed in your script. These of course are good and necessary to the visual organization of your code. select or deselect Esc Shortcut Keys. the following code is placed in your script: do { } while (). you will enter spaces. and line breaks into your script. you can show them next to elements in the ActionScript toolbox. so you can begin typing your condition: catch () { } If you want to learn (or be reminded) about which commands have Escape shortcut keys. The insertion point is placed immediately following the word while. so you can begin typing your condition. Similarly. if you are working in the Script pane and press Escape+d+o. tabs. Escape shortcut keys appear next to elements in the ActionScript toolbox. About coding in the Actions panel and Script window 53 . To show or hide Escape shortcut keys: ■ From the Actions panel pop-up menu. and the insertion point is placed between the parentheses [()]. if you press Escape+c+h.For example. Showing hidden characters in the Script pane allows you to see and then remove double-byte spaces. the Flash compiler generates errors if it encounters double-byte spaces that are not part of a string value.

Enter the search string that you want to locate in the script. do one of the following: ■ ■ Select Hidden Characters from the pop-up menu.The following symbols are used to display each hidden character: single-byte space double-byte space tab line break . select the Find tool or press Control+F (Windows) or Command+F (Macintosh). With hidden characters shown. 2. You may also match the case of the text. You may replace the first or all occurrences of the text in your script. Press Control+Shift+8 (Windows) or Command+Shift+8 (Macintosh).0 . 54 Writing and Editing ActionScript 2. From the Actions panel or Script window toolbar. l >> To show hidden characters. To find text in a script: 1. the Script pane looks like this: Using the Find tool The Find tool allows you to find and optionally replace text string in your scripts.

Select the Script pane (so it has focus). it is highlighted. If the text or characters are present in the script. You can also check to see if a set of parentheses. do one of the following: ■ ■ ■ Click Check Syntax in the Actions panel or Script window toolbar. To find and replace text in a script: 1. Syntax errors are listed in the Output panel. Sometimes you will generate errors—even if the global class path is set correctly—because the compiler is not aware that this class is being compiled. those classes are compiled and their syntax is also checked. curly braces. 5. or brackets around a block of code is balanced. Click Replace to replace the string. the current script is checked. select Check Syntax from the pop-up menu. If you click Check Syntax in an external ActionScript 2.0 class file in the Script window. For more information on compiling classes. you can do a quick check of your ActionScript code without leaving the FLA file. Checking syntax and punctuation To determine whether the code you wrote performs as planned. In the Actions panel. When you check syntax. see “Compiling and exporting classes” on page 280. To check syntax. Other scripts that might be in the FLA file are not checked. the words or characters will be highlighted in the Script pane. you can repeat the search by selecting Find Again from the pop-up menu.0 classes. or click Replace All to replace all occurrences of the string. and then press Control+T (Windows) or Command+T (Macintosh). Enter the search string that you want to locate and replace in the script. Click Find Next. However. From the Actions panel or Script window toolbar. the global class path affects this process. NO T E About coding in the Actions panel and Script window 55 . 4. Click Find Next. enter the new string. click the Find tool or press Control+F (Windows) or Command+F (Macintosh). you need to publish or test the file. If the current script calls ActionScript 2. 2. In the Replace text box.3. If the string is present in the script. After you’ve entered a search string in the Find tool. 3.

In the Script window. For Windows. Save the ActionScript (AS) file. or for Macintosh. or parentheses [()] in your script. ■ You can export a script from the Actions panel. Importing and exporting scripts You may both import a script into the Actions panel or Script window and export your scripts to external ActionScript files. select Import Script from the pop-up menu or press Control+Shift+I (Windows) or Command+Shift+I (Macintosh). To export a script from the Actions panel: 1. For more information. 2. or parentheses. exporting is unnecessary because you can instead save the AS file. press Command+' (single quote) to highlight the text between braces. brackets.0 . brackets ([]). see “Importing and exporting scripts” on page 56 and “Import and export preferences” on page 57. To import an external AS file: ■ To import an external script into a script that you’re working on in the Script pane. Both can be useful for sharing code between different Flash applications and development teams. select Import Script from the File menu or press Control+Shift+I (Windows) or Command+Shift+I (Macintosh). The highlighting helps you check that opening punctuation has corresponding closing punctuation.To check for punctuation balance. place the insertion point where you want the first line of the external script to be located and then do either of the following: ■ In the Actions panel. do one of the following: ■ ■ Click between braces ({}). 56 Writing and Editing ActionScript 2. The Save As dialog box appears. Select the script to export and then select Export Script from the pop-up menu or press Control+Shift+X (Windows) or Command+Shift+X (Macintosh). press Control+' (single quote). Flash supports a number of different character encoding formats (including Unicode) and you may specify which format to use when importing and exporting scripts. When you use the Script window.

also called the traditional code page. If text in your scripts doesn’t look as expected when you open or import a file. If you receive a warning message when you export ActionScript files. the Test Movie command (see “Debugging your scripts” on page 711) fails if any part of the SWF file path has characters that cannot be represented by using the Multibyte Character Sets (MBCS) encoding scheme. select UTF-8 Encoding to save or export using Unicode encoding. Japanese. For Save/Export. change the import encoding preference. C A U TI O N Import and export preferences You can set ActionScript preferences to specify the type of encoding to use when importing or exporting ActionScript files. if you are importing or exporting ActionScript files in UTF-8 format. you can include text in English. won’t work on an English system. which work on a Japanese system.Unicode support for ActionScript Flash 8 supports Unicode text encoding for ActionScript. or select Default Encoding to open or import using the encoding form of the language currently used by your system. select UTF-8 Encoding to open or import using Unicode encoding. All areas of the application that use the external player are subject to this limitation. To select text encoding options for importing or exporting ActionScript files: 1. do one or both of the following: ■ For Open/Import. Default Encoding is the encoding form supported by the language your system is currently using. and French in the same file. Under Editing Options. use the Default Encoding preference. For example. Japanese paths. For example. click ActionScript in the Category list. This means that you can include text in different languages in an ActionScript file. In general. In the Preferences dialog box (Edit > Preferences (Windows) or Flash > Preferences (Macintosh)). If you are importing or exporting files in the traditional code page in use on your system. use the UTF-8 preference. You can select UTF-8 encoding or Default Encoding. or select Default Encoding to save or export using the encoding form of the language currently used by your system. UTF-8 is 8-bit Unicode format. you can change the export encoding preference or turn this warning off in ActionScript preferences. When you use a non-English application on an English system. ■ About coding in the Actions panel and Script window 57 . 2.

which you’ll read about in the following sections. and click Warnings from the Category list. Select or deselect Warn on encoding conflicts when exporting ActionScript files.To turn the export encoding warning off or on: 1. see these sections: ■ ■ ■ “About Script Assist” on page 58 “Pinning scripts in the Actions panel” on page 59 “Inserting target paths” on page 60 About Script Assist Script Assist prompts you to enter the elements of a script. For features that are available in both the Script window and the Actions panel.0 . 58 Writing and Editing ActionScript 2. Used in conjunction with the Actions panel. helping you to more easily add simple interactivity to your Flash SWF file or application. For features only available in the Actions panel. instead of writing a new script. Even though the Actions panel has all the features of the Script window. select Edit > Preferences (Windows) or Flash > Preferences (Macintosh). you can select a language element from the Actions toolbox (or the Add (+) command on the toolbar). For example. see the sections in “About coding in the Actions panel and Script window” on page 38. and then use Script Assist to help you complete the script. drag it into the Script pane. 2. These features are not available in the Script window. the Script window is used for a different functionality. Script Assist mode is ideal for users who either aren’t comfortable writing their own scripts or who just appreciate the convenience the tool provides. In the Flash system menu. Script Assist prompts you to select options and enter parameters. The Actions panel has to support some FLA file-related functionality. About Actions panel features The following features are only available in the Actions panel.

To pin a script means that you can keep the location of the code open in the Actions panel. you can pin multiple scripts in the Actions panel to make it easier to move among them. TIP About Actions panel features 59 . (period). the Script pane is probably showing a pinned script. Script Assist displays all of the prompts needed to use this ActionScript function—in this case. You can move among the pinned scripts by clicking on the tabs or by using keyboard shortcuts. the gotoAndPlay function was added to the Script pane.) That script is also pinned (it is shown as the right-most tab). Two other scripts are pinned: one on Frame 1 and the other on Frame 15 of the layer named Intro. and the frame number. the scene name. Moving among pinned scripts does not change your current position on the timeline. the script associated with the current location on the timeline is on Frame 1 of the layer named Cleanup. and you can click each tab to move between the scripts. Pinning scripts in the Actions panel If you don’t centralize your code within a FLA file in one location (discussed in “Organizing ActionScript code” on page 33) or if you’re using behaviors (see “About behaviors” on page 61). As you can see in the following figure. If the content in the Script pane doesn’t change to reflect the location that you select on the timeline.In the example below. such as Control+Shift+. In the following figure. multiple scripts are open in the Actions panel. and easily click between each open script. the type. (The tab at the far left always follows your location along the timeline. Click the left tab at the lower left of the Script pane to show the ActionScript associated with your location along the timeline.

Select Pin Script from the pop-up menu (at the upper right of the Actions panel). (comma) Control+Shift+. Do one of the following: ■ ■ ■ ■ Click the pushpin icon to the right of the tab. 60 Writing and Editing ActionScript 2. press Control+-(minus sign) in Windows or Command+. With the mouse pointer focused in the Script pane. buttons.(minus sign) Macintosh shortcut key Command+= Command+Command+Shift+. press Control+= (equal sign) in Windows or Command+= on the Macintosh. Right-click (Windows) or Control-click (Macintosh) on the tab. Position your mouse pointer on the Timeline so the script appears in a tab at the lower left of the Script pane in the Actions panel. You can set either an absolute or relative target path. 2. Select Close Script or Close All Scripts from the pop-up menu (at the upper right of the Actions panel). and other symbol instances. Command+Shift+. ■ ■ ■ To use keyboard shortcuts with pinned scripts: ■ You can use the following keyboard shortcuts to work with pinned scripts: Action Pin script Unpin script Windows shortcut key Control+= (equal sign) Control+. Command+Shift+- Move focus to tab on the right Control+Shift+.on Macintosh.To pin a script: 1. (period) Move focus to tab on the left Unpin all scripts Control+Shift+. you set a target path—the address of the instance you want to target. click the pushpin icon on the right of the tab. and select Pin Script. Right-click (Windows) or Control-click (Macintosh) on a tab. With the mouse pointer focused in the Script pane.0 . 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. To unpin one or more scripts.(minus) Inserting target paths Many of the actions that you create in your script will affect movie clips. To apply actions to instances on a timeline. and select Close Script or Close All Scripts.

a movie clip or a button. 2. Select the target from the list of available targets. The path is appended to the action. Typically. or conversely as a way to learn how ActionScript works in certain situations. Click OK. Select either the Absolute or Relative path option. loading of external SWF files and JPEGs. such as frame navigation. prompts you to enter the target path for the selected action in your script. Select and position the pointer in an action in your script. Behaviors provide you with prewritten ActionScript functionality. as shown in the following example: About behaviors 61 . Behaviors are available to you only when you are working in a Flash document. You can use behaviors as a convenience when building your Flash application—as a way to avoid having to write ActionScript. About behaviors Behaviors are predefined ActionScript functions that you can attach to objects in your Flash document without having to create the ActionScript code yourself. Do one of the following: ■ ■ 3. and then select the behavior you want. which is available in the Actions panel. you select a triggering object in your document. Manually enter the path to the target instance. The Insert Target Path dialog box appears. 5.The Target Path tool. select Add on the Behaviors panel to display the available behaviors. controlling the stacking order of movie clips. 4. Click Target Path on the Actions panel toolbar. To insert a target path: 1. not in an external script file. and movie clip dragging.

You edit the Flash document’s publish settings to change the version of ActionScript that will be used when the document is published.0 . 62 Writing and Editing ActionScript 2. Because the Actions panel and the Script window are essentially two different views that use the same ActionScript editor. Modifying ActionScript publish settings When you publish a Flash document. For more information about setting a documentlevel or the global level classpath. About ActionScript publish settings You can edit ActionScript in two ways. you can do so by editing the publish settings. You can also set the classpath for the current document by passing the global ActionScript classpath. ActionScript settings and preferences within Flash apply to both views. If you need to change the version of ActionScript or to specify a document-level classpath. For more information about modifying the ActionScript publish settings.0 by default and the classpath is inherited from the global classpath setting. the ActionScript version is set to 2. using the Script window. Or you can edit ActionScript that is in a separate script file. You can edit ActionScript that is embedded into a Flash document by using the Actions panel. see “Modifying the classpath” on page 63.The behavior is added to the object and is displayed in the Actions panel. external to the Flash document. see “Modifying ActionScript publish settings” on page 62.

see “Modifying the classpath” on page 63. Select Edit > Preferences (Windows) or Flash > Preferences (Macintosh) to open the Preferences dialog box. Click ActionScript in the Category list. ActionScript 2.. you use the Publish Settings dialog box for the FLA file. Select the ActionScript version from the pop-up menu. You can use the Preferences dialog box to modify the global classpath. you can also set a document-level classpath.0. To resolve this problem.0 Settings. with the following exception: the slash (/) syntax used to indicate movie clip paths (for example.0 is selected by default. 2. In both cases. 2. or select the ActionScript 1. C:/my_classes) and relative directory paths (for example.0 compiler compiles all ActionScript 1. parentClip/ testMC:varName= "hello world") generates compilation errors if you select ActionScript 2.0 as the ActionScript version. Modifying the classpath When you use ActionScript 2./my_classes or ".0 instead of 2. change this setting before you publish your Flash document. About ActionScript publish settings 63 .) notation in place of slashes. The ActionScript 2. . To modify the document-level classpath setting. For more information. either rewrite your code using dot (. To modify the global classpath: 1. If you write your scripts in ActionScript 1.").0 code. You use the Settings button (next to the ActionScript version pop-up menu) to modify the document-level classpath. and then click ActionScript 2. Select File > Publish Settings and then select the Flash tab.0. you can add absolute directory paths (for example.To change the ActionScript version: 1. Changing the classpath in the publish settings only applies to the current Flash file. This is useful when you create your own classes and you want to override the global ActionScript classpath that is set in the ActionScript preferences.0 compiler.

NO TE To modify the document-level classpath: 1. and click OK. 4. Doubleclick the new line. click Add New Path (+) to add a new line to the Classpath list. and click OK. click Browse to Path. browse to the directory you want to add. click Add New Path (+) to add a new line to the Classpath list. Do not delete the absolute global classpath (see Global and document-level classpaths). Alternatively. browse to the directory you want to add. browse to the directory you want to add. select the path in the Classpath list. type a relative or absolute path. type the desired path. ■ To edit an existing classpath directory. For more information on setting and modifying classpaths. Do one of the following: ■ To add a directory to the classpath. double-click the path in the Classpath list. and click OK. Alternatively. ■ To edit an existing classpath directory. and click OK. click Browse to Path. If you accidentally delete this classpath. ■ To delete a directory from the classpath.0 . select the path in the Classpath list. type the desired path. Alternatively. Click Settings next to the ActionScript Version pop-up menu. reinstate it by adding $(LocalData)/Classes as a new classpath. Do one of the following: ■ To add a directory to the classpath. Doubleclick the new line. 2. double-click the path in the Classpath list. and click OK. select the path in the Classpath list and click Remove from Path. 64 Writing and Editing ActionScript 2. click Browse to Path. browse to the directory you want to add. Flash uses this classpath to access built-in classes. Select File > Publish Settings to open the Publish Settings dialog box. and click OK. and click Remove from Path. select the path in the Classpath list. type a relative or absolute path. and click OK. click Browse to Path. ■ To delete a directory from the classpath.3. see “About setting and modifying the classpath” on page 240. 3. Click the Flash tab. Alternatively. and click OK.

For more information on the organization of this directory. see “Using ASO files” on page 282. Macintosh: Hard Disk/Users/user/Library/Application Support/Macromedia/Flash 8/ language/Configuration/Classes. ■ ■ Include classes folder ■ Contain all of the global ActionScript include files and is located in: Windows: Hard Disk\Documents and Settings\user\Local Settings\Application Data\Macromedia\Flash 8\language\Configuration\Include. several ActionScript-related configuration folders and files are placed on your system. You might use these files to make certain configurations to the authoring environment.xml configuration file syntax highlighting. The Classes folder is organized into folders that contain directories that contain the classes for Flash Player 7 (FP7) and Flash Player 8 (FP8). Macintosh: Hard Disk/Users/user/Library/Application Support/Macromedia/Flash 8/ language/Configuration/Include. see the readme file in the Classes folder.Configuration files that install with Flash 8 When you install Flash Basic 8 or Flash Professional 8. modify carefully and save a back up of files that you modify.xml configuration file hinting and is located in: ■ Windows: Hard Disk\Documents and Settings\user\Local Settings\Application Data\Macromedia\Flash 8\language\Configuration\ActionsPanel\ActionScript_1_2. For more information on ASO files. ■ About ActionScript publish settings 65 . It also contains a directory for the mx package (mx). Includes the configuration file for ActionScript code ■ ActionsPanel. located in: ■ Windows: Hard Disk\Documents and Settings\user\Local Settings\Application Data\Macromedia\Flash 8\language\Configuration\ActionsPanel\. Macintosh: Hard Disk/Users/user/Library/Application Support/Macromedia/Flash 8/ language/Configuration/ActionsPanel. ActionScript classes folder Contain all of the ActionScript classes (AS files) that are included in Flash Professional 8 or Flash Basic 8. Typical paths to this folder are as follows: Windows: Hard Disk\Documents and Settings\user\Local Settings\Application Data\Macromedia\Flash 8\language\Configuration\Classes. As always. Macintosh: Hard Disk/Users/user/Library/Application Support/Macromedia/Flash 8/ language/Configuration/ActionsPanel/ActionScript_1_2. The configuration file for ActionScript code color ■ AsColorSyntax. that’s used in both players and ASO files (aso).

66 Writing and Editing ActionScript 2.0 .

org/js/language/es4/index. classes and interfaces cannot be defined in the Actions panel. If it does not.html).0 are supported by Flash Player 6 and later. it lets you write scripts that more closely adhere to standards used in other object-oriented languages.0 to use ActionScript 2.0 in its publish settings.0 to define classes or interfaces must be stored as external script files. 67 .0 is loosely based on this specification. “Classes.0 syntax. you can import packages (collections of class files in a directory) by using wildcards.mozilla. Applications developed with ActionScript 2. your file will compile incorrectly.0 are based on the ECMAScript 4 Draft Proposal currently in development by ECMA TC39-TG1 (see www. although Flash will not necessarily generate compiler errors.CHAPTER 3 About ActionScript The object-oriented programming (OOP) features in ActionScript 2.0 supports all the standard elements of the ActionScript language. If you plan to modify an existing FLA file with ActionScript 1. The default publish setting for new files created in Flash 8 is ActionScript 2. ActionScript 2.” on page 773). “Error Messages. CAUTION ■ ■ For more information on using ActionScript 2. ActionScript 2.” on page 225. that is. with a single class defined in each script.0. such as Java.0 also lets you declare the object type of a variable when you create it (see “About assigning data types and strict data typing” on page 81) and provides significantly improved compiler errors (see Appendix A. see Chapter 7. 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. ensure that the FLA file specifies ActionScript 2. and because it is still changing. Key facts about ActionScript 2. 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).0 include the following points: ■ 3 Scripts that use ActionScript 2. Because the ECMA-4 proposal is not yet a standard.0 to write object-oriented programs in Flash. ActionScript 2.

0 also lets you explicitly specify data types for variables.0.0.0 and begin rewriting it in ActionScript 2. or class). What is ActionScript The main features of ActionScript 2.0.0 implements several object-oriented concepts and keywords such as class. change the publish settings of the FLA file to ActionScript 2.Although Macromedia recommends that you use ActionScript 2.0. and function return types. make sure that the publish settings for the FLA file specify ActionScript 2. If you don’t. ActionScript 2. function parameters. var userName:String = "". especially if you are doing more traditional Flash work such as simple animation that doesn’t require user interaction. if you open an older FLA file that uses ActionScript 1. The OOP model provided by ActionScript 2. Strict data typing ActionScript 2. and packages that will be familiar to you if you’ve programmed with Java. you can continue to use ActionScript 1. your FLA file will not compile correctly. Compiler warnings and errors 68 About ActionScript . For example.0 is a familiar model for creating object-oriented programs.0 syntax. and errors won’t be generated. Familiar object-oriented programming (OOP) model The previous two features (OOP model and strict data typing) enable the authoring tool and compiler to provide compiler warnings and error messages that help you find bugs in your applications faster than was previously possible in Flash. However. interface.0. the following code declares a variable named userName of type String (a built-in ActionScript data type.0 include the following: The primary feature of ActionScript 2. This is the default for files created in Flash MX 2004 and Flash 8. you can create custom classes and extend Flash’s built-in classes. With ActionScript 2. When you use ActionScript 2.0 is a “syntactic formalization” of the prototype chaining method used in previous versions of Macromedia Flash to create objects and establish inheritance.0.

0 and classes. ActionScript 2. such as a mobile device application.0 also offers a syntax that follows standards in other programming languages. such as remaining consistent with case sensitivity.0 lets you use an object-oriented approach to developing applications by using an additional set of language elements.0 69 . apply to both versions. When you build a small project.0 When you start a new document or application in Flash.0. and keeping a consistent naming convention. About choosing between ActionScript 1. It is often more efficient to put ActionScript inside the document. you must use ActionScript 1. regardless of the version of ActionScript. In some cases. You might decide to put your code inside the FLA file by using ActionScript 2.0 and ActionScript 2. For example. but not all documents use classes. you will feel familiar with ActionScript if you have encountered another language that’s based on the same structure and syntax standards. This does not mean that you should necessarily use ActionScript 1. to make it easier to update and modify your application. try to put all your code on the Timeline on as few frames as possible. rather than placing it within a class that you import. enhancing readability. which is compatible with Flash Player for a number of devices. This makes the language easier and more valuable to learn. you can apply this knowledge to other languages you learn in the future. many short examples in the documentation do not use classes. ActionScript 2. you cannot choose which version of ActionScript to use. you should use ActionScript 2. you should follow good practices. such as when you are building applications or complex FLA files. Using classes to store functionality is not the easiest or best solution for small applications or simple FLA files.About choosing between ActionScript 1. If you plan to update your application in future versions of Flash. In this case.0.0 and ActionScript 2. it is often more work and effort to use classes or external code files to organize ActionScript instead of adding ActionScript within the FLA file. Sometimes it is easier to keep all the ActionScript code within the FLA file. and avoid placing code on or in instances (such as buttons or movie clips) in a FLA file. Remember. or make it larger and more complex. Or. If you are building a SWF file that targets an old version of Flash Player. Many of these practices. You might use classes in some projects. which can be advantageous to your application development.0 with its strict data typing and its new methods and properties. you must decide how to organize its associated files. using code completion. For example. avoiding keywords for instance names.

Therefore.0. No case sensitivity is involved with the code.0.0 with publish settings set to Flash Player 6 and ActionScript 1. 70 About ActionScript . if you compile your SWF file with Publish Settings set to Flash Player 7 or 8 and ActionScript 1. Data type annotations (strict data types) are enforced at compile time for Flash Player 7 and 8 when you have publish settings set to ActionScript 2.0 compiles to ActionScript 1.Understanding ActionScript and Flash Player If you compile a SWF file that contains ActionScript 2. your code functions as long as it does not use ActionScript 2.0. 7. ActionScript 2. so you can target Flash Player 6. Flash enforces case sensitivity.0.0 classes. only Flash Player.0 bytecode when you publish your applications. or 8 while working with ActionScript 2.

. Following this. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72 About variables . . . . .110 4 About data Data refers to the numbers. . . You also use data when you create advanced graphics and script-generated animation. . . . . . . . . . For more information about data and data types. . . . . . . . . built-in ActionScript classes. . . Chapter 5. . . . . . . In the next chapter. . . . . . . . . . . . . . . . . . . . . . “Functions and Methods” demonstrates how to use functions and methods in the ActionScript language. . . . . . . . . . web services. . . . . . . . . . . . . . . . . Using data is usually essential when you create applications or websites. . . . strings. . . . . . . . . . . . .71 About data types. . . . . . . . or you can load data from external files or sites using XML. . . . . . . 86 Organizing data in objects . . . . . . . . . . . 108 About casting . . . . . . . . . . . . . . . . . . . . . . . .CHAPTER 4 Data and Data Types This chapter is the first of several chapters that outline and demonstrate some fundamental concepts of ActionScript. . . . . . . . . or displaying images in movie clip instances. . . . . . . . . . and what kinds of data you can work with. . . . . . . . . . 71 . . and then represent that information in several ways in a SWF file. . and so on. . . . . . . . . . .” you’ll discover how to use ActionScript syntax and form statements. . . . . . . . . . . . . . . . . . In this chapter. . . . “Syntax and Language Fundamentals. . . . . . . . . . . . . . . . . and you might have to manipulate values that you use to drive your effects. This can include displaying the information in text fields or components. . . . . . . . . you’ll also learn about how to work with data in a FLA file. . . . . . . . . . . . . see the following sections: About data . . Chapter 6. . . . . . . . . . . . You can define data in variables within Flash. You can store data in a database. . . . and other information that you can manipulate within Flash. . . . You’ll practice some basic coding techniques to learn how to create complex applications. . .

object instances.0 Language Reference. About data types A data type describes a piece of data and the kinds of operations that you can perform on it. see “About top-level and built-in classes” on page 286. see “About data types” on page 72. You can do this with the instanceof and typeof operators (see “About determining data type” on page 85). In this chapter. Object(). You use many different data types when you write ActionScript. See the table in “About primitive and complex data types” on page 73 for more information. String(). ActionScript also has core classes. see “About primitive and complex data types” on page 73. Any class that you define using the class declaration is also considered a data type. and so on. you’ll also learn about the data types in Flash and how to use them. Number(). such as Array and Date. In ActionScript 2. The data types you assign can be any of the core types or can represent a custom class that you created. You can also create custom classes for your applications. you might need to determine the data type of an expression or variable to understand why it is behaving a certain way. You store data in a variable. see Chapter 7.Some of the most common kinds of data include strings (a sequence of characters. A variable that is assigned a data type can only hold a value within that data type’s set of values. Boolean(). “Classes. When you debug scripts.” on page 225. objects (such as movie clips). and function definitions to assign the type of data you’re working with. For more info on complex and reference data types. ActionScript 2. For more information. you can assign data types to variables when you declare them. 72 Data and Data Types . For more information on core and other builtin classes. In addition. ActionScript has numerous basic data types that you will probably use frequently in your applications.0. For information on variables. such as names and passages of text). that are considered complex or reference data types. For information on types of data. You can convert one data type to another at runtime using one of the following conversion functions: Array(). see “About variables” on page 86. Boolean values (true and false). For more information on creating custom classes.0 defines several commonly used data types. see “About variables” on page 86. see “About assigning data types and strict data typing” on page 81. Data types describe the kind of value that a variable or ActionScript element can contain. numbers. all data types and classes are fully defined in ActionScript 2. For information on variables. You use data types when creating variables.

Error. ■ About primitive and complex data types You can divide all the different data type values into two main categories: primitive or complex. For more information on these complex data types. Often. Data types that define sets of complex values include Array. No other values are valid for variables of this type. and XML. which means that operations on the primitive data types are generally faster and more efficient than operations carried out on complex data types.You can find a sample source file. see their entries in the ActionScript 2. Function. Complex. Complex values belong to the Object data type or a data type that is based on the Object data type.fla. Number. String. The following data types all define a set of one or more primitive values: Boolean. A primitive value (or primitive data type) is a value that ActionScript stores at the lowest level of abstraction. On the Macintosh. and undefined. browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\DataTypes. null. For more information. A complex value (or complex data type) is a value that is not a primitive value and that references the primitive values. MovieClip About data types 73 . Variables that contain primitive data types behave differently in certain situations than those containing complex types. The MovieClip data type lets you control movie clip symbols using the methods of the MovieClip class. these are called reference data types. ActionScript has the following basic data types that you can use in your applications: Data type Boolean Description Primitive. in the Samples folder on your hard disk.0 Language Reference. see “MovieClip data type” on page 76. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/DataTypes. For more information. ■ In Windows. The default value of Boolean variable that has been declared but not initialized is false. Date. datatypes. For more information. see “Using variables in a project” on page 106. see “Boolean data type” on page 75. which shows you how to use data types in an application. The Boolean data type consists of two values: true and false.

you should include a decimal point in the number. datatypes. and it lets you arrange objects inside each other (nested objects). The Void data type contains only one value: void.fla. which shows you how to use data types in an application. On the Macintosh. To store a floating point number. ■ 74 Data and Data Types . unsigned integers. The null data type is the default data type for all classes that define complex data types. For more information. You can only assign a value of undefined to variables that belong to the Object class. You use this data type to designate functions that don’t return a value. Complex. Complex. The undefined data type contains one value: undefined. This value means no value—that is. see “undefined data type” on page 80. Primitive. Primitive. see ActionScript 2. Void is a complex data type that references the primitive Void data type. This data type can represent integers. Primitive. This is the default value for instances of the Object class. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/DataTypes. Without the decimal point. and punctuation marks. see “null data type” on page 77. ■ In Windows.Data type null Description Primitive. For more information. You can assign the null value in a variety of situations to indicate that a property or variable does not have a value assigned to it. a lack of data. Number Object String undefined Void You can find a sample source file. Strings are stored as Unicode characters. The null data type contains the value null. numbers. An operation on a String value returns a new instance of the string. An exception to this rule is the Object class. For more information.0 Language Reference and “Number data type” on page 78. The Object data type is defined by the Object class. browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\DataTypes. see “Object data type” on page 78. For more information.MAX_VALUE (very high) to Number. the number is stored as an integer. and floating point numbers. using the UTF-16 format. The Number data type can store values from Number.MIN_VALUE (very low). see “Void data type” on page 81. For more information. The Object class serves as the base class for all class definitions in ActionScript. The String data type represents a sequence of 16-bit characters that might include letters. in the Samples folder on your hard disk. see “String data type” on page 79. which defaults to undefined. For more information.

trace a message } else { trace("unable to load text file"). Boolean values are most often used with logical operators in ActionScript statements that make comparisons to control the flow of a script. and displays a message in the Output panel if the text file does not load correctly.controls. trace monthNames if (success) { trace(my_lv. var btnListener:Object = new Object().Button. welcome_lbl. Two Boolean variables are created.text = titleMessage. About data types 75 . a Label. which is used with the Button component. // Create a listener object. See the comments in the code example for more details.TextInput.txt"). //if success is false. var userNameEntered:Boolean = (userName_ti. checks for a user name and password.onLoad = function(success:Boolean) { //if success is true.Boolean data type A Boolean value is one that is either true or false. //success is a Boolean value my_lv. The following example checks that users enter values into two TextInput component instances. a welcome message is assigned to the titleMessage String variable.text. if (userNameEntered && isPasswordCorrect) { var titleMessage:String = "Welcome " + userName_ti. var submit_button:mx. //Hide the label welcome_lbl. btnListener.length > 0).controls. userNameEntered and isPasswordCorrect. ActionScript also converts the values true and false to 1 and 0 when appropriate. The following example loads a text file into a SWF file.Label.monthNames). and a Button component on the Stage.text + "!". or the parameters if it does load successfully. } }. var password_ti:mx. my_lv.load("http://www. // When the Button is clicked. var my_lv:LoadVars = new LoadVars().visible = false. var isPasswordCorrect:Boolean = (password_ti. and if both variables evaluate to true.controls.TextInput.com/flash/params.text == "vertigo"). var welcome_lbl:mx. // Strict data type the three component instances var userName_ti:mx.click = function(evt:Object) { // Checks that the user enters at least one character in the TextInput // instances and returns a Boolean true/false.helpexamples.controls. // Add two TextInput components.

//display the label welcome_lbl. and the returned value must be a numeric value. Using MovieClip._width.createEmptyMovieClip("image_mc". function getMCWidth(target_mc:MovieClip):Number { return target_mc. parent_mc. Then you simply call the methods of the MovieClip class using the dot (. For example. To dynamically create a movie clip. } trace(getMCWidth(my_mc)). You do not use a constructor to call the methods of the MovieClip class. For more information. Creating movie clips dynamically 76 Data and Data Types . MovieClip data type Movie clips are symbols that can play animation in a Flash application. // Loads an image into image_mc.com/flash/images/image1. The second example returns the width of a movie clip called my_mc on the Stage. 9). They are the only data type that refers to a graphic element. see “Using functions in Flash” on page 214 and “About logical operators” on page 194.jpg").com/support/" + product). The targeted instance must be a movie clip. } }.helpexamples. You can create a movie clip instance on the Stage or create an instance dynamically.createEmptyMovieClip().macromedia. you might create an image gallery with a large number of thumbnail images that you want to organize on the Stage.createEmptyMovieClip() lets you create an application entirely using ActionScript.visible = true. The MovieClip data type lets you control movie clip symbols using the methods of the MovieClip class.addEventListener("click". Working with movie clips on the Stage The following example calls the startDrag() and getURL() methods for different movie clip instances that are on the Stage: my_mc. Using ActionScript to create movie clips dynamically is useful when you want to avoid manually creating movie clips on the Stage or attaching them from the library.loadMovie("http://www.getURL("http://www. as shown in the following example: // Creates a movie clip to hold the container. submit_button. btnListener).startDrag(true). use MovieClip. image_mc. this.) operator.

The following example demonstrates how you can use null to test if form fields currently have form focus: if (Selection. to indicate that no value was available to be returned by the function As a parameter to a function.lineTo(100.lineTo(200.moveTo(100. 200). null data type The null data type has only one value. }. You can assign the null value in a variety of situations to indicate that a property or variable does not yet have a value assigned to it. see Chapter 11. This value means no value—that is. 0x000000. square_mc. null.lineStyle(1. } About data types 77 . square_mc. 100). to indicate that a parameter is being omitted ■ Several methods and functions return null if no value has been set. this. you can assign the null value in the following situations: ■ ■ ■ To indicate that a variable exists but has not yet received a value To indicate that a variable exists but no longer contains a value As the return value of a function. square_mc.startDrag(). 100). 200). 100). square_mc.stopDrag().beginFill(0xFF0000. square_mc. square_mc. a lack of data.endFill(). }. 100).lineTo(200.The second example creates a movie clip called square_mc that uses the Drawing API to draw a rectangle.onRelease = function() { this.lineTo(100. For more information. 100). square_mc.” on page 351 and the MovieClip entry in the ActionScript 2.createEmptyMovieClip("square_mc". square_mc. “Working with Movie Clips. square_mc.onPress = function() { this.getFocus() == null) { trace("no selection"). For example. Event handlers and the startDrag() and stopDrag() methods of the MovieClip class are added to make the rectangle draggable.0 Language Reference. 1). square_mc.

round((intro_mc. This lets you arrange objects inside each other. _alpha (transparency) is a property. The maximum is approximately 1. Each property has a name and a value. hoursWorked is a property of weeklyStats.getBytesTotal()) * 100).0 Language Reference. Therefore.sqrt(100). Object data type An object is a collection of properties. For more information. For example. multiplication (*). the transparency of an object (such as a movie clip) is an attribute that describes its appearance.getBytesLoaded() / intro_mc.Number data type The Number data type is a double-precision floating-point number. see “Using numeric operators” on page 188.79E+308. modulo (%).floor(Math. You can also use methods of the built-in Math and Number classes to manipulate numbers. The following example uses the sqrt() (square root) method of the Math class to return the square root of the number 100: Math. subtraction (-). The following example traces a random integer between 10 and 17 (inclusive): var bottles:Number = 0.weeklyStats.hoursWorked 78 Data and Data Types . division (/). trace("There are " + bottles + " bottles"). A property is an attribute that describes the object. For example. bottles = 10 + Math.random() * 7). For more information on the methods and properties of these classes. increment (++). The following example finds the percent of the intro_mc movie clip that is loaded and represents it as an integer: var percentLoaded:Number = Math. You can manipulate numbers using the arithmetic operators addition (+). or nest them. which is a property of employee: employee. The minimum value of a number object is approximately 5e-324. in the following code. The value of a property can be any Flash data type—even the Object data type. see the Math and Number entries in ActionScript 2. and decrement (--). To specify objects and their properties.) operator. you use the dot (.

simplify your scripting. Creating custom objects lets you organize this information into groups. "L7" is a string assigned to the variable favoriteBand_str: var favoriteBand_str:String = "L7". see “Example: Writing custom classes” on page 263. You can use the addition (+) operator to concatenate. name. " + firstName. The following expression includes a space after the comma: var greeting_str:String = "Welcome. ActionScript treats spaces at the beginning or end of a string as a literal part of the string.name = "Irving". For example. the number of frames loaded. or the key that the user pressed last. user. in the following statement. the speed of a ball. About data types 79 . you need many pieces of information: for example. This example uses the play() and nextFrame() methods: mcInstanceName. To add interactivity to an application with ActionScript.play(). you might need a user’s name. The following ActionScript code shows an example of using custom objects to organize information. String data type A string is a sequence of characters such as letters. user.age = 32. You enter strings in an ActionScript statement by enclosing them in single (') or double (") quotation marks. var user:Object = new Object(). and phone number. and phone. user. age. You can also create custom objects to organize information in your Flash application. which are String and Numeric data types.nextFrame(). or join. numbers. mc2InstanceName. and punctuation marks. age. For more information. It creates a new object called user and creates three properties.The ActionScript MovieClip object has methods that let you control movie clip symbol instances on the Stage. two strings.phone = "555-1234". the names of items in a shopping cart. and reuse your scripts. A common way that you use the string type is to assign a string to a variable.

To include a quotation mark in a string.\uFFFF Character 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 Strings in ActionScript are immutable. as shown in the following example: if (init == undefined) { trace("initializing app"). and is automatically assigned to a variable to which a value hasn’t been assigned. You use the undefined data type to check if a variable is set or defined.0 Language Reference. unlike null. This is called escaping a character. There are other characters that cannot be represented in ActionScript except by special escape sequences. init = true. For information on the methods and properties of the String class. undefined. The value undefined is automatically assigned. The following table lists all the ActionScript escape characters: Escape sequence \b \f \n \r \t \" \' \\ \000 . either by your code or user interaction. undefined data type The undefined data type has one value.\377 \x00 . precede it with a backslash character (\). This data type lets you write code that executes only when the application is running. The String class is a built-in ActionScript class. just as they are in Java. Any operation that modifies a string returns a new string.\xFF \u0000 . } 80 Data and Data Types . see the String entry in the ActionScript 2. you don’t assign undefined to a variable or property.

If you assign a value to a variable. which is called strict data typing. During authoring. NO T E Because data type mismatches trigger compiler errors. Declaring data types (strict data typing) can help prevent or diagnose errors in your code at compile time. You can explicitly declare the object type of a variable when you create the variable. Strict data typing is sometimes called strong typing a variable. for example. the code does not execute a second time because the init variable is no longer undefined. null. to the compiler. (See “Assigning a data type” on page 82. Void data type The Void data type has one value. Number. String. the variable x can have a value of any type. Strict data typing offers several benefits at compile time. strict data typing activates code hinting in the ActionScript editor (but you should still use instance name suffixes for visual elements). ActionScript always converts primitive data types (such as Boolean. About data types 81 . as shown in the following example. the statement x = "hello" changes the type of x to String. use the following format: var variableName:datatype. or undefined) automatically when an expression requires the conversion and the variables aren’t strictly typed. If you do not explicitly define an item as holding either a number. To declare a variable using strict data typing. or another data type. the compiler cannot determine the type. a string. strict data typing helps you find bugs in your code at compile time and prevents you from assigning the wrong type of data to an existing variable. void.If your application has multiple frames. Because x was not declared using strict data typing. at runtime Flash Player will try to determine the data type of an item when it is assigned. and is used in a function definition to indicate that the function does not return a value.) A later assignment might change the type of x. as shown in the following example: //Creates a function with a return type Void function displayFromURL(url:String):Void {} About assigning data types and strict data typing You use variables in Flash to hold values in your code. Flash Player evaluates at runtime the element on the right side of the operator and determines that it is of the Number data type: var x = 3.

For more information on creating variables. browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\DataTypes.Using strict data typing helps ensure that you don’t inadvertently assign an incorrect type of value to a variable. Array. String. ranging from the native data types such as Number. On the Macintosh. see “Assigning a data type” on page 82. in the Samples folder on your hard disk. ■ Assigning a data type You need to assign data types whenever you define a variable. FileReference. There are many possibilities for data types. ■ In Windows. 82 Data and Data Types . The most common types of data types you might need to specify are the built-in data types such as Number. which shows you how to use data types in an application. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/DataTypes.. Flash checks for typing mismatch errors at compile time. Boolean. Strict data typing means the ActionScript editor automatically shows code hints for objects. or built-in classes that are included in Flash Player 8. You can find a sample source file. set function return type. or define a variable to use within a for or for. see “About naming variables” on page 91. which are shown in the following code examples. datatypes.fla. For information on naming variables. To assign a data type. whether you declare a variable using the var keyword. using strict typing also helps to ensure that you do not attempt to access properties or methods that are not part of an object’s type. and the types you can assign. and displays an error message if you use the wrong type of value. which means you follow the variable name with a colon and then the data type: var my_mc:MovieClip. For more information on assigning data types. Boolean. String. or even custom classes that you or other developers have written. create a function argument.in loop. see “About variables” on page 86. or Object. such as BitmapData. you use post-colon syntax. Therefore.

you can assign a data type of Function to the new variable. age:Number) { } // Strict typing of parameter and return value function square(myNum:Number):Number { var squared:Number = myNum * myNum. /* Type mismatch in assignment statement: found String where Boolean is required. and so on) as well as classes and interfaces that you create. return squared.as class file class Student { public var status:Boolean. see the following example: function sayHello(name_str:String):Void { trace("Hello.status = "enrolled". if you have a file named Student. If you write a function that doesn’t have a return type. a type mismatch error is generated because the SWF file expects a Boolean value. as shown in the following example: // Strict typing of variable or object var myNum:Number = 7. you can specify a return type of Void for that function. " + name_str). // Strict typing of parameters function welcome(firstName:String. suppose you type the following code: // in the Student.as in which you define the Student class. // Hello. specify its type using the var keyword and postcolon syntax. } sayHello("world"). Date. */ When Flash compiles this script. To specify that objects are of type Function or Void. greeting("Augustus"). // property of Student objects } // in the FLA file var studentMaryLago:Student = new Student(). Or if you create a shortcut to a function. For this example. var birthday:Date = new Date(). } You can declare the data type of objects based on built-in classes (Button. // Hello. you can specify that objects you create are of type Student: var myStudent:Student = new Student().To assign a specific data type to an item. In the following example. world var greeting:Function = sayHello. Augustus About data types 83 . studentMaryLago.

84 Data and Data Types . For information on type checking. var myNum:String = "abc". but type mismatch error in ActionScript 2.Another advantage of strict data typing is that Flash automatically shows code hints for builtin objects when they are strictly typed. Flash checks that the type you specify for a variable matches the value(s) that you assign to it. and make a selection from the ActionScript version pop-up menu. Therefore. If you use strict data typing. ActionScript can also type checking at runtime. make sure you set your publish settings to ActionScript 2. About type checking Type checking refers to verifying that the type of a variable and an expression are compatible. see “About assigning data types and strict data typing” on page 81. myNum = 12. You can specify the publish settings and define which version of ActionScript you want to publish your files as by modifying the publish settings from the main menu (File > Publish Settings) or by clicking the Settings button in the Property inspector (make sure no instances are selected).0 can optionally use data typing. Files published using ActionScript 2.0.0 doesn’t support slash syntax. Flash interprets a statement such as var myNum:String = "abc" as slash syntax rather than as strict typing.0 */ The reason for this is that when you publish a file for ActionScript 1. select the Flash tab in the Publish Settings dialog box. /* No error in ActionScript 1. see “About type checking” on page 84. causing the compiler to let illegal method calls and undefined property references pass through unreported.0 do not respect strict data typing assignments at compile time. Files published using ActionScript 1.0. (ActionScript 2. Type checking can occur at either compile time or runtime. if you implement strict data typing in your code. type checking occurs at compile time.) This behavior can result in an object that is assigned to a variable of the wrong type. see “About assigning data types and strict data typing” on page 81 and “Assigning a data type” on page 82. For more information. Therefore. To use a specific version of ActionScript or the Flash Player. so assigning the wrong type of value to a variable that you have strictly typed doesn’t generate a compiler error. For more information on strict data types and assigning data types.0. Because ActionScript is a dynamically typed language.

} About determining data type While testing and debugging your programs. This lets you create properties or assign dynamically methods at runtime. About data types 85 . you use the parameter to hold a value of type Number and then a value of type String. then a runtime error will occur. } } dynamicTest(100). You do not need to explicitly add data type information in your ActionScript. return myParam. function runtimeTest(myParam) { myParam. dynamicTest("one hundred"). An example of the flexibility afforded by dynamic type checking involves the use of properties and methods that are not known at compile time.For example. it can lead to benefits in some coding situations. The ActionScript compiler lets you use properties and invoke methods that do not exist at compile time. trace("String: " + myStr). function dynamicTest(xParam) { if (typeof(xParam) == "string") { var myStr:String = xParam. You can use the typeof operator to return information about data. the following code creates a function named runtimeTest() that invokes a method and returns a property. Using ActionScript. The code will not generate a compile-time error. the following code does not specify the data type of the parameter xParam. but if the property or method is not accessible at runtime. you might discover problems that seem to be related to the data types of different items.someMethod(). The dynamicTest() function then uses the typeof operator to test whether the parameter is of type String or Number. but remember that typeof does not return information about the class to which an instance belongs. } else if (typeof(xParam) == "number") { var myNum:Number = xParam. you might find it useful to know the data type of a given variable. At runtime.someProperty. Or if you use variables that are not explicitly associated with a data type. Because the code is less restrictive. you can determine an item’s data type. Use the typeof operator to get the data types. trace("Number: " + myNum). For example. neither of which is known to the compiler.

” on page 225. see Chapter 8.” on page 301. you can record and save information about what the user has done. “Classes. see Chapter 7. but the contents (the value) can change. or evaluate whether a condition is true or false. you create a new String variable named myName. such as when a player’s score changes in a Flash game. record values that change as the SWF file plays. trace(myNumber instanceof Number). The use of :Number in the previous code assigns the type of value that variable holds. /* typeof operator doesn't specify class. For more information on classes. see “About assigning data types and strict data typing” on page 81 and “Assigning a data type” on page 82. see Chapter 18. // object In this example. // true For more information about these operators. For more information on testing and debugging. “Debugging Applications. You might need the variable to continually update while the SWF file plays. only specifies that my_lv is an object */ var typeResult:String = typeof(my_lv). For more information on data typing.0 Language Reference. The following ActionScript shows what a variable looks like in ActionScript: var myVariable:Number = 10. This variable holds a numerical value. trace(myName instanceof String). var my_lv:LoadVars = new LoadVars(). trace(typeResult).” on page 711 For more information on inheritance and interfaces. see typeof operator and instanceof ActionScript 2. Variables are essential when you create and handle user interaction in a SWF file. // true var myNumber:Number = new Number(myName). The container (represented by the variable name) is always the same throughout your ActionScript. “Inheritance. called data typing. You can change the value of a variable in a script as many times as you want. and then convert it into a Number data type: var myName:String = new String("17"). operator in the About variables A variable is a container that holds information. When you change the value of a variable while the SWF file plays. 86 Data and Data Types .The following example shows how you can use the typeof operator to return the kind of object that you trace: // Create a new instance of LoadVars class.

you should be understand these differences to avoid unexpected behavior. Typical types of information that you can store in a variable include a URL (String type). a user’s name (String type). Then. TIP ■ ■ ■ ■ ■ ■ ■ ■ ■ Variables can hold different types of data. use the trace() statement to send the value to the Output panel. see “About data types” on page 72. For more information on variables. Initializing a variable helps you track and compare the variable’s value as the SWF file plays. To view the value of a variable. or whether a user has clicked a particular button (Boolean type). Assigning an initial value is called initializing the variable. see the following topics: “About declaring variables” on page 88 “About assigning values” on page 88 “About naming variables” on page 91 “Using variables in an application” on page 92 “About variables and scope” on page 96 “About default values” on page 88 “About operators and variables” on page 90 “About loading variables” on page 100 “Using variables in a project” on page 106 NO T E About variables 87 .It’s a good idea to assign a value to a variable the first time you declare the variable. The type of data that a variable contains affects how the variable’s value changes when you assign that value in a script. For example. the number of times an event occurred (Number type). for more information. If you have written scripts for Flash Player 6 and plan to write or port scripts for Flash Player 7 or later. Flash Player 7 and later evaluate uninitialized variables differently than Flash Player 6 and earlier. Each SWF file and object instance (such as a movie clip) has a set of variables. with each variable having a value independent of variables in other SWF files or movie clips. trace(hoursWorked) sends the value of the variable hoursWorked to the Output panel in the test environment. the value displays in the Output panel when you test the SWF file in the test environment. and it’s often done on Frame 1 of the Timeline or from within a class that loads when the SWF file begins to play. For more information on different kinds of variables and scope. the result of a mathematical operation (Number type). which are affected by scope. There are different kinds of variables. see “About variables and scope” on page 96. You can also check and set the variable values in the Debugger in the test environment.

About declaring variables You can declare variables on a frame in the timeline. directly on an object. You initialize a variable when you set its value for the first time. About default values A default value is the value that a variable contains before you set its value. you assign a data type to the variable. as long as the value matches the data type you assign to the variable. After you declare the variable. arrays. as shown in the following example: var firstName:String. About assigning values You can define a value as the current contents of a variable. If you declare a variable. dates. When you declare the variable. see “About assigning data types and strict data typing” on page 81. you also assign a data type to the variable. objects. numbers. you assign the String data type to the firstName variable. For more information on assigning data types. You might follow the previous line of ActionScript with this line: catName = "Pirate Eye". or even custom classes that you create. For more information on creating and using variables. you can assign a value to it. but do not set its value. or within an external class file. the value needs to be enclosed in straight quotes (quotation marks). In this case. You can also assign a value to a variable. N OT E 88 Data and Data Types . you declare a variable in Flash using the var keyword. The following example shows how you might create a variable called catName: var catName:String. The value can be a strings. Define variables using the var keyword and follow the variable naming conventions. The value of an uninitialized variable defaults to the value undefined. XML. that variable is uninitialized. You can declare a variable called firstName. Because Pirate Eye is a string. When you declare a variable. Remember. see “About variables” on page 86.

you can also assign a value to it instead of assigning it afterwards (as in the previous examples). When you reassign a value to an existing variable. you can assign a new value using the following ActionScript: numWrinkles = 60. var hasChildren:Boolean = false. About variables 89 . although you could also use a decimal or floating-point value such as 38.4. true or false. You could set the catName variable when you declare it. This statement sends the value to the Output panel. you will see the following error in the Output panel when you test the SWF file: Type mismatch in assignment statement: found Number where String is required. you don’t need to use the var keyword or define the variable’s data type (in this case. Examples of numeric and Boolean values are shown in the following snippet: var age:Number = 38. You can trace the value of the catName variable and see that the actual value doesn’t include the quotation marks by using the following ActionScript: var catName:String = "Pirate Eye". String). the variable age contains an integer (nondecimal) value. In the previous example. the value doesn’t use straight quotes (quotation marks). If you want to display the value of the catName variable in the test environment. as shown in the following example: var catName:String = "Pirate Eye". you can use the trace() statement. // Pirate Eye Remember that the value you assign must match the data type that you assign to it (in this case. var married:Boolean = true. as shown in the following code: var numWrinkles:Number = 55. such as catName = 10. trace(catName). If the value is numeric or Boolean (true or false). If you later try to assign a number to the catName variable. This error tells you that you attempted to set the wrong data type to a specified variable. When you assign a numeric value to a variable. the quotation marks aren’t necessary. When you declare the variable. If you want to change the value of numWrinkles later in your code.This example assigns the value of Pirate Eye to the catName variable. Boolean variables (such as married or hasChildren) have only two possible values. :Number).

age:50. and you use an operator to assign a value to a variable in your code. If you use the + operator on two or more string values. Similarly. myObj. You can use either of the following ways to create a new object. the strings will be concatenated. for example.width and Stage. You can rewrite the previous example as follows: var childrenArr:Array = ["Pylon". For more information on creating arrays and the array access operators. For example. "Smithers".age = 50.If you want to create an array and assign values to it. see “About arrays” on page 163 and “About using dot syntax to target an instance” on page 118.firstName = "Steve". "Chip"]}. "Gil"]. the format is slightly different. you could use the values of the following two predefined values: Stage. The values that operators manipulate are called operands. on the Internet or in books.height. Data and Data Types . N OT E 90 About operators and variables You might wonder about the mathematical symbols in your code. "Chip"). Not all variables need to be explicitly defined. shorthand way you can code the myObj array is as follows: var myObj:Object = {firstName:"Steve". you can create a new object called myObj. Some variables are created by Flash automatically for you. There is an alternative (shorthand) syntax for creating an array using array access operators. "Gil"). Operators calculate a new value from one or more values. You use the equality (=) operator to assign a value to a variable: var username:String = "Gus". to find the dimensions of the Stage. The second. "Robbie". myObj. Another example is the addition (+) operator. as shown in the following code: var childrenArr:Array = new Array("Pylon". which use the bracket ([]) punctuators. myObj. which you use to add two or more numeric values to produce a new value. especially when you define instances of objects. using the shorthand method can save a lot of typing and time. "Robbie".childrenArr = new Array("Mike". It is important to be familiar with this alternate syntax because you will encounter it if you work in teams or when you work with third-party ActionScript code that you find. These symbols are called operators in ActionScript. As you see in this example. "Smithers". childrenArr:["Mike". The first (and longer) way to code an array is as follows: var myObj:Object = new Object().

letter. A variable’s name must follow these rules: A variable must be an identifier. N OT E A variable cannot be a keyword or an ActionScript literal such as true. N OT E ■ ■ ■ ■ For more information on using operators in your ActionScript. About naming variables Be careful when you start naming variables. trace(helloStr. underscore (_). use the following code: numChildren = 8. Flash will generate a compiler error: // This code works as expected. For more information on literals. If you want to change the value of the numChildren variable. or dollar sign ($). // 0 // But if you give a variable the same name as a built-in class. function. underscore. A variable should not be any element in the ActionScript language.. you might experience syntax errors or unexpected results. or dollar sign. false. You don’t need to use var because the variable has previously been defined. if you name a variable new and then test your document. there are some rules. see “About operators” on page 176. the following script uses the assignment operator to assign a value of 7 to the variable numChildren: var numChildren:Number = 7. null. For example. The first character of an indentifier must be a letter. because although they can have nearly any name. An identifier is the name of a variable. trace(helloStr. object. you use an operator to define a value to a variable. var new:String = "hello". such as a class name. or undefined. //error: Identifier expected var helloStr:String = new String(). var helloStr:String = new String().When you assign a value. // undefined About variables 91 .length). If you don’t follow the rules when you name a variable. Each subsequent character can be a number. or method. In the following example. A variable must be unique within its scope (see “About variables and scope” on page 96)..length). see “About literals” on page 130. property.

// 36 Similar behavior occurs when you pass an undefined variable to a method or function. in the expression i+2. As soon as you type the period (. For example. trace(squared). 2. To compare undefined and defined variables being passed to a function: 1. the variable’s value in Flash Player 7 and later will be NaN.The ActionScript editor supports code hints for built-in classes and for variables that are based on these classes. 92 Data and Data Types . Open the Property inspector and type bad_button into the Instance Name text box. Using variables in an application In this section. If you want Flash to provide code hints for a particular object type that you assign to a variable. members. see Chapter 5. For example. Flash displays a list of methods and properties available for Array objects. see “Naming variables” on page 736. and your script might produce unintended results: var squared:Number = myNum * myNum. Drag a Button component to the Stage from the Components panel. For recommended coding conventions for naming variables. If you use an undefined variable. the statement that declares and initializes the variable myNum comes first. Code hints provide tooltip-style syntax hints and a pop-up menu that helps you write your code quickly. In the following example. as shown next. the variable is undefined and may cause unexpected results. as shown in the following example.) in the Actions panel. You need to declare and initialize a variable in a script before you can use it in an expression. and + is an operator. trace(squared). you use variables in short code snippets of ActionScript. var squared:Number = myNum * myNum. // NaN var myNum:Number = 6. you can strictly type the variable.” on page 113. type the following code: var members:Array = new Array(). so squared can be replaced with a value: var myNum:Number = 6. Expressions are combinations of operands and operators that represent a value. “Syntax and Language Fundamentals. i and 2 are operands. For more information on writing expressions. If you do not initialize a variable before you use it in an expression.

3.

Type the following code on Frame 1 of the Timeline.
// Does not work function badClickListener(evt:Object):Void { getURL(targetUrl); var targetUrl:String = "http://www.macromedia.com"; } bad_button.addEventListener("click", badClickListener);

4. 5. 6. 7.

Select Control > Test Movie, and notice that the button does not work (it doesn’t open the web page). Drag another Button component onto the Stage. Select the button. Open the Property inspector, and type good_button into the Instance Name text box. Add the following ActionScript to Frame 1 of the Timeline (following the previous ActionScript you added):
// Works function goodClickListener(evt:Object):Void { var targetUrl:String = "http://www.macromedia.com"; getURL(targetUrl); } good_button.addEventListener("click", goodClickListener);

8.

Select Control > Test Movie and click the second button you added to the Stage. This button properly opens the web page.

The type of data that a variable contains affects how and when the variable’s value changes. Primitive data types, such as strings and numbers, are passed by value, which means the current value of the variable is used rather than a reference to that value. Examples of complex data types include the Array and Object data types. In the following example, you set myNum to 15 and copy the value into otherNum. When you change myNum to 30 (in line 3 of the code), the value of otherNum remains 15 because otherNum doesn’t look to myNum for its value. The otherNum variable contains the value of myNum that it receives (in line 2 of the code).
To use variables in your ActionScript:
1. 2.

Create a new Flash document, and save it as var_example.fla. Select Frame 1 of the Timeline, and type the following code into the Actions panel:
var myNum:Number = 15; var otherNum:Number = myNum; myNum = 30; trace(myNum); // 30 trace(otherNum); // 15

About variables

93

When you change myNum to 30 (in line 3 of the code), the value of otherNum remains 15 because otherNum doesn’t look to myNum for its value. The otherNum variable contains the value of myNum that it receives (in line 2 of the code).
3. 4.

Select Control > Test Movie to see the values display in the Output panel. Now add the following ActionScript after the code you added in step 2:
function sqr(myNum:Number):Number { myNum *= myNum; return myNum; } var inValue:Number = 3; var outValue:Number = sqr(inValue); trace(inValue); // 3 trace(outValue); // 9

In the this code, the variable inValue contains a primitive value, 3, so the value passes to the sqr() function, and the returned value is 9. The value of the variable inValue does not change, although the value of myNum in the function changes.
5.

Select Control > Test Movie to see the values display in the Output panel.

The Object data type can contain such a large amount of complex information that a variable with this type doesn’t hold an actual value; it holds a reference to a value. This reference is similar to 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. For information on passing a variable by reference, see “Passing a variable by reference” on page 94.

Passing a variable by reference
Because the Array and Object data types hold a reference to a value instead of containing its actual value, you need be careful when you work with arrays and objects. The following example shows how to pass an object by reference. When you create a copy of the array, you actually create only a copy of the reference (or alias) to the array’s contents. When you edit the contents in the second array, you modify both the contents of the first and second array because they both point to the same value.

94

Data and Data Types

To pass an object by reference:
1. 2.

Select File > New and then select Flash Document to create a new FLA file, and save it as copybyref.fla. Select Frame 1 of the Timeline, and type the following code into the Actions panel:
var myArray:Array = new Array("tom", "josie"); var newArray:Array = myArray; myArray[1] = "jack"; trace(myArray); // tom,jack trace(newArray); // tom,jack

3.

Select Control > Test Movie to test the ActionScript. This ActionScript creates an Array object called myArray that has two elements. You create the variable newArray and pass a reference to myArray. When you change the second element of myArray to jack, it affects every variable with a reference to it. The trace() statement sends tom,jack to the Output panel.
Flash uses a zero-based index, which means that 0 is the first item in the array, 1 is the second, and so on.
NO TE

In the following example, myArray contains an Array object, so you pass the array to function zeroArray() by reference. 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.
To pass an array by reference:
1. 2.

Select File > New and then select Flash Document to create a new FLA file, and save it as arraybyref.fla. Add the following ActionScript to Frame 1 of the Timeline:
function zeroArray (theArr:Array):Void { var i:Number; for (i = 0; i < theArr.length; i++) { theArr[i] = 0; } } var myArr:Array = new Array(); myArr[0] = 1; myArr[1] = 2; myArr[2] = 3; trace(myArr); // 1,2,3 zeroArray(myArr); trace(myArr); // 0,0,0

About variables

95

3.

Select Control > Test Movie to test your ActionScript. The first trace() statement in this ActionScript displays the original contents of the myArray array (1,2,3). After you call the zeroArray() function and pass a reference to the myArray array, each of the array’s values are overwritten and set to zero. The subsequent trace() statement displays the new contents of the myArray array (0,0,0). Because you pass the array by reference and not by value, you don’t need to return the updated contents of the array from within the zeroArray() function.

For more information on arrays, see “About arrays” on page 163.

About variables and scope
A variable’s scope refers to the area in which the variable is known (defined) and can be referenced. The area in which the variable is known might be within a certain timeline or inside a function, or it might be globally known throughout the entire application.For more information about scope, see “About scope and targeting” on page 123. Understanding variable scope is important when you develop Flash applications with ActionScript. Scope indicates not only when and where you can refer to variables but also for how long a particular variable exists in an application. When you define variables in the body of a function, they cease to exist as soon as the specified function ends. If you try to refer to objects in the wrong scope or to variables that have expired, you get errors in your Flash documents, which lead to unexpected behavior or broken functionality. There are three types of variable scopes in ActionScript:

Global variables and functions are visible to every timeline and scope in your document. Therefore, a global variable is defined in all areas of your code. Timeline variables are available to any script on that timeline. Local variables are available within the function body in which they are declared (delineated by curly braces). Therefore, local variables are only defined in a part of your code.

■ ■

For guidelines on using scope and variables, see Chapter 5, “About scope and targeting,” on page 123.
ActionScript 2.0 classes that you create support public, private, and static variable scopes. For more information, see “About class members” on page 250 and “Controlling member access in your classes” on page 273.
NO T E 96

You cannot strict type global variables. For information and a workaround, see “Global variables” on page 97.

Data and Data Types

Global variables
Global variables and functions are visible to every timeline and scope in your document. To declare (or create) a variable with global scope, use the _global identifier before the variable name and do not use the var = syntax. For example, the following code creates the global variable myName:
var _global.myName = "George"; // Incorrect syntax for global variable _global.myName = "George"; // Correct syntax for global variable

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, as shown in the following example:
_global.counter = 100; // Declares global variable trace(counter); // Accesses the global variable and displays 100 function count():Void { for (var counter:Number = 0; counter <= 2; counter++) { // Local variable trace(counter); // Accesses local variable and displays 0 through 2 } } count(); trace(counter); // Accesses global variable and displays 100

This example simply shows that the global variable is not accessed in the scope of the count() function. However, you could access the global-scoped variable if you prefix it with _global. For example, you could access it if you prefix the counter with _global as shown in the following code:
trace(_global.counter);

You cannot assign strict data types to variables that you create in the _global scope, because you have to use the var keyword when you assign a data type. For example, you couldn't do:
_global.foo:String = "foo"; //syntax error var _global.foo:String = "foo"; //syntax error

The Flash Player version 7 and later security sandbox enforces restrictions when accessing global variables from SWF files loaded from separate security domains. For more information, see Chapter 17, “Understanding Security,” on page 677.

Timeline variables
Timeline variables are available to any script on that particular timeline. To declare timeline variables, use the var statement and initialize them in any frame in the timeline. The variable is available to that frame and all following frames, as shown in the following example.

About variables

97

To use timeline variables in a document:
1. 2.

Create a new Flash document, and name it timelinevar.fla. Add the following ActionScript to Frame 1 of the Timeline:
var myNum:Number = 15; /* initialized in Frame 1, so it's available to all frames */

3. 4. 5.

Select Frame 20 of the Timeline. Select Insert > Timeline > Blank Keyframe. With the new keyframe selected, type the following ActionScript into the Actions panel:
trace(myNum);

6.

Select Control > Test Movie to test the new document. The value 15 appears in the Output panel after approximately a second. Because Flash documents loop by default, the value 15 continually traces in the Output panel every time the playhead reaches Frame 20 in the Timeline. To stop the looping action, add stop(); after the trace() statement.

You must declare a timeline variable before trying to access it in a script. For example, if you put the code var myNum:Number = 15; in Frame 20, any scripts attached to a frame before Frame 20 cannot access myNum and are undefined instead of containing the value 15.

Local variables
When you use the var statement inside a function block, you declare local variables. When you declare a local variable within a function block (also called function definition), it is defined within the scope of the function block, and expires at the end of the function block. Therefore, the local variable only exists within that function. For example, if you declare a variable named myStr within a function named localScope, that variable will not be available outside of the function.
function localScope():Void { var myStr:String = "local"; } localScope(); trace(myStr); // Undefined, because myStr is not defined globally

98

Data and Data Types

If the variable name you use for your local variable is already declared as a timeline variable, the local definition takes precedence over the timeline definition while the local variable is in scope. The timeline variable will still exist outside of the function. For example, the following code creates a timeline string variable named str1, and then creates a local variable of the same name inside the scopeTest() function. The trace statement inside the function generates the local definition of the variable, but the trace statement outside the function generates the timeline definition of the variable.
var str1:String = "Timeline"; function scopeTest():Void { var str1:String = "Local"; trace(str1); // Local } scopeTest(); trace(str1); // Timeline

In the next example, you can see how certain variables live only for the life of a specific function and can generate errors if you try to refer to the variable outside the scope of that function.
To use local variables in an application:
1. 2.

Create a new Flash document. Open the Actions panel (Window > Actions) and add the following ActionScript to Frame 1 of the Timeline:
function sayHello(nameStr:String):Void { var greetingStr:String = "Hello, " + nameStr; trace(greetingStr); } sayHello("world"); // Hello, world trace(nameStr); // undefined trace(greetingStr); // undefined

3.

Select Control > Test Movie to test the document. Flash displays the string “Hello, world” in the Output panel and displays undefined for the values of nameStr and greetingStr because the variables are no longer available in the current scope. You can only reference nameStr and greetingStr in the execution of the sayHello function. When the function exits, the variables cease to exist.

About variables

99

The variables i and j are often used as loop counters. In the following example, you use i as a local variable; it exists only inside the initArray() function:
var myArr:Array = new Array(); function initArray(arrayLength:Number):Void { var i:Number; for(i = 0; i < arrayLength; i++) { myArr[i] = i + 1; } } trace(myArr); // <blank> initArray(3); trace(myArr); // 1,2,3 trace(i); // undefined It’s also common to see the following syntax for a for loop: for (var i:Number = 0; i < arrayLength; i++) {...}.
NO TE 100

This example displays undefined in the Flash test environment because the variable i isn’t defined in the main timeline. It exists only in the initArray() function. You can use local variables to help prevent name conflicts, which can cause unexpected results in your application. For example, if you use age as a local variable, you could use it to store a person’s age in one context and the age of a person’s child in another context. There is no conflict in this situation because you are using these variables in separate scopes. It’s good practice to use local variables in the body of a function so the function can act as an independent piece of code. You can change a local variable only within its own block of code. If an expression in a function uses a global variable, code or events outside the function can change its value, which changes the function. You can assign a data type to a local variable when you declare it, which helps prevent assigning the wrong type of data to an existing variable. For more information, see “About assigning data types and strict data typing” on page 81.

About loading variables
In the following sections, you load variables from the server in different ways or into a document from a URL string or FlashVars (you can use FlashVars to pass variables into Flash) in your HTML code. These practices demonstrate that there are several ways to use variables outside a SWF file. You can find more information on loading variables (such as name/value pairs) in Chapter 16, “Working with External Data,” on page 633.

Data and Data Types

You can use variables in different ways in a SWF file, depending on what you need the variables for. For more information, see the following topics:
■ ■ ■

“Using variables from the URL” on page 101 “Using FlashVars in an application” on page 104 “Loading variables from a server” on page 105

Using variables from the URL
When you develop an application or simple example in Flash, you might want to pass values from an HTML page into your Flash document. The passed values are sometimes known as the query string, or URL-encoded variables. URL variables are useful if you want to create a menu in Flash, for example. You can initialize the menu to show the correct navigation by default. Or you can build an image viewer in Flash and define a default image to show on the website.
To use URL variables in a document:
1. 2. 3.

Create a Flash document, and name it urlvariables.fla. Select File > Save As, and save the document on your desktop. Select Frame 1 of the Timeline, and add the following code in the Actions panel:
this.createTextField("myTxt", 100, 0, 0, 100, 20); myTxt.autoSize = "left"; myTxt.text = _level0.myURL;

4.

Select Control > Test Movie to test the SWF file in Flash Player. The text field displays undefined. If you want to make sure the variables are properly defined before you proceed, you need to check for the existence of the variables in Flash. You can do this by checking to see if they are undefined.

5.

To check to see if the variable is defined, modify the ActionScript you added to the Actions panel in step 3 to match the following code. Add the code that appears in bold:
this.createTextField("myTxt", 100, 0, 0, 100, 20); myTxt.autoSize = "left"; if (_level0.myURL == undefined) { myTxt.text = "myURL is not defined"; } else { myTxt.text = _level0.myURL; }

When you publish your Flash document, an HTML document is created by default in the same directory as the SWF file. If an HTML file was not created, select File > Publish settings, and make sure you select HTML in the Formats tab. Then publish your document again.

About variables

101

The following code demonstrates the HTML in the document that is responsible for embedding a Flash document in an HTML page. You need to look at this HTML to understand how URL variables work in the following step (where you add additional code for URL variables).
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/ swflash.cab#version=8,0,0,0" width="550" height="400" id="urlvariables" align="middle"> <param name="allowScriptAccess" value="sameDomain" /> <param name="movie" value="urlvariables.swf" /> <param name="quality" value="high" /> <param name="bgcolor" value="#ffffff" /> <embed src="urlvariables.swf" quality="high" bgcolor="#ffffff" width="550" height="400" name="urlvariables" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" /> </object> 6.

To pass variables from the generated HTML document to your Flash document, you can pass variables after the path and filename (urlvariables.swf). Add the bold text to the HTML file that was generated on your desktop.
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/ swflash.cab#version=8,0,0,0" width="550" height="400" id="urlvariables" align="middle"> <param name="allowScriptAccess" value="sameDomain" /> <param name="movie" value="urlvariables.swf?myURL=http:// weblogs.macromedia.com" /> <param name="quality" value="high" /> <param name="bgcolor" value="#ffffff" /> <embed src="urlvariables.swf?myURL=http://weblogs.macromedia.com" quality="high" bgcolor="#ffffff" width="550" height="400" name="urlvariables" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http:// www.macromedia.com/go/getflashplayer" /> </object>

7.

If you want to pass multiple variables to Flash, you need to separate the name/values pairs with an ampersand (&). Find the following code from step 6:
?myURL=http://weblogs.macromedia.com

Replace it with the following text:
?myURL=http://weblogs.macromedia.com&myTitle=Macromedia+News+Aggregator

102

Data and Data Types

Remember, you need to make the same changes to both the object tag and the embed tag to maintain consistency between all browsers. You might notice that the words are separated by + punctuators. The words are separated this way because the values are URLencoded and the + punctuator represents a single blank space.
For a list of common URL-encoded special characters, see the Flash TechNote, URL Encoding: Reading special characters from a text file.
NO TE

Because the ampersand (&) serves as a delimiter for different name/value pairs, if the values you are passing contain ampersands, unexpected results might occur. Given the nature of name/value pairs and parsing, if you had the following values being passed to Flash:
my.swf?name=Ben+&+Jerry&flavor=Half+Baked

Flash would build the following variables (and values) into the root scope:
'name': 'Ben ' (note space at end of value) ' Jerry': '' (note space at beginning of variable name and an empty value) 'flavor': 'Half Baked'

To avoid this, you need to escape the ampersand (&) character in the name/value pair with its URL-encoded equivalent (%26).
8.

Open the urlvariables.html document, and find the following code:
?myURL=http://weblogs.macromedia.com&myTitle=Macromedia+News+Aggregator

Replace it with the following code:
?myURL=Ben+%26+Jerry&flavor=Half+Baked 9.

Save the revised HTML, and test your Flash document again. You see that Flash created the following name/value pairs.
'name': 'Ben & Jerry' 'flavor': 'Half Baked' All browsers will support string sizes as large as 64K (65535 bytes) in length. FlashVars must be assigned in both the object and embed tags in order to work on all browsers.
N OT E

About variables

103

Using FlashVars in an application
Using FlashVars to pass variables into Flash is similar to passing variables along the URL in the HTML code. With FlashVars, instead of passing variables after the filename, variables are passed in a separate param tag as well as in the embed tag.
To use FlashVars in a document:
1. 2. 3.

Create a new Flash document, and name it myflashvars.fla. Select File > Publish Settings and make sure that HTML is selected, and then click OK to close the dialog box. Add the following ActionScript to Frame 1 of the main Timeline:
this.createTextField("myTxt", 100, 0, 0, 100, 20); myTxt.autoSize = "left"; if (_level0.myURL == undefined) { myTxt.text = "myURL is not defined"; } else { myTxt.text = _level0.myURL; } By default, HTML code publishes to the same location as myflashvars.fla.
N OT E

4. 5.

Select File > Publish to publish the SWF and HTML files. Open the directory containing the published files (where you saved myflashvars.fla on your hard drive) and open the HTML document (myflashvars.html by default) in an HTML editor such as Dreamweaver or Notepad. Add the code that appears in bold below, so your HTML document matches the following:
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/ swflash.cab#version=8,0,0,0" width="550" height="400" id="myflashvars" align="middle"> <param name="allowScriptAccess" value="sameDomain" /> <param name="movie" value="myflashvars.swf" /> <param name="FlashVars" value="myURL=http://weblogs.macromedia.com/"> <param name="quality" value="high" /> <param name="bgcolor" value="#ffffff" /> <embed src="myflashvars.swf" FlashVars="myURL=http:// weblogs.macromedia.com/" quality="high" bgcolor="#ffffff" width="550" height="400" name="myflashvars" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" /> </object>

6.

104

Data and Data Types

This code passes a single variable called myURL, which contains the string http://weblogs.macromedia.com. When the SWF file loads, a property named myURL is created in the _level0 scope. One of the advantages of using FlashVars or passing variables along the URL is that the variables are immediately available in Flash when the SWF file loads. This means you don’t have to write any functions to check if the variables have finished loading, which you would need to do if you loaded variables using LoadVars or XML.
7. 8.

Save your changes to the HTML document, and then close it. Double click myflashvars.html to test the application. The text http://weblogs.macromedia.com, a variable in the HTML file, appears in the SWF file.
All browsers will support string sizes as large as 64K (65,535 bytes) in length. FlashVars must be assigned in both the object and embed tags in order to work on all browsers.
NO TE

Loading variables from a server
There are several ways to load variables into Flash from external sources (such as text files, XML documents, and so on). You can find much more information on loading variables, including name/value pairs, in Chapter 16, “Working with External Data,” on page 633. In Flash, you can easily load variables using the LoadVars class, as shown in the next example.
To load variables from a server:
1. 2.

Create a new Flash document. Select Frame 1 of the Timeline, and add the following ActionScript in the Actions panel:
var my_lv:LoadVars = new LoadVars(); my_lv.onLoad = function(success:Boolean):Void { if (success) { trace(this.dayNames); // Sunday,Monday,Tuesday,... } else { trace("Error"); } } my_lv.load("http://www.helpexamples.com/flash/params.txt");

This code loads a text file from a remote server and parses its name/value pairs.
Download or view the text file (http://www.helpexamples.com/flash/params.txt) in a browser if you want to know how the variables are formatted.
TIP

About variables

105

3.

Select Control > Test Movie to test the document. If the file successfully loads, the complete event is called and the Output panel displays the value of dayNames. If the text file cannot be downloaded, the success argument is set to false and the Output panel displays the text Error.

Using variables in a project
When you build animations or applications with Flash, there are very few situations in which you don’t need to use any kind of variable in your project. For example, if you build a login system, you might need variables to determine whether the user name and password are valid, or whether they are filled in at all. You can find more information on loading variables (such as name/value pairs) in Chapter 16, “Working with External Data,” on page 633. In the following example, you use variables to store the path of an image you are loading with the Loader class, a variable for the instance of the Loader class, and a couple of functions that are called depending on whether the file is successfully loaded or not.
To use variables in a project:
1. 2.

Create a new Flash document, and save it as imgloader.fla. Select Frame 1 of the Timeline, and add the following ActionScript to the Actions panel:
/* Specify default image in case there wasn't a value passed using FlashVars. */ var imgUrl:String = "http://www.helpexamples.com/flash/images/ image1.jpg"; if (_level0.imgURL != undefined) { // If image was specified, overwrite default value. imgUrl = _level0.imgURL; } this.createEmptyMovieClip("img_mc", 10); var mclListener:Object = new Object(); mclListener.onLoadInit = function(target_mc:MovieClip):Void { target_mc._x = (Stage.width - target_mc._width) / 2; target_mc._y = (Stage.height - target_mc._height) / 2; } mclListener.onLoadError = function(target_mc:MovieClip):Void { target_mc.createTextField("error_txt", 1, 0, 0, 100, 20); target_mc.error_txt.autoSize = "left"; target_mc.error_txt.text = "Error downloading specified image;\n\t" + target_mc._url; } var myMCL:MovieClipLoader = new MovieClipLoader(); myMCL.addListener(mclListener); myMCL.loadClip(imgUrl, img_mc);

106

Data and Data Types

The first line of code specifies the image that you want to dynamically load into your Flash document. Next, you check whether a new value for imgURL was specified using FlashVars or URL-encoded variables. If a new value was specified, the default image URL is overwritten with the new value. For information on using URL variables, see “Using variables from the URL” on page 101. For information on FlashVars, see “Using FlashVars in an application” on page 104. The next couple of lines of code define the MovieClip instance, and a Listener object for the future MovieClipLoader instance. The MovieClipLoader’s Listener object defines two event handlers, onLoadInit and onLoadError. The handlers are invoked when the image successfully loads and initializes on the Stage, or if the image fails to load. Then you create a MovieClipLoader instance, and use the addListener() method to add the previously defined listener object to the MovieClipLoader. Finally, the image is downloaded and triggered when you call the MovieClipLoader.loadClip() method, which specifies the image file to load and the target movie clip to load the image into.
3.

Select Control > Test Movie to test the document. Because you’re testing the Flash document in the authoring tool, no value for imgUrl will be passed by FlashVars or along the URL, and therefore the default image displays.

4.

Save the Flash document and select File > Publish to publish the file as a SWF and HTML document.
Make sure that Flash and HTML are both selected in the Publish Settings dialog box. Select File > Publish Settings and then click the Formats tab. Then, select both options.
N OT E

5.

If you test your document in the Flash tool (select Control > Test Movie) or in a local browser (File > Publish Preview > HTML), you will see that the image centers itself both vertically and horizontally on the Stage. Edit the generated HTML document in an editor (such as Dreamweaver or Notepad), and modify the default HTML to match the following text:
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/ swflash.cab#version=8,0,0,0" width="550" height="400" id="urlvariables" align="middle"> <param name="allowScriptAccess" value="sameDomain" /> <param name="movie" value="urlvariables.swf" /> <param name="FlashVars" value="imgURL=http://www.helpexamples.com/flash/ images/image2.jpg"> <param name="quality" value="high" /> <param name="bgcolor" value="#ffffff" />

6.

About variables

107

<embed src="urlvariables.swf" quality="high" FlashVars="imgURL=http:// www.helpexamples.com/flash/images/image2.jpg" bgcolor="#ffffff" width="550" height="400" name="urlvariables" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" /> </object> 7.

Test the HTML document to see the changes. An image that you specify in the HTML code appears in the SWF file. To modify this example to use your own images, you would modify the FlashVars value (the string inside the double quotes).

Organizing data in objects
You might already be used to objects that you place on the Stage. For example, you might have a MovieClip object on the Stage, and this object contains other movie clips inside it. Text fields, movie clips, and buttons are often called objects when you place them on the Stage. Objects, in ActionScript, are collections of properties and methods. Each object has its own name, and it is an instance of a particular class. Built-in objects are from classes that are predefined in ActionScript. For example, the built-in Date class provides information from the system clock on the user’s computer. You can use the built-in LoadVars class to load variables into your SWF file. You can also create objects and classes using ActionScript. You might create an object to hold a collection of data, such as a person’s name, address. and telephone number. You might create an object to hold color information for an image. Organizing data in objects can help keep your Flash documents more organized. For general information on creating a custom class to hold a collection of methods and properties, see “Writing custom class files” on page 235. For detailed information on both built-in and custom classes, see Chapter 7, “Classes,” on page 225. There are several ways to create an object in ActionScript. The next example creates simple objects in two different ways, and then loops over the contents of those objects.
To create simple objects in Flash:
1. 2.

Create a new Flash document, and save it as simpleObjects.fla. Select Frame 1 of the Timeline, and type the following ActionScript into the Actions panel:
// The first way var firstObj:Object = new Object(); firstObj.firstVar = "hello world"; firstObj.secondVar = 28; firstObj.thirdVar = new Date(1980, 0, 1); // January 1, 1980

108

Data and Data Types

i < usersArr.fla. Create a new Flash document. and type the following ActionScript into the Actions panel: var usersArr:Array = new Array(). 3. Both objects are equivalent. Instead of having a series of variables such as firstname1.This code. To loop over each of the previous objects and display the contents of objects. which is one way to create a simple object. Thomas } 4. 4. To use an array to create an object: 1. } 5. // The second way var secondObj:Object = {firstVar:"hello world". The benefit of organizing variables into arrays and objects is that it becomes much easier to loop over the variables and see the values. 2. This code above creates a new object and initializes some properties using the object shorthand notation. usersArr. and firstname3 to represent a collection of variables. 1)}. // George.push({firstname:"John"}). Select Control > Test Movie. for (i = 0. var i:Number. as shown in the following step. firstname2. creates a new object instance and defines a few properties within the object. for (i in firstObj) { trace(i + ": " + firstObj[i]). Type the following code after the ActionScript you added in step 2. This technique is demonstrated next.push({firstname:"Thomas"}). John.firstname). secondVar:28. Select Frame 1 of the Timeline. Select Control > Test Movie. i++) { trace(usersArr[i]. usersArr. and the following text appears in the Output panel: George John Thomas Organizing data in objects 109 . and the following text appears in the Output panel: firstVar: hello world secondVar: 28 thirdVar: Tue Jan 1 00:00:00 GMT-0800 1980 You can also use arrays to create objects.length. thirdVar:new Date(1980. and save it as arrayObject. add the following ActionScript on Frame 1 of the Timeline (after the code you’ve already entered): var i:String. you can make an array of objects to represent the same data. Now enter the following ActionScript after the code you entered in step 2. usersArr. 0.push({firstname:"George"}). This is another way of creating an object. 3.

“Classes. var2:"Two". For more information on casting. var i:String. for (i in myObj) { trace(i + ": " + myObj[i]). an object is created and looped over using a for. Casting an object to a different type means you convert the value that the object or variable holds to a different type.. var myNumber:Number = Number(myBoolean). In this example.” on page 157.in loop.. the following code takes a Boolean value and casts it to an integer. var myBoolean:Boolean = true. For more information on objects. For information on for. you wrap the object name in parentheses (()) and precede it with the name of the new type.in loops. var3:18. For example. see Chapter 5. } //outputs the following: /* var1: One var2: Two var3: 18 var4: 1987 */ For information on creating for loops. To cast an object to a different type. see Chapter 7.0 lets you cast one data type to another. “Using for loops.in loops” on page 158. and each property appears in the Output panel: var myObj:Object = {var1:"One".” on page 225. see the following topics: ■ “About casting objects” on page 111 110 Data and Data Types . About casting ActionScript 2.. The results of a type cast vary depending on the data types involved. var4:1987}. see “Using for.The following example presents another way to loop over objects.

so no compile-time error occurs.bark(). the compiler cannot determine whether a cast will fail at runtime and won’t generate compile-time errors in those cases. the compiler doesn’t know that the cast will fail (that is. This is because the global conversion functions have precedence over the cast operators. Casting is essentially a function call. that you tried to cast a Cat object to an Animal type). Casting to null or undefined returns undefined. and the function call returns null if the cast fails at runtime (this occurs in files published for Flash Player 7 or later. function bark(myAnimal:Animal) { var foo:Dog = Dog(myAnimal).bark(). you asserted to the compiler that foo is a Dog object. If the cast succeeds. the function call returns the original object. However. if you include a check in your script to make sure that the cast succeeds. The following code shows an example: // Both the Cat and Dog classes are subclasses of the Animal class function bark(myAnimal:Animal) { var foo:Dog = Dog(myAnimal). bark(curAnimal). bark(curAnimal).About casting objects The syntax for casting is type(item). // Won't work In this example. you can find casting errors at runtime. } } You can cast an expression to an interface. and therefore the compiler assumes that foo. If not. For example. About casting 111 . However. files published for Flash Player 6 do not have runtime support for failed casts). the cast fails. as shown in the following example. the cast succeeds. foo. } var curAnimal:Animal = new Dog(). you can’t cast to Array because the Array() conversion function takes precedence over the cast operator. if (foo) { foo.bark(). However. If the expression is an object that implements the interface or has a base class that implements the interface. is a legal statement. N O TE You can’t override primitive data types that have a corresponding global conversion function with a cast operator of the same name. where you want the compiler to behave as if the data type of the item is type. // Will work curAnimal = new Cat().

as shown in the following example: var firstNum:String = "17". and String function. var secondNum:String = "29". Boolean function.0 Language Reference: Array function. Object function. The initial result is that the numbers are concatenated instead of added because they are a String data type. Data conversion is important when working with data loaded using XML or FlashVars.This example defines two string variables (firstNum and secondNum). see the entry for each conversion function in ActionScript 2. Number function. // 1729 trace(Number(firstNum) + Number(secondNum)). which are added together. // 46 For more information on data conversion functions. The second trace statement converts both numbers to a Number data type before performing the addition that yields the proper result. trace(firstNum + secondNum). 112 Data and Data Types .

” on page 731. a period ends a sentence.CHAPTER 5 Syntax and Language Fundamentals Learning ActionScript syntax and statements is like learning how to put together words to make sentences. a semicolon ends a statement. In Chapter 4. It contains many short code snippets and some examples to demonstrate fundamental language concepts. “Data and Data Types. N OT E 5 113 . and how you can format it in your code. ActionScript can do very simple or very complex things. in ActionScript. ActionScript can be as simple. For example. see Chapter 19. Most ActionScript terms also have individual requirements. in English.0 Language Reference. you can type a stop() action to stop the playhead of a movie clip instance or a SWF file from looping. For more information on how to apply the rules described in this section. for the rules for a specific term. You add ActionScript directly to a frame on the Timeline within this chapter.” you learned how the ActionScript language uses data. In the ActionScript language. This chapter demonstrates how you can form statements in ActionScript using syntax.0. Or you can write thousands of lines of code to power an interactive banking application. which you can then put together into paragraphs. As you can see. see its entry in the ActionScript 2. you use classes to separate your ActionScript from the FLA file. The general rules described in this section apply to all ActionScript. Applying the basics of ActionScript in a way that creates elegant programs can be a challenge for users who are new to ActionScript. “Best Practices and Coding Conventions for ActionScript 2. Upcoming chapters contain longer and increasingly involved code examples that combine and facilitate the fundamentals you learn in this chapter. In later chapters.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124 About constants and keywords . . . . . . . . . . . . . . . 114 Syntax and Language Fundamentals . . . . . . . . . . . . . . . . . . A statement is an instruction you give the FLA file to do something. . . . . . . . . . . . . . . . syntax is a collection of rules and guidelines that help you form correct ActionScript. . . . . . . . . . and expressions . . . you can use a conditional statement to determine whether something is true or exists. . . . . . . based on whether the condition is true or not. . . . . . . see “About statements” on page 141. . . . . . . . . . . . . . . . . . . . . . . . . . . .For more information on working with ActionScript syntax and language fundamentals. . . . . . . . . . . . . . . . // if statement if (condition) { // statements. } For more information on statements. . . . . . . statements. . . . . . . . . . Therefore. . You need to use correct ActionScript syntax to form statements so the code compiles and runs correctly in Flash. Then you might execute actions that you specify. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . see the following topics: About syntax. The if statement is a conditional statement and evaluates a condition to determine the next action that should occur in your code. . . . . . . syntax refers to the grammar and spelling of a language that you program with. . . . . 118 About language punctuators . . . . 176 About syntax. . . . . . . . . . such as to perform a particular action. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . and expressions The ActionScript language is made up of the built-in classes that make up the ActionScript language. . . . so you see errors or warnings displayed in the Output panel when you try to test the document in the test environment. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . For example. . . . . . statements. . . . . The compiler cannot understand incorrect syntax. . 163 About operators . In this case. . . . . . . . . . 135 About statements . . . . . . . .114 About dot syntax and target paths . . such as functions or expressions. . . . . . .141 About arrays . . .

are any legal combination of ActionScript symbols that represent a value. ActionScript will seem familiar. For example. The Java Technology site has tutorials on object-oriented programming (http:// java. see the following topics: ■ ■ “Differences between ActionScript and JavaScript” “About case sensitivity” Differences between ActionScript and JavaScript ActionScript is similar to the core JavaScript programming language. The expression follows ActionScript rules of precedence and of association. and procedures. ■ About syntax. it’s difficult to read the logic of a FLA file that doesn’t contain indents or comments. see “About operators” on page 176.com/docs/books/tutorial/java/index. For more information on objects and properties. the code is easier to read and debug if you encounter problems. different from statements. You don’t need to know JavaScript to use and learn ActionScript. There are many resources that provide more information about general programming concepts and the JavaScript language. see “Formatting ActionScript syntax” on page 764.html) that are targeted for the Java language but are useful for understanding concepts that you can apply to ActionScript. statements. see www. For more information on operators and operands. Typically. however. When you indent blocks of ActionScript (such as loops and if statements). This manual does not attempt to teach general programming. values. x and 2 are operands and + is an operator.Expressions. while values and properties have types.htm. For more information about formatting ActionScript. see “Object data type” on page 78. Expressions have values. For more information on syntax and language fundamentals. Flash Player interprets the expression and then returns a value that you can use in your application. functions. if you know JavaScript. ActionScript is based on this specification. You can also see proper formatting of ActionScript in these sections.sun.org/publications/standards/Ecma-262. ■ The ECMAScript (ECMA-262) edition 3 language specification is derived from JavaScript and serves as the international standard for the JavaScript language. The way you format your ActionScript also determines how maintainable your code is. An expression can consist of operators and operands. and expressions 115 . the following code is an expression: x + 2 In the previous expression. or contains inconsistent formatting and naming conventions. For more information. For example.ecmainternational.

The following ActionScript code shows this: // use mixed capitalization var firstName:String = "Jimmy".0 or ActionScript 2. In ActionScript.com/software/central.macromedia.org/publications/standards/Ecma-262. using different case.htm).hilite = true. = 10.ecmainternational. your code is case-sensitive.Some of the differences between ActionScript and JavaScript are described in the following list: ■ ActionScript does not support browser-specific objects such as Document. = 10. ActionScript does not support regular expressions using the RegExp object.hilite = true. or any identifier. // Creates three var myVar:Number var myvar:Number var mYvAr:Number N O TE 116 different variables = 10. This means that variables with slightly different capitalization are considered different from each other. // use all lower case trace(firstname). see Chapter 19. Syntax and Language Fundamentals .0 supports several features that are not in the ECMA-262 specification. ActionScript does not support some JavaScript syntax constructs. For more information on naming variables. Window.0. It is not a good practice to differentiate between variables. For more information on Macromedia Central.” on page 731. ActionScript does not completely support all the JavaScript built-in objects. “Best Practices and Coding Conventions for ActionScript 2. Macromedia Central does support the RegExp object. CAT. Many of these features are modeled after the ECMAScript (ECMA-262) edition 3 language specification (see www.0 // // Sets properties of two different objects cat. see www. ■ ■ ■ ■ ■ About case sensitivity When you write ActionScript for Flash Player 7 and later. such as statement labels. and Anchor. // undefined Or you could write the following: // In file targeting Flash Player 8 // and either ActionScript 1. ActionScript 2. the eval() function can perform only variable references. such as classes and strong typing. However.

For more information. you should review both external script files and scripts in FLA files to confirm that you used consistent capitalization.0). such as those loaded with LoadVars. classes. “Best Practices and Coding Conventions for ActionScript 2. Flash traces the string Jimmy in the Output panel. Case sensitivity is implemented on a per-SWF file basis. if you use loadMovie() to load a Flash Player 6 SWF file into a Flash Player 8 SWF file. language elements written with correct capitalization are blue by default.0 class files. and function names. if you use a ColdFusion web service. Case sensitivity can have a large impact when you work with a web service that uses its own rules for variable naming and for the case that variables are in when they are returned to the SWF file from the server. Case sensitivity also affects external variables that you load into a SWF file. while the version 8 SWF file is treated as case-sensitive. and expressions 117 . If you created FLA files for Flash Player 6 or earlier with nonmatching capitalization in your variables. About syntax. Unless you use the same case in Flash. When syntax coloring is enabled. Therefore. see Chapter 19.0. you might experience unexpected results. such as ActionScript 2. variable.0 or ActionScript 2.” on page 731. Doing so also makes it easier to differentiate between variables.When you publish for versions of Flash Player (Flash Player 6 and earlier). For example. such as FIRSTNAME. and scripts in a FLA file. For more information on coding conventions. firstName and firstname are two separate variables (when you use either ActionScript 1. such as those used in this manual. If a strict (case-sensitive) Flash Player 8 application calls a nonstrict Flash Player 6 SWF file. it’s good practice to follow consistent capitalization conventions. the version 6 SWF file remains case-insensitive. For example. ActionScript executed in the Player 6 SWF file is nonstrict. If you encounter runtime errors and are exporting to more than one version of Flash Player. N OT E Case sensitivity is implemented for external scripts.load(). Because Flash Player 7 and later versions are case-sensitive. or class name—not just the case. Do not use case to make two identifiers differ. scripts that you import using the #include command. Change the instance. see “About reserved words” on page 139. property names from a structure or object might be all uppercase. statements. This is an important concept to understand. your functionality and files might break during conversion of the file or application that targets a newer version of the Flash Player.

variables. you use a dot (. variable. You name a movie clip instance by selecting the instance and typing the instance name in the Property inspector. or button. or object. you must specify its name and its address in code. The path to the instance that you target is sometimes called the target path. You can create instances on the Stage or you can use ActionScript.About dot syntax and target paths In ActionScript. This is called a target path. The following sections demonstrate how to write dot syntax expressions. Or you can specify the instance name with code if you create the instance using ActionScript. loaded SWF file. You also use the dot operator to identify the target path to an instance (such as a movie clip). followed by a dot. To target (or address) objects in a SWF file. “About scope and targeting” on page 123 “Using the Target Path button” on page 124 “About slash syntax” on page 124 For more information on objects and properties. Dot syntax helps you create a path to the instance you need to target. you must specify a target path. A FLA file has a particular hierarchy. For more information on assigning an instance name and using dot syntax to target an instance. see “Object data type” on page 78. In order to specify a target path for a movie clip or button. About using dot syntax to target an instance To write ActionScript that controls an instance such as a movie clip or manipulates assets in a loaded SWF file. You can manipulate any instance as long as you name it. For example. To control a movie clip. and it ends with the element you want to specify. function. you use dot syntax (also called dot notation). A dot syntax expression begins with the name of the object or movie clip. Target paths are hierarchical addresses of movie clip instance names. 118 Syntax and Language Fundamentals .) operator (dot syntax) to access properties or methods that belong to an object or instance on the Stage. see the following topics: ■ ■ ■ ■ “About using dot syntax to target an instance” on page 118. You can even create instances that are inside other instances. you must assign an instance name to the movie clip or button. You can use the target path to assign an action to a movie clip or to get or set the value of a variable or property. and objects in a SWF file. Or you might have instances that nest within several other instances. you need to target a movie clip or button instance before you can apply an action to it.

You usually need to define where that instance is in the SWF file (for example. Use the Oval tool to draw a shape on the Stage. Dynamically by using ActionScript.jpg"). You can also give an instance name to an object you create using ActionScript. you target that particular instance and then tell it to do something (such as move the playhead or open a web page). To target an instance: 1. 2. which you can specify in two different ways (both demonstrated below): ■ Manually by selecting an instance and typing an instance name in the Property inspector (when an instance is on the Stage). Remember to select the stroke and fill if necessary. 3. Then. type a name into the Instance Name text box. This code creates a new movie clip and assigns it the instance name pic_mc. ■ To assign the instance an instance name in the Property inspector. For more information on working with scope.createEmptyMovieClip("pic_mc". T IP About dot syntax and target paths 119 . pic_mc. you need to target that instance and then tell it to do something. You create an instance using ActionScript and assign it an instance name when you create it. Select File > New and select Flash Document. When you do this.fla. what timeline it’s on or what instance it’s nested within) by creating the target path. this. 4.You name instances using an instance name. Draw an oval of any size and color.loadMovie("http://www. Use the Selection tool to select the oval on the Stage. and then you added code to the FLA file that uses those instance names. Targeting an instance If you want something to work in your SWF file. you can manipulate the pic_mc instance using code. see “About scope and targeting” on page 123 and “About variables and scope” on page 96. such as loading an image into it as demonstrated in the previous code. For more information on objects and properties. such as assigning it an action or changing its properties. Remember that you have given many of the instances in your FLA file instance names.helpexamples.getNextHighestDepth()). Select File > Save As and name the file target. see “Object data type” on page 78.com/flash/images/image1. It can be as simple as the following code: this.

Select the Movie Clip option and click OK. Select the new instance. Add the following ActionScript to Frame 1 of the actions layer: myClip. Select the new shape. you only need to target the instance using the instance name. The ActionScript scales the instance to half its original width. This ActionScript resizes the myOtherClip instance to 50% of its current width. 6. 2.5. 7. Open target. This line of code targets the myClip instance on the Stage. and rename it target2. If the instance was on a different timeline or nested within another instance._xscale = 50. 7. You can also target that nested instance using ActionScript. 3. and then select Modify > Convert to Symbol. 120 Syntax and Language Fundamentals .myOtherClip. and type myOtherClip in the Instance Name text box of the Property inspector. you need to complete the exercise in “Targeting an instance” on page 119. Targeting a nested instance You can also target instances that are nested inside other instances. 5. and then click OK to create the symbol. Click Scene 1 in the edit bar to return to the main Timeline.fla. and the myOtherClip is a nested symbol. you would need to modify the target path accordingly._xscale = 50.fla file modified the myClip instances _xscale property. To target a nested instance: 1. Because the ActionScript is on the same timeline as the movie clip symbol. 8. select the Movie Clip option. 4. Double-click the myClip instance on the Stage. 8. you’ll notice that myOtherClip will be 25 percent of the original width. Before you proceed with the following exercise. Because the target.fla from the procedure on targeting an instance. and then follow these steps to target a nested instance. Insert a new layer and rename the layer actions. Add the following ActionScript to Frame 1 of the actions layer: myClip. 6. Select the Oval tool and draw another oval inside of the myClip instance. Select the movie clip on the Stage and give it the instance name myClip in the Property inspector. Select Modify > Convert to Symbol. Perhaps you want to place a second movie clip instance inside of the myClip instance from the exercise in “Targeting an instance” on page 119.

rotateClip. For example. but you cannot see anything on the Stage. 4. you can use the following ActionScript to create a movie clip. Select Control > Test Movie to test your document. you might load an image into the movie clip. you won’t see anything on the Stage unless you add something to the movie clip. Targeting dynamic instances and loaded content You can also create an object using ActionScript and target it using a target path afterwards.If you work with nested movie clips that have their own timelines. see dynamic statement in the ActionScript 2. Even though you added code that creates a movie clip instance.nestedClip. Insert a new layer and rename the layer actions. as demonstrated in the previous examples._rotation = 50.fla. For more information about the dynamic statement. You can also set a variable within a movie clip.speed = 1. If either the speed or gravity variables existed previously in the starClip movie clip instance. 2.createEmptyMovieClip("rotateClip". this. you can manipulate the playhead in a nested instance’s timeline using code similar to the following snippet: myClip. For example. Then you can change the rotation of that movie clip using ActionScript. which sets a variable in the starClip movie clip: starClip. 5. Return to the authoring environment. trace(rotateClip). because the MovieClip class was defined with the dynamic keyword. Notice that the clip that you manipulate (such as nestedClip) appears right before the action. You are able to add new properties to the starClip movie clip. myClip.8. You’ll notice this trend in upcoming sections. the previous values would have been overwritten as soon as the new values were set. as seen in the following code.1.getNextHighestDepth()).gotoAndStop("tweenIn"). You can tell that you created a movie clip because of the trace statement. About dot syntax and target paths 121 .gravity = 0.gotoAndPlay(15). and open the Actions panel. Add the following ActionScript to Frame 1 of the actions layer: this. starClip. The dynamic keyword specifies that objects based on the specified class (in this case MovieClip) can add and access dynamic properties at runtime.someOtherClip. Create a new Flash document and save the file as targetClip. You aren’t limited to accessing predefined methods and properties of instances on the Stage. as shown in the next example: To target a dynamically created movie clip instance: 1. 3.0 Language Reference.

You can also target or identify parts of SWF files that you load into a base SWF file. The instance submitBtn is inside of formClip on the main timeline: this._visible = false. For example. You can express a method or property of a particular object (such as a movie clip or text field) using this pattern. loaderClip. Now you should see an image on the Stage that rotates 50º clockwise. if you want to set a variable for a form that’s inside another form.loadMovie("http://www. 122 Syntax and Language Fundamentals . you can use the following code. 99). you load a SWF file into level 99 and set its visibility to false: //Load the SWF onto level 99. For example. a SWF file loaded into level 99 has the target path _level99. }. the property of an object would be myClip. For example. 7.helpexamples. In the following example.formClip.jpg").mouseOver = true. To identify a loaded SWF file: ■ Use _levelX. Using the MovieClip. TIP Setting variables using a path You can set variables for instances that you nest inside of other instances. Select Control > Test Movie to test your document.onEnterFrame = function(){ _level99.submitBtn.6. This code loads an image into the rotateClip movie clip that you created with code. //Set the visibility of level 99 to false. Type the following ActionScript after the code you added in step 3: rotateClip. It’s generally a good idea to avoid using levels if you can load content into movie clips at different depths instead.getNextHighestDepth() method enables you to create new movie clip instances on the Stage dynamically without having to check whether there is already an instance at a particular depth._alpha = 50. loadMovieNum("contents. where X is the level number specified in the loadMovie() function that loaded the SWF file. You’re targeting the rotateClip instance with ActionScript.swf".com/flash/images/ image1.

myClip in the Output panel.0.” on page 731. If you trace the movie clip. “Best Practices and Coding Conventions for ActionScript 2. and you’ll see the following message in the Output panel: me: _level0. _root in the loaded file might point to the root scope of the SWF file it loads into. Double-click a movie clip.myClip my parent: _level0 This indicates you targeted the main timeline. When the SWF file loads into a different SWF file. you can drop the this keyword. target the parent of the movie clip (which is the main Stage). However. see Chapter 19. or break functionality altogether. you’ve probably noticed people using the _root scope. You can use relative target paths instead of _root. and just use myClip You might choose to add the this keyword for readability and consistency. when you target a movie clip called myClip that's on the current main timeline. Optionally. This can lead to unpredictable results. The _root scope generally refers to the main timeline of the current Flash document. you would use this. For more information on recommended coding practices._parent. instead of referring to its own root as you intend it to. If you're familiar with Flash and ActionScript.stop(). you use the this keyword. You can use parent to create a relative path to an object. For example. for either snippet above you see _level0. the movie clip that nests a second movie clip is known as the parent to the nested instance. the following statement on the instance dogClip tells animalClip to stop animating: this.About scope and targeting When you nest instances. The main Stage and main timeline are essentially a movie clip themselves. About dot syntax and target paths 123 . You can target parent instances and parent timelines using ActionScript. You should avoid using the _root scope unless it’s absolutely necessary. When you want to target the current timeline. and can therefore be targeted as such. Test the SWF file. if the movie clip dogClip is nested inside the animating movie clip animalClip. and place the following ActionScript on the movie clip’s timeline: trace("me: " + this). you can encounter errors if you load the SWF file into another Flash document. For more information on scope. For example. see “About variables and scope” on page 96. If you use _root in your code. trace("my parent: " + this. if you have ActionScript that’s inside the myClip movie clip but you want to target the main timeline. The nested instance is known as the child instance.myClip._parent).

To use the Target Path button: 1. see the Flash Lite product page. The target path for the selected instance appears in the Script pane. or what target path you need for a piece of code. Click OK. The movie clips in your current document appear in a dialog box. About slash syntax Slash syntax was used in Flash 3 and 4 to indicate the target path of a movie clip or variable. Each of these punctuators has a special meaning in the Flash language and helps define data types.0 and Flash Player 7 or Flash Player 8. see the following topics: ■ ■ ■ ■ ■ “Semicolons and colons” on page 125 “Curly braces” on page 126 “Parentheses” on page 129 “About literals” on page 130 “About comments” on page 131 124 Syntax and Language Fundamentals .Using the Target Path button Sometimes it takes some time to figure out what a given target path is. 3. terminate statements or structure ActionScript. Using slash syntax is not recommended unless you do not have another option. Select one of the instances from the list in the dialog box. but it’s not supported in ActionScript 2. The most common type of punctuators are semicolons (. For more information on Flash Lite. The following sections discuss how to use the punctuators in your code. such as when you create content intended specifically for Flash Player 4 or Flash Lite 1. 4. Open the Actions panel (Window > Actions) and click the Insert Target Path button. If you target an instance you have on the Stage. About language punctuators There are several language punctuators in Flash. For more information on language punctuators.). colons (:).0 in Flash Player 7 and earlier. you can use the Target Path button to determine what the path is to that instance.1 (and earlier) where you must use slash syntax. This syntax is supported by ActionScript 1. parentheses [()] and braces ({}). 2.

You use the semicolon to separate parameters. The example loops from 0 to 9 and then displays each number in the Output panel: var i:Number.1. return squared. When you click the Auto Format button in the Actions panel or Script window. as demonstrated in the following two lines of code: var myNum:Number = 50. To assign a specific data type to an item. Semicolons and colons ActionScript statements terminate with a semicolon (. see “Formatting ActionScript syntax” on page 764.) operator and array access ([]) operators. but doing so usually makes your code more difficult to read. for (i = 0.. // strict typing of parameters function welcome(firstName:String.. var myDate:Date = new Date(). } About language punctuators 125 . myAge:Number) { } // strict typing of parameter and return value function square(num:Number):Number { var squared:Number = num * num. it is good scripting practice to use semicolons because it makes your code more readable. specify its type using the var keyword and post-colon syntax. You can omit the semicolon character and the ActionScript compiler assumes that each line of code represents a single statement.9 } You use colons (:) in your code to assign data types to your variables.) character. // 0. as shown in the following example: // strict typing of variable or object var myNum:Number = 7. For information on white space and code formatting. myClip. i < 10. trailing semicolons are appended to the end of your statements by default.For more information on the dot (. as shown in the following example. Using a semicolon to terminate a statement allows you to place more than one statement on a single line. N OT E Another place you use semicolons is in for loops.. However._alpha = myNum.. i++) { trace(i). see “Using dot and array access operators” on page 184.

var numUsers:Number.0. For this reason. NO TE Place braces around each statement when it is part of a control structure (such as if. Coding conventions recommend that you put the opening brace on the same line for consistency. “Best Practices and Coding Conventions for ActionScript 2.You can declare the data type of objects based on built-in classes (Button. add braces so the code looks like the following example: var numUsers:Number. You put the opening brace on the same line as the declaration. and so on) and on classes and interfaces that you create. if you add a second statement after the trace statement. } Syntax and Language Fundamentals .” on page 71. Although this code validates. “Data and Data Types. The following example shows code that is written using poor form: for). which can lead to unexpected results. You can also specify that objects are of the Function or the Void data type. class definitions. Braces are added to this statement if you click the Check Syntax button. it is considered poor form because it lacks braces around the statements. MovieClip. and functions into blocks using curly brace ({}) punctuators. TI P 126 In this case. For more information on assigning data types."). see Chapter 4.. You can also put the opening brace on the line that follows the declaration. Curly braces You group ActionScript events. For information on braces and code conventions. if (numUsers == 0) { trace("no users found").” on page 731. see Chapter 19. In the following snippet.else or even if it contains only a single statement. if (numUsers == 0) trace("no users found. This good practice helps you avoid errors in your ActionScript when you forget to add braces to your code. the second statement executes regardless of whether the numUsers variable equals 0. you create a new object of the custom type Student: var firstStudent:Student = new Student(). Date.

jpg".helpexamples. }. this. // Student._lastName = lastName.onLoadError = function(target_mc:MovieClip):Void { trace("failure")._firstName = firstName.loadClip(imgUrl. var imgUrl:String = "http://www. public function Student(id:String. mclListener.as. }. _middleName:String. The next example displays a simple class file that could be used to create a Student object. this. _firstName:String._middleName = middleName. mclListener. img_mc). Select File > New and then select ActionScript File. var myClipl:MovieClipLoader = new MovieClipLoader(). 100). myClipl. var mclListener:Object = new Object(). this._id = id. middleName:String.addListener(mclListener).. you create both an event listener object and a MovieClipLoader instance. this.” on page 225. mclListener. “Classes._firstName = value. _lastName:String.com/flash/images/image1. 2.as class Student private var private var private var private var { _id:String. You learn more about class files in Chapter 7. } About language punctuators 127 . } public function get firstName():String { return this. firstName:String.createEmptyMovieClip("img_mc". }. Add the following ActionScript to the AS file. To use curly braces in an ActionScript file: 1.In the following example. Select File > Save As and save the new document as Student. } // . lastName:String) { this.onLoadInit = function(target_mc:MovieClip):Void { trace("success"). 3. myClipl.._firstName.onLoadStart = function() { trace("starting"). } public function set firstName(value:String):Void { this.

Save the new FLA file as student_test. and add the following ActionScript into the Actions panel: function checkForm():Boolean { status_lbl. trace(firstStudent. Select Control > Test Movie to test the FLA and AS files. 8. type an instance name of status_lbl into the Instance Name text box. Type the following ActionScript on Frame 1 of the main Timeline: // student_test. clickListener). 9.fla.text = "Please enter a first name. Drag an instance of the Label component from the Components panel onto the Stage. submit_button. } return true.text = "".firstName = "Craig".fla. 6. Select File > New and click Flash Document to create a new FLA file.fla import Student.firstName). }. 4. The next example demonstrates how curly braces are used when you work with functions. Drag an instance of the Button component onto the Stage and give it an instance name of submit_button.firstName). if (firstName_ti.".text. // John firstStudent. "Doe"). Save the class file.fla. Select File > New and select Flash Document to create a new FLA file. 7. // Craig 8.length == 0) { status_lbl. 6.addEventListener("click". Select Frame 1 of the Timeline. Type 200 into the W (width) text box to resize the component to 200 pixels wide. Select File > Save As and name the new file checkform. return false. var firstStudent:Student = new Student("cst94121". Drag an instance of the TextInput component onto the Stage and give it an instance name of firstName_ti. 5. To use curly braces with functions: 1. 128 Syntax and Language Fundamentals . Open the Property inspector (Window > Properties > Properties) and with the Label component instance selected. } function clickListener(evt_obj:Object):Void { var success:Boolean = checkForm(). "H. 5. 2. 7.". 3. Select File > Save to save the changes to student_test.4. "John". trace(firstStudent.

properties are defined in the object by specifying the variable names within the curly brace ({}) punctuators: var myObject:Object = {id:"cst94121". Select File > Save to save the Flash document. Control > Test Movie to test the code in the authoring environment. TI P Parentheses When you define a function in ActionScript. the following code creates an empty Object instance: var myObject:Object = {}. firstName:"John". lastName: Doe */ You can also use empty curly braces as a syntax shortcut for the new Object() function. true).9. myAge:Number. lastName:"Doe"}. 10._x + 20) * 0. 78. } /* id: cst94121 firstName: John middleName: H. middleName:"H. This error appears in the Label component and informs users that they need to enter a first name. you place parameters inside parentheses [()] punctuators. as shown in the following lines of code: function myFunction(myName:String. In the SWF file.". } When you call a function. Remember to make sure each opening curly brace has a matching closing brace. Select The next example using curly braces shows how to create and define properties within an object. For example. In this example. an error message is displayed if you click the Button instance on the Stage when you do not have text in the firstName_ti TextInput component. as seen in the following example: var computedValue:Number = (circleClip. This means you can change the order in which values are computed by placing brackets around certain values. for (i in myObject) { trace(i + ": " + myObject[i]). happy:Boolean):Void { // Your code goes here. var i:String. as shown in the following example: myFunction("Carl". About language punctuators 129 . You can use parentheses to override the ActionScript order of precedence or to make your ActionScript statements easier to read. you also include any of the parameters you pass to the function in parentheses.8.

5. "beta". var computedValue:Number = tempValue * 0. An array literal can be used to initialize an array. // assigning literal directly var myStrings:Array = ["alpha".8.4 null undefined true false Literals can also be grouped to form compound literals. 3._x + 20. 2. var myNums:Array = [1. 3. "gamma"]. 2. // using new statement var myStrings:Array = new Array("alpha".) to separate array elements. 130 Syntax and Language Fundamentals . you must add a statement to evaluate the expression. 5. but you can also assign literal values directly when instantiating instances of any built-in ActionScript class. meaning that the first operation would be 20 * 0._x and finally assigned to the computedValue variable. Literals are constant (unchanging) values within your Flash documents.8. "gamma"). as shown in the following example: var tempValue:Number = circleClip. If you don’t use parentheses. or even the string “foo”. you need to make sure each opening parentheses has a closing parentheses. Array literals are enclosed in bracket punctuators ([]) and use the comma punctuator (. var myNums:Array = new Array(1. "beta". The following examples are all literals: 17 "hello" -3 9. 8). 16. You can use the new statement and pass the compound literal as a parameter to the Array class constructor. if you didn’t use parentheses or use two separate statements. The following examples show two arrays that are initialized using array literals.Because of order of precedence. 1. About literals A literal is a value that appears directly in your code. would then be added to the current value of circleClip. false. The result. 52. As with brackets and braces. Examples of a literal include true. 8]. the multiplication would be computed first. 0.

and it can be helpful to anyone else who reads your code. // assigning literal directly var myObject:Object = {propA:1. For example. you should add comments to it. propB:2. you could improve the ActionScript by removing the work-around. Comments must clearly explain the intent of the code and not just translate the code.) to separate object properties. or you can assign the object literal directly to the instance you are declaring. if the issue is fixed or improved in a future version of Flash or Flash Player. the first line of code creates the string literal firstStr. You can create a generic object using the new statement and pass the object literal as a parameter to the Object class constructor. // using new statement var myObject:Object = new Object({propA:1. They make ActionScript easier to understand. answering both how and why. A generic object is an instance of the Object class. If something is not readily obvious in the code. propC:3}).Literals can also be used to initialize a generic object. Using comments to add notes to scripts is highly recommended. Do not confuse a string literal with a String object. For more information on strings. and the second line of code creates the String object secondStr: var firstStr:String = "foo" var secondStr:String = new String("foo") Use string literals unless you specifically need to use a String object for better performance. Using comments can help you remember important coding decisions. and 3. propC:3}. propB. which separates the name of the property from the value of the property. About comments Comments are a way of annotating your code with plain-English descriptions that do not get evaluated by the compiler. About language punctuators 131 . propA. Or. Object literals are enclosed in curly braces ({}) and use the comma punctuator (. propB:2. respectively. Comments document the decisions you make in the code. You can use comments within your code to describe what the code is doing or to describe which data returns to the document. Therefore. The following example creates a new generic object and initializes the object with three properties. see “About strings and the String class” on page 450. In the following example. you or another developer can easily find sections of code to update or fix. you might describe a work-around in comments. and propC. Each property is declared with the colon punctuator (:). 2. each with values set to 1.

it is usually a sign that the ActionScript is inelegant and not intuitive. such as “define the x and y variables” or other comments that are immediately obvious to other developers. If you format your ActionScript using the Auto Format button in the Actions panel or Script window. Single-line comments are typically used to explain a small code snippet. The following example includes a single-line comment: while (condition) { // handle condition with statements } Syntax and Language Fundamentals . or use single comment lines (//) to maintain spacing. remove any superfluous comments from the code. Using comments is most important in ActionScript that is intended to teach an audience. Remember to add white space back into your code. Before you deploy your project. or add a short description of what a piece of code accomplishes. these lines are easier to remove after you format your code than trying to determine where white space once was. Add comments to your code if you are creating sample applications for the purpose of teaching Flash or if you are writing articles or tutorials on ActionScript. When you enable syntax coloring. Comments can be any length without affecting the size of the exported file. You can use singleline comments for any short comments that fit on a single line. You might comment out a single line of code. as shown in the following code: // The following sets a local variable for age.Avoid using cluttered comments. To indicate that a line or portion of a line is a comment. An example of cluttered comments is a line of equal signs (=) or asterisks (*) used to create a block or separation around your comments. Instead. If you find that you have many extra comments in the ActionScript. and they do not need to follow rules for ActionScript syntax or keywords. use white space to separate your comments from the ActionScript. comments are gray by default. NO TE 132 Single-line comments You use single-line comments to add a comment to a single line in your code. precede the comment with two forward slashes (//). var myAge:Number = 26. this removes the white space. If you need to include many comments about how the code works. consider whether you need to rewrite some of the code.

Multiline comments
Use multiline comments, also called block comments, for comments that are several lines in length. Developers commonly use multiline comments to describe files, data structures, methods, and descriptions of files. They are usually placed at the beginning of a file and before or within a method. To create a comment block, place /* at the beginning of the commented lines and */ at the end of the comment block. This technique lets you create lengthy comments without adding // at the beginning of each line. Using // for numerous sequential lines can lead to some problems when you modify the comments. The format for a multiline comment is as follows.
/* The following ActionScript initializes variables used in the main and sub-menu systems. Variables are used to track what options are clicked. */ If you place the comment characters (/* and */) on separate lines at the beginning and end of the comment, you can easily comment them out by placing double slash characters (//) in front of them (for example, ///* and //*/). These let you quickly and easily comment and uncomment your code.
TI P T IP

By placing large chunks of script in a comment block, called commenting out a portion of your script, you can test specific parts of a script. For example, when the following script runs, none of the code in the comment block executes:
// The following code runs. var x:Number = 15; var y:Number = 20; // The following code is commented out and will not run. /* // create new Date object var myDate:Date = new Date(); var currentMonth:Number = myDate.getMonth(); // convert month number to month name var monthName:String = calcMonth(currentMonth); var year:Number = myDate.getFullYear(); var currentDate:Number = myDate.getDate(); */ // The code below runs. var namePrefix:String = "My name is"; var age:Number = 20; It’s good practice to place a blank line before a block comment.

About language punctuators

133

Trailing comments
You use trailing comments to add a comment on the same line as your code. These comments appear on the same line as your ActionScript code. Developers commonly use trailing comments to indicate what a variable contains or to describe or note the value that returns from a line of ActionScript. Format trailing comments as follows:
var myAge:Number = 26; // variable for my age trace(myAge); // 26

Space the comments to the right so readers can distinguish them from the code. Try to have the comments line up with each other, if possible, as shown in the following code.
var myAge:Number = 28; var myCountry:String = "Canada"; var myCoffee:String = "Hortons"; // my age // my country // my coffee preference

If you use autoformatting (click the Auto Format button in the Actions panel), trailing comments move to the next line. Add these comments after you format your code, or you must modify their placement after using the Auto Format button.

Comments inside classes
You use comments in your classes and interfaces to document them to help developers understand the contents of your class. You might start all your class files with a comment that provides the class name, its version number, the date, and your copyright. For example, you might create documentation for your class that is similar to the following comment:
/** Pelican class version 1.2 10/10/2005 copyright Macromedia, Inc. */

Use block comments to describe files, data structures, methods, and descriptions of files. They are usually placed at the beginning of a file and before or within a method. There are two kinds of comments in a typical class or interface file: documentation comments and implementation comments. Documentation comments are used to describe the code’s specifications and do not describe the implementation. You use documentation comments to describe interfaces, classes, methods, and constructors. Implementation comments are used to comment out code or to comment on the implementation of particular sections of code.

134

Syntax and Language Fundamentals

Include one documentation comment per class, interface, or member, and place it directly before the declaration. If you have additional information to document that does not fit into the documentation comments, use implementation comments (in the format of block comments or single-line comments). Implementation comments directly follow the declaration. The two kinds of comments use slightly different delimiters. Documentation comments are delimited with /** and */, and implementation comments are delimited with /* and */.
Don’t include comments that do not directly relate to the class being read. For example, do not include comments that describe the corresponding package.
TIP
■ ■ ■ ■ ■ ■

You can also use single-line comments, block comments, and trailing comments in class files. For more information on these kinds of comments, see the following sections: “Single-line comments” on page 132 “Multiline comments” on page 133 “Trailing comments” on page 134

About constants and keywords
Constants and keywords are the backbone of ActionScript syntax. Constants are properties with a fixed value that cannot be altered, so they are values that don’t change throughout an application. Flash includes several predefined constants, which can help simplify application development. An example of constants can be found in the Key class, which includes many properties, such as Key.ENTER or Key.PGDN. If you rely on constants, you never have to remember that the key code values for the Enter and Page Down keys are 13 and 34. Using constant values not only makes development and debugging easier, but it also makes your code easier to read by your fellow developers. Keywords in ActionScript are used to perform specific kinds of actions. They are also reserved words because of this, so you can’t use them as identifiers (such as variable, function, or label names). Examples of some reserved keywords are if, else, this, function, and return. For more information on constants and keywords, see the following topics: “Using constants” on page 136 “About keywords” on page 138 “About reserved words” on page 139

About constants and keywords

135

For more information on objects and properties, see “Object data type” on page 78. For a list of constants in the language (such as false and NaN), see the ActionScript Language Elements > Constants category in the ActionScript 2.0 Language Reference.

Using constants
Constants are properties with a fixed value that cannot be altered; in other words, they are values that don’t change throughout an application. The ActionScript language contains many predefined constants. For example, the constants BACKSPACE, ENTER, SPACE, and TAB are properties of the Key class and refer to keyboard keys. The constant Key.TAB always has the same meaning: it indicates the Tab key on a keyboard. Constants are useful for comparing values and for using values in your application that do not change. To test whether the user is pressing the Enter key, you could use the following statement:
var keyListener:Object = new Object(); keyListener.onKeyDown = function() { if (Key.getCode() == Key.ENTER) { trace("Are you ready to play?"); } }; Key.addListener(keyListener);

For the previous ActionScript to work, it may be necessary to disable keyboard shortcuts in the authoring environment. Select Control > Test Movie from the main menu, then while previewing the SWF file in the player, select Control > Disable Keyboard Shortcuts from the SWF file’s preview window. In Flash there is no way to create your own constant values except when you create your own custom classes with private member variables. You cannot create a “read-only” variable within Flash. Variables should be lowercase or mixed-case letters; however, constants (variables that do not change) should be uppercase. Separate words with underscores, as the following ActionScript shows:
var BASE_URL:String = "http://www.macromedia.com"; //constant var MAX_WIDTH:Number = 10; //constant

Write static constants in uppercase, and separate words with an underscore. Do not directly code numerical constants unless the constant is 1, 0, or -1, which you might use in a for loop as a counter value. You can use constants for situations in which you need to refer to a property whose value never changes. This helps you find typographical mistakes in your code that you might not find if you use literals. It also lets you change the value in a single place. For more information on literals, see “About literals” on page 130.
136 Syntax and Language Fundamentals

For example, the class definition in the next example creates three constants that follow the naming convention used by ActionScript 2.0.
To use constants in an application:
1. 2. 3.

Select File > New and then select ActionScript File to create an AS file. Name the new file ConstExample.as. Type the following code into the Script window:
class ConstExample { public static var EXAMPLE_STATIC:String = "Global access"; public var EXAMPLE_PUBLIC:String = "Public access"; private var EXAMPLE_PRIVATE:String = "Class access"; }

The EXAMPLE_STATIC property is a static property, which means that the property applies to the class as a whole instead of to a particular instance of the class. You must access a static property of a class using the name of the class instead of the name of an instance. You cannot access a static property through a class instance.
4. 5.

Create a new Flash document and save it as const.fla. Open the Actions panel, and type the following code on Frame 1 of the Timeline:
trace(ConstExample.EXAMPLE_STATIC); // output: Global access

When you declare the EXAMPLE_STATIC property as static, you use this code to access the value of the property.
6.

Select Control > Test Movie to test your document. You will see Global access in the Output panel. In the Actions panel, type this code following the code you added in step 5.
trace(ConstExample.EXAMPLE_PUBLIC); // error trace(ConstExample.EXAMPLE_PRIVATE); // error

7.

8.

Select Control > Test Movie to test your document. The EXAMPLE_PUBLIC and EXAMPLE_PRIVATE properties are not static properties. When you try to access the values through the class, you see the error message:
The property being referenced does not have the static attribute.

To access a property that is not static, you must access the value through an instance of the class. Because the EXAMPLE_PUBLIC property is a public property, it is available to code outside of the class definition.
9.

In the Actions panel, delete the trace statements that you added in steps 5 and 7.

About constants and keywords

137

10. Type

the following code into the Actions panel:

var myExample:ConstExample = new ConstExample(); trace(myExample.EXAMPLE_PUBLIC); // output: Public access

This code instantiates the myExample instance and accesses the EXAMPLE_PUBLIC property.
11.

Select Control > Test Movie to test your document. You see Public access in the Output panel. the Actions panel, delete the trace statement that you added in step 10.

12. In 13.

Type the following code into the Actions panel.
trace(myExample.EXAMPLE_PRIVATE); // error

The EXAMPLE_PRIVATE property is a private property, so it is available only within the class definition.
14. Select

Control > Test Movie to test your document.

You see The member is private and cannot be accessed in the Output panel. For more information on built-in classes and creating custom classes, see Chapter 7, “Classes,” on page 225.

About keywords
Keywords are words in ActionScript that do one specific thing. For example, you use the var keyword to declare a variable. The var keyword is shown in the following line of code:
var myAge:Number = 26;

A keyword is a reserved word that has a specific meaning: for example, you use the class keyword to define new a new ActionScript class; and you use the var keyword to declare local variables. Other examples of reserved keywords are: if, else, this, function, and return. Keywords cannot be used as identifiers (such as variable, function, or label names), and you should not use them elsewhere in your FLA files for other things (such as instance names). You have already used the var keyword a lot, particularly if you read Chapter 4, “Data and Data Types,” on page 71. ActionScript reserves words in the language for specific use. Therefore, you can’t use keywords as identifiers (such as variable, function, or label names). You can find a list of these keywords in “About reserved words” on page 139.

138

Syntax and Language Fundamentals

About reserved words
Reserved words are words that you cannot use as identifiers in your code because the words are reserved for use by ActionScript. Reserved words include keywords, which are ActionScript statements, and words that are reserved for future use. That means you should not use them for naming your variables, instances, custom classes, and so on; doing so can lead to technical problems in your work. The following table lists reserved keywords in Flash that cause errors in your scripts:
add catch delete eq function if in le not private static throw void and class do extends ge ifFrameLoaded instanceof lt on public switch try while break continue dynamic finally get implements interface ne onClipEvent return tellTarget typeof with case default else for gt import intrinsic new or set this var

The following table lists keywords that are reserved for future use by ActionScript or the ECMAScript (ECMA-262) edition 4 draft language specification. You should also avoid using these keywords in your code:
abstract byte debugger float enum long protected throws export synchronized double transient short char volatile goto

About constants and keywords

139

All built-in class names, component class names, and interface names are reserved words, and should not be used as identifiers in your code:
Accessibility Binding CellRenderer ComboBox CustomActions DataHolder Date DeltaItem Error Iterator Loader Math Microphone NetConnection Object ProgressBar ScrollPane SOAPCall StyleManager TextFormat Tree UIEventDispatcher Accordion Boolean CheckBox ComponentMixins CustomFormatter DataProvider DateChooser DeltaPacket FocusManager Key LoadVars Media Mouse NetStream PendingCall RadioButton Selection Sound System TextInput TreeDataProvider UIObject Alert Button Collection ContextMenu CustomValidator DataSet DateField DepthManager Form Label LocalConnection Menu MovieClip Number PopUpManager RDBMSResolver SharedObject Stage TextArea TextSnapshot TypedValue Video XML Array Camera Color ContextMenuItem DataGrid DataType Delta EndPoint Function List Log MenuBar MovieClipLoader NumericStepper PrintJob Screen Slide String TextField TransferObject UIComponent WebService XMLConnector

WebServiceConnector Window XUpdateResolver

Several words, although they are not reserved words, should not be used as identifiers (such as variable or instance names) in your ActionScript code. These are words that are used by the built-in classes that make up the ActionScript language. Therefore, do not use the names of properties, methods, classes, interfaces, component class names, and values as names in your code (such as when you name variables, classes, or instances).

140

Syntax and Language Fundamentals

To learn what these names are, refer to the ActionScript 2.0 Language Reference, and search the Help panel for additional instructional and usage sections in this book (Learning ActionScript 2.0 in Flash).

About statements
A statement is an instruction you give the FLA file to do something, such as to perform a particular action. For example, you can use a conditional statement to determine whether something is true or exists. Then your code might execute actions that you specify, such as functions or expressions, based on whether the condition is true or not. For example, the if statement is a conditional statement and evaluates a condition to determine the next action that should occur in your code.
// if statement if (condition) { // statements; }

Another example is the return statement, which returns a result as a value of the function in which it executes. There are many different ways for you to format or write ActionScript. You might differ from someone else who writes ActionScript in the way you form syntax, such as the way you space out your statements or where you put curly braces ({}) in your code. Even though there are several different ways you can form statements without breaking your code, there are some general guidelines you can follow to write well-formed ActionScript.
Place only one statement on a line to increase the readability of your ActionScript.

The

following example shows the recommended and not recommended statement usage:
theNum++; // recommended theOtherNum++; // recommended aNum++; anOtherNum++; // not recommended Assign variables as separate statements. var myNum:Number = (a = b + c) + d;

Consider the following ActionScript example:

This ActionScript embeds an assignment within the code, which is difficult to read. If you assign variables as separate statements, it improves readability, as the following example shows:
var a:Number = b + c; var myNum:Number = a + d;

The following sections show you how to form specific statements in ActionScript. For information on writing and formatting events, see Chapter 10, “Handling Events,” on page 329.

About statements

141

For more information on each statement, see the following topics:
■ ■ ■

“About compound statements” on page 142 “About conditions” on page 142 “Repeating actions using loops” on page 153

About compound statements
A compound statement contains numerous statements that you enclose within curly brace ({}) punctuators. The statements inside a compound statement can be any kind of ActionScript statement. A typical compound statement is shown below. The statements within the curly brace punctuators are indented from the compound statement, as the following ActionScript shows:
var a:Number = 10; var b:Number = 10; if (a == b) { // This code is indented. trace("a == b"); trace(a); trace(b); }

This compound statement contains several statements, but acts like a single statement in your ActionScript code. The opening brace is placed at the end of the compound statement. The closing brace begins a line, and aligns with the beginning of the compound statement. For more information on using braces, see “Curly braces” on page 126.

About conditions
You use conditions to determine whether something is true or exists, and then you can optionally repeat an action (using loops), or execute actions that you specify, such as functions or expressions, based on whether the condition is true or not. For example, you can determine whether a certain variable is defined or has a certain value and execute a block of code based on the result. Also, you could change the graphics within your Flash document based on what time the user's system clock is set to or on the weather in the user’s current location. To perform an action depending on whether a condition exists, or to repeat an action (create loop statements), you can use if, else, else if, for, while, do while, for..in, or switch statements.

142

Syntax and Language Fundamentals

For more information on conditions that you can use, and how to write them, see the following topics:
■ ■ ■ ■ ■ ■ ■

“About writing conditions” on page 143 “Using the if statement” on page 144 “Using the if..else statement” on page 145 “Using the if..else if statement” on page 146 “Using a switch statement” on page 147 “Using try..catch and try..catch..finally statements” on page 149 “About the conditional operator and alternative syntax” on page 152

About writing conditions
Statements that check whether a condition is true or false begin with the term if. If the condition evaluates to true, ActionScript executes the next statement. If the condition evaluates to false, ActionScript skips to the next statement outside the block of code.
To optimize your code’s performance, check for the most likely conditions first.
TIP

The following statements test three conditions. The term else if specifies alternative tests to perform if previous conditions are false.
if ((passwordTxt.text.length == 0) || (emailTxt.text.length == 0)) { gotoAndStop("invalidLogin"); } else if (passwordTxt.text == userID){ gotoAndPlay("startProgram"); }

In this code snippet, if the length of the passwordTxt or emailTxt text fields is 0 (for example, the user hasn’t entered a value), the Flash document redirects to the invalidLogin frame label. If both the passwordTxt and emailTxt text fields contain values and the passwordTxt text field’s contents match the userID variable, the SWF file redirects to the startProgram frame label. If you want to check for one of several conditions, you can use the switch statement rather than multiple else if statements. For more information on switch statements, see “Using a switch statement” on page 147. Refer to the following sections to learn how to write different kinds of conditions in your ActionScript applications.

About statements

143

Using the if statement
Use the if statement when you want to execute a series of statements based on a whether a certain condition is true.
// if statement if (condition) { // statements; }

There are several times when you’ll use if statements when you work on a Flash project. For example, if you are building a Flash site that requires users to log in before they can access certain sections of a website, you can use an if statement to validate that the user enters some text in the username and password fields. If you need to validate user names and passwords using an external database, you probably want to verify that the username/password combination a user submits matches a record in the database. You also want to check whether the user has permission to access the specified part of the site. If you script animations in Flash, you might want to use the if statement to test whether an instance on the Stage is still within the boundaries of the Stage. For example, if a ball moves downward along the y-axis, you might need to detect when the ball collides with the bottom edge of the Stage, so you can change the direction so that the ball appears to bounce upwards.
To use an if statement:
1. 2.

Select File > New and then select Flash Document. Select Frame 1 of the Timeline, and then type the following ActionScript in the Actions panel:
// create a string to hold AM and PM var amPm:String = "AM"; // no parameters pass to Date, so returns current date/time var current_date:Date = new Date(); // if current hour is greater than/equal to 12, sets amPm string to "PM". if (current_date.getHours() >= 12) { amPm = "PM"; } trace(amPm);

3.

Select Control > Test Movie to test the ActionScript. In this code, you create a string that holds AM or PM based on the current time of day. If the current hour is greater than or equal to 12 the amPM string sets to PM. Finally, you trace the amPm string, and if the hour is greater than or equal to 12, PM is displayed. Otherwise, you’ll see AM.

144

Syntax and Language Fundamentals

Using the if..else statement
The if..else conditional statement lets you test a condition and then execute a block of code if that condition exists or execute an alternative block of code if the condition does not exist. For example, the following code tests whether the value of x exceeds 20, generates a trace() statement if it does, or generates a different trace() statement if it does not:
if (x > 20) { trace("x is > 20"); } else { trace("x is <= 20"); }

If you do not want to execute an alternative block of code, you can use the if statement without the else statement. The if..else statement in Flash is similar to the if statement. For example, if you use the if statement to validate that a user’s supplied user name and password matches a value stored in a database, then you might want to redirect the user based on whether the user name and password are correct. If the login is valid, you can redirect the user to a welcome page using the if block. However, if the login was invalid, you can redirect the user to the login form and display an error message using the else block.
To use an if..else statement in a document:
1. 2.

Select File > New and then select Flash Document to create a new FLA file. Select Frame 1 of the Timeline, and then type the following ActionScript in the Actions panel:
// create a string that holds AM/PM based on the time of day. var amPm:String; // no parameters pass to Date, so returns current date/time. var current_date:Date = new Date(); // if current hour is greater than/equal to 12, sets amPm string to "PM". if (current_date.getHours() >= 12) { amPm = "PM"; } else { amPm = "AM"; } trace(amPm);

3.

Select Control > Test Movie to test the ActionScript. In this code, you create a string that holds AM or PM based on the current time of day. If the current hour is greater than or equal to 12, the amPM string sets to PM. Finally, you trace the amPm string, and if the hour is greater than or equal to 12, PM is displayed. Otherwise, you’ll see AM in the Output panel.

About statements

145

Using the if..else if statement
You can test for more than one condition using the if..else if conditional statement. You use the following syntax in an if..else if statement:
// else-if statement if (condition) { // statements; } else if (condition) { // statements; } else { // statements; }

You want to use an if..else if block in your Flash projects when you need to check a series of conditions. For example, if you want to display a different image on the screen based on the time of the day the user is visiting, you can create a series of if statements that determine if it’s early morning, afternoon, evening, or night time. Then you can display an appropriate graphic. The following code not only tests whether the value of x exceeds 20 but also tests whether the value of x is negative:
if (x > 20) { trace("x is > 20"); } else if (x < 0) { trace("x is negative"); }

To use an if..else if statement in a document:
1. 2.

Select File > New and then select Flash Document. Select Frame 1 of the Timeline, and then type the following ActionScript in the Actions panel:
var now_date:Date = new Date(); var currentHour:Number = now_date.getHours(); // if the current hour is less than 11AM... if (currentHour < 11) { trace("Good morning"); // else..if the current hour is less than 3PM... } else if (currentHour < 15) { trace("Good afternoon"); // else..if the current hour is less than 8PM... } else if (currentHour < 20) { trace("Good evening"); // else the current hour is between 8PM and 11:59PM } else { trace("Good night"); }

146

Syntax and Language Fundamentals

3.

Select Control > Test Movie to test the ActionScript. In this code, you create a string called currentHour that holds the current hour number (for example, if it’s 6:19 pm, currentHour holds the number 18). You use the getHours() method of the Date class to get the current hour. Then you can use the if..else if statement to trace information to the Output panel, based on the number that returns. For more information, see the comments in the previous code snippet.

Using a switch statement
The switch statement creates a branching structure for ActionScript statements. Similar to the if statement, the switch statement tests a condition and executes statements if the condition returns a value of true. When you use a switch statement, the break statement instructs Flash to skip the rest of the statements in that case block and jump to the first statement that follows the enclosing switch statement. If a case block doesn’t contain a break statement, a condition called “fall through” occurs. In this situation, the following case statement also executes until a break statement is encountered or the switch statement ends. This behavior is demonstrated in the following example, where the first case statement doesn’t contain a break statement and therefore both of the code blocks for the first two cases (A and B) execute. All switch statements should include a default case. The default case should always be the last case on a switch statement and should also include a break statement to prevent a fallthrough error if another case is added. For example, if the condition in the following example evaluates to A, both the statements for case A and B execute, because case A lacks a break statement. When a case falls through, it does not have a break statement, but includes a comment in the break statement’s place, which you can see in the following example after case A. Use the following format when you write switch statements:
switch (condition) { case A : // statements // falls through case B : // statements break; case Z : // statements break; default : // statements break; }

About statements

147

To use a switch statement in a document:
1. 2.

Select File > New and then select Flash Document. Select Frame 1 of the Timeline, and then type the following ActionScript in the Actions panel:
var listenerObj:Object = new Object(); listenerObj.onKeyDown = function() { // Use the String.fromCharCode() method to return a string. switch (String.fromCharCode(Key.getAscii())) { case "A" : trace("you pressed A"); break; case "a" : trace("you pressed a"); break; case "E" : case "e" : /* E doesn't have a break statement, so this block executes if you press e or E. */ trace("you pressed E or e"); break; case "I" : case "i" : trace("you pressed I or i"); break; default : /* If the key pressed isn’t caught by any of the above cases, execute the default case here. */ trace("you pressed some other key"); } }; Key.addListener(listenerObj);

3.

Select Control > Test Movie to test the ActionScript. Type letters using the keyboard, including the a, e, or i key. When you type those three keys, you’ll see the trace statements in the preceding ActionScript. The line of code creates a new object that you use as a listener for the Key class. You use this object to notify the onKeyDown() event when the user presses a key. The Key.getAscii() method returns the ASCII code of the last key that the user presses or releases, so you need to use the String.fromCharCode() method to return a string that contains the characters represented by the ASCII values in the parameters. Because “E” doesn’t have a break statement, the block executes if the user presses the e or E key. If the user presses a key that isn’t caught by any of the first three cases, the default case executes.

148

Syntax and Language Fundamentals

catch. control passes to the catch block.. If any code within the try code block throws an error (using the throw statement).finally blocks lets you add error handling to your Flash applications. if one exists. regardless of whether an error was thrown. you can write custom handlers to handle the error gracefully and take appropriate actions.. the code in the finally block still executes.catch and try. Then control passes to the finally code block.catch and try. You can even use the catch block to try to connect to a web service that alerts an administrator that a particular error occurred... so he or she can make sure the application works properly.finally statements using the following format: // try-catch try { // statements } catch (myError) { // statements } // try-catch-finally try { // statements } catch (myError) { // statements } finally { // statements } Any time your code throws an error. The finally block executes even if the try block exits using a return statement NO T E You write try.finally keywords let you enclose a block of code where an error can occur and respond to that error. The optional finally block always executes.. You might need to try loading external data from a web service or text file or to display an error message to the end user. The try. About statements 149 .....catch.. the try block completes normally). if one exists. If code within the try block doesn’t throw an error (that is.Using try.catch.finally statements Using try.catch.

to var n2:Number = 2. The Output panel displays Unable to divide by zero. try { if (n2 == 0) { throw new Error("Unable to divide by zero"). } catch (err:Error) { trace("ERROR! " + err. Select Control > Test Movie to test the document. } finally { delete n1. You aren’t limited to throwing new instances of the Error class when an error occurs. You could also extend the Error class to create your own custom errors. } 3. and then type the following ActionScript in the Actions panel: var n1:Number = 7. delete n2. the Output panel displays the result of n1 divided by n2.toString()). The finally block executes regardless of whether an error occurs and deletes the values of the n1 and n2 variables from the Flash document.catch. var n2:Number = 0. 4.finally block for data validation before dividing some numbers: 1.. Select Control > Enter to test the document again. If the value of n2 equals zero.. 5. 2. which displays a message in the Output panel. as demonstrated in the following example. If the value of y is not equal to zero. } trace(n1/n2). Select Frame 1 of the Timeline. Select File > New and then select Flash Document. an error is thrown and is caught by the catch block. Return to the authoring environment and change the following line of code: var n2:Number = 0. 150 Syntax and Language Fundamentals . 6.To use the try.

“Classes. About statements 151 . } else if (n2 < 0) { throw new Error("n2 cannot be less than zero"). n2 cannot be less than zero in the Output panel. Create a new Flash document named exception_test. and then save the file. var n2:Number = 0. Because the value of n2 equals 0.fla in the same directory as the ActionScript file. 6. try { if (n2 == 0) { throw new DivideByZeroException(). } } catch (err:DivideByZeroException) { trace(err. 5. Setting the value of n2 to any number greater than 0 causes the result of the division to appear in the Output panel.as: class DivideByZeroException extends Error { var message:String = "Divide By Zero error". " + err. Type the following ActionScript into the Script pane: // In DivideByZeroException. } catch (err:Error) { trace("An unknown error occurred. Flash throws your custom DivideByZeroException error class and displays Divide By Zero error in the Output panel. Select File > Save As and name the file DivideByZeroException.To create a custom error: 1. Save the ActionScript file.toString()).” on page 225.as. If you change the value of n2 in line two from 0 to -1. Type the following ActionScript into the Actions panel in Frame 1 of the main Timeline: var n1:Number = 7. } 7.toString()). Select File > New and create a new ActionScript file. 3. you would see An unknown error occurred. and retest the Flash document. } 4. For more information on creating custom classes. } else { trace(n1/n2). Save the Flash document and select Control > Test Movie to test the file in the test environment. 2. see Chapter 7.

also called conditional expressions. The second snippet is shorter and has fewer expressions to evaluate. 152 Syntax and Language Fundamentals . the shortened syntax reduces readability. trace((numTwo > 0) ? numOne/numTwo : "carrot"). } else { return false.else statements into a single line of code. place the leading condition (before the question mark [?]) inside parentheses. and so it is not preferable. and returns the result of numOne/numTwo or a string of carrot: var numOne:Number = 8. } However. The following code is an example of ActionScript with improved readability: var numOne:Number.. // 1. The operator helps decrease the amount of code you write while accomplishing the same thing. the ActionScript in the following example is preferable: return (cartArr. The conditional operator lets you convert simple if. As you can see. The following condition is written in long hand.About the conditional operator and alternative syntax If you like shortcuts. as the following example shows: if (cartArr. but it also tends to make your ActionScript more difficult to read. and checks whether the variable numTwo is greater than zero.6 } else { trace("carrot").length > 0). you would write the same code using this format: var numOne:Number = 8. var numTwo:Number = 0. It’s easier to read and understand.length > 0) { return true. You can write a conditional statement that returns a Boolean value. compared with the previous code. } Using a conditional expression. you can use the conditional (?:) operator. (numOne >= 5) ? numOne : -numOne. var numTwo:Number = 5. If you must use conditional operators. if (numTwo > 0) { trace(numOne / numTwo). This helps improve the readability of your ActionScript.

About statements 153 . while loops. In the for action. and do.. There are four types of loops in ActionScript: for loops. the counter and the statement that increments the counter are part of the action. If you do not use parentheses.while loops. Loops let you repeat a series of statements when a particular condition is true. For more information on operator precedence. you (or others working with your ActionScript) might run into operator precedence errors. Similar to while loops. Iterate over the children of a movie clip or object. You can declare a variable and write a statement that increases or decreases the variable each time the loop executes. see “About operator precedence and associativity” on page 179.in loops. For example.in loops while loops do. the following code does not use parentheses around the condition: if (fruit == "apple" && veggie == "leek") {} The following code uses good form by adding parentheses around conditions: if ((fruit == "apple") && (veggie == "leek")) {} Repeating actions using loops ActionScript can repeat an action a specified number of times or while a specific condition exists... for.while loops Description Repeat an action using a built-in counter. Loop for loops for. Each type of loop behaves somewhat differently. and each one is useful for different purposes. Each execution of a loop is called an iteration.. Most loops use some kind of counter to control how many times the loop executes. except the expression evaluates at the bottom of the code block. so the loop always runs at least once. Repeat an action while a condition exists. it is good form to use parentheses [()] to group conditions.When you write complex conditions.

} while (i > 0). such as web services or external text/XML files.. the expression is evaluated at the bottom of the code block so that the loop always runs at least once. In the following example. i--... This is shown in the following example: var i:Number = 4. } You can use the do. the expression is evaluated again. Use the while. To repeat an action while a condition exists: ■ Use the while statement. See the following procedures for more information on each of these loops. _y:i*20}).while) are useful when you want to loop over a series of statements but you don’t necessarily know how many times you need to loop. and you want to perform a series of statements on each item in the array.The most common type of loop is the for loop.while statement to create the same kind of loop as a while loop. This section contains general information on these loops. i. Another type of loop is the for. _y:i*20}). In this case you can use a while loop that loops as long as a certain condition is true. for. i--.while loop. if you have an array of items. After each statement in the body is executed. the loop executes four times: var i:Number = 4. This can be very useful when you are debugging your Flash projects and want to display the values that load from external sources.. i. In a do. 154 Syntax and Language Fundamentals . and for.duplicateMovieClip("newMC" + i. do.in actions to create loops.in loop. while (i > 0) { myClip. A while loop evaluates an expression and executes the code in the body of the loop if the expression is true. {_x:i*20. The final two types of loops (while and do. you would use a for loop and loop from 0 to the number of items in the array. which can be very useful when you want to loop over each name/value pair within an object and then perform some type of action. {_x:i*20. which loops over a block of code a predefined number of times. For more information on the while statement. For example.while. see “Using while loops” on page 160...duplicateMovieClip("newMC" + i. do { myClip. ActionScript can repeat an action a specified number of times or while a specific condition exists.

in with the typeof operator. Children include other movie clips. Each execution of a loop is called an iteration. The second expression (i > 0) is the condition that is checked each time before the loop runs. The following example uses the trace statement to print its results in the Output panel: var myObject:Object = {name:'Joe'. for (var i:Number = 4. i. In the following example.in statement. In the following example. over only movie clip children. with the value: Joe myObject has the property: age. objects.To repeat an action using a built-in counter: ■ Use the for statement. and variables. the counter and the statement that increments the counter are part of the action. with the value: " + myObject[propertyName]). the first expression (var i:Number = 4) is the initial expression that is evaluated before the first iteration. } This example produces the following results in the Output panel: myObject has the property: name. {_x:i*20. You can do this using for. You can declare a variable and write a statement that increases or decreases the variable each time the loop executes. i > 0. var propertyName:String. To loop through the children of a movie clip or an object: ■ Use the for. with the value: 25 myObject has the property: city. The third expression (i--) is called the post expression and is evaluated each time after the loop runs. } For more information on the for statement. see “Using for loops” on page 157. city:'San Francisco'}. a child movie clip instance (called instance2) is inside a movie clip instance on the Stage. _y:i*20}). i--) { myClip. for (propertyName in myObject) { trace("myObject has the property: " + propertyName + ". age:25. Most loops use some kind of counter to control how many times the loop executes. Add the following ActionScript to Frame 1 of the Timeline: for (var myName in this) { if (typeof (this[myName]) == "movieclip") { trace("I have a movie clip child named " + myName).duplicateMovieClip("newMC" + i... with the value: San Francisco You might want your script to iterate over a particular type of child—for example. functions. In the for action. } } About statements 155 .

The results vary on each computer you run it on.in statement.620 times before displaying an error message on a given computer. } When you work with arrays. "Sep". An infinite loop. for (i = 0. WA R N ING 156 For more information on each statement. such as “Using while loops” on page 160. "Oct". For example. the loop executes about 142. you need to be aware of a condition called an infinite loop. whether they’re simple or complex. The following code is an example of an infinite loop: // BAD CODE. "Aug".in loops” on page 158.. i < monthArr. for (i = 0. i++) { trace(monthArr[i]). You can probably see the obvious error immediately: if the value of i decreases after each loop iteration. This causes real problems—crashing your Flash application. Do you want to abort the script? Syntax and Language Fundamentals . or causing very inconsistent behavior of your Flash document. If it continues to run. see “Using for. "Nov". i--) { trace(i).. Poorly written loops can cause performance problems and stability issues. and their respective entries in the ActionScript 2. "Dec"). the end condition is never met. see the individual sections that follow in this chapter. as its name suggests. "Mar". var monthArr:Array = new Array("Jan". Iterations in Flash execute very quickly in the Flash Player. The following error message is displayed in a dialog box: A script in this movie is causing Flash Player to run slowly. A for loop iterates from 0 to the number of items in the array and displays each item in the Output panel.creates an infinite loop // USE AT OWN RISK! var i:Number. "Apr". "May". and the speed at which the code fails depends on the speed of the CPU and other factors. } The value of i is initialized to 0 and the end condition is met when i is greater than or equal to 10 and after each iteration the value of i is decremented.0 Language Reference. i < 10.For more information on the for. but loops depend heavily on the processor. The more iterations a loop has and the more statements executed within each block.length. About creating and ending loops The following example shows a simple array of month names. causing your Flash document to stop responding in a web browser. var i:Number. "Jul". is a loop with no end condition. "Feb". your computer may become unresponsive. the more processor resources will be consumed. "Jun".

see “Using a switch statement” on page 147. for (i = 0. and an expression that changes the value of the variable with each loop. In a for statement. For more information on controlling loops. 3. For example. This can be useful if you want to duplicate a movie clip on the Stage a certain number of times or to loop over an array and perform a task on each item in that array. About statements 157 .. condition. A for loop repeats an action using a built-in counter. A for loop is useful when you know exactly how many times you need to repeat a series of ActionScript statements. To create a for loop: 1. i < 5. Using for loops The for loop lets you iterate over a variable for a specific range of values. The value of the variable i starts at 0 and ends at 4. always make sure that the loop can exit properly and does not end up in an infinite loop. the following code loops five times. each on its own line. update) { // statements. Select the Export for ActionScript check box. Create a movie clip on the Stage. and type libraryLinkageClassName in the Class text input field. Click OK. 2.When you work with loops (and especially while and do. } In the next example.while loops). the first expression (i = 0) is the initial expression that evaluates before the first iteration. The third expression (i++) is called the post expression and is evaluated each time after the loop runs. i++) { trace(i). Right-click the movie clip symbol in the Library panel and select Linkage from the context menu. } You must supply three expressions to a for statement: a variable that is set to an initial value. the counter and the statement that increments the counter are all part of the for statement. and the output are the numbers 0 through 4. The second expression (i < 5) is the condition that you check each time before the loop runs. var i:Number. 4. Select File > New and then select Flash Document. a conditional statement that determines when the looping ends. You write the for statement using the following basic format: for (init.

"two". see the for statement in the ActionScript 2. For more information. Remember to include a space following each expression in a for statement. Select Control > Test Movie to test the code in Flash Player. for (var i:String in myObj) { trace(i + ": " + myObj[i]).in loops Use the for. which causes the loop to exit. Looping over objects can be an effective way to debug applications because it lets you see what data returns from web services or external documents such as text or XML files. } This code outputs the following in the Output panel: x: 20 y: 30 You can also iterate through the elements of an array: var myArray:Array = ["one". Using for.. This ActionScript duplicates the movie clip symbol in the library and repositions the clips on the Stage at x coordinates of 0. and then type the following ActionScript in the Actions panel: var i:Number. {_x:(i * 100)}).. Common uses of the for. On the last iteration of the loop. for (var i:String in myArray) { trace(myArray[i]). i++) { this. so properties appear in an unpredictable order): var myObj:Object = {x:20. you can use a for. and variables. properties of an object. The loop executes five times. with the variable i assigned a value of 0 through 4.. i < 5. include other movie clips.0 Language Reference. Select Frame 1 of the Timeline. } 158 Syntax and Language Fundamentals . i. Notice how five movie clips duplicate across the top of the Stage. "clip" + i + "_mc". functions. 100. objects.in loop include looping over instances on a timeline or looping over the key/value pairs within an object. "three"]. } 6. for (i = 0.. or elements of an array.in statement to loop through (or iterate through) the children of a movie clip. 300 and 400 pixels. For example. referenced previously.attachMovie("libraryLinkageClassName".in loop to iterate through the properties of a generic object (object properties are not kept in any particular order. Children.5.. the value of i increments to 4 and the second expression (i < 5) is no longer true. y:30}. 200.

However. For more information..This code outputs the following in the Output panel: three two one For more information on objects and properties.age = 27 myObj. The curly braces ({}) used to enclose the block of statements to be executed by the for. age:27. If you write a for. You cannot iterate through the properties of an object if it is an instance of a custom class.in loop in a class file (an external ActionScript file). 2.city = San Francisco About statements 159 . “Classes.name = Tara myObj. unless the class is a dynamic class. see the for. Select Frame 1 of the Timeline.in loop in a FLA file for an instance of the class. var i:String. When you test the SWF file. 3. For more information on writing class files. city:"San Francisco"}.. N OT E The following example uses for. if you write a for. instance members are not available within the loop.. you are able to iterate only through properties that are added dynamically. see “Object data type” on page 78.” on page 225. Even with instances of dynamic classes. you should see the following text in the Output panel: myObj. NO TE Select File > New and then select Flash Document. see Chapter 7..in statement are not necessary if only one statement executes. } Select Control > Test Movie to test the code in Flash Player. and then type the following ActionScript in the Actions panel: var myObj:Object = {name:"Tara".0 Language Reference.in to iterate over the properties of an object: To create a for loop: 1. but static members are.." + i + " = " + myObj[i]). for (i in myObj) { trace("myObj.in statement in the ActionScript 2. instance members are available but static members are not.

the statement or series of statements is skipped and the loop ends. If the condition evaluates to true. Select File > New and then select Flash Document. Open the Components panel and drag a DataSet component onto the Stage. the loop becomes an infinite loop. For example. 160 Syntax and Language Fundamentals . To create a while loop: 1. i++. but the while loop example does compile if you omit that step. 2. When the condition evaluates to false. Using while loops can be very useful when you aren’t sure of how many times you’ll need to loop over a block of code. 3. Open the Property inspector (Window > Properties > Properties) and type the instance name users_ds. The for loop example code does not compile if you omit the expression that increments the counter variable. while (i < 5) { trace(i).Using while loops Use the while statement to repeat an action while a condition exists. a statement or series of statements runs before looping back to evaluate the condition again. similar to an if statement that repeats as long as the condition is true. Without the expression that increments i. } You see the following numbers traced to the Output panel: 0 1 2 3 4 One disadvantage of using a while loop instead of a for loop is that infinite loops are easier to write with while loops. follow this example. the following code traces numbers to the Output panel: var i:Number = 0. A while loop evaluates an expression and executes the code in the body of the loop if the expression is true. To create and use a while loop in a FLA file.

. users_ds. age:" + users_ds.data. you create an infinite loop that displays a warning or crashes Flash Player. age:34}).addItem({name:"Irving".4.. the expression is evaluated at the bottom of the code block in a do.first().while statement. i++. and then type the following ActionScript in the Actions panel: var users_ds:mx. For more information on and examples of do.components.0 Language Reference..currentItem["age"]).DataSet.. Select Control > Test Movie to test the document. // users_ds. while (users_ds.while loops You can use the do. Use a for loop instead if you know how many times you want to loop. so the loop always runs at least one time.. About do.while loop (it’s checked after the code block executes). var i:Number = 5. see the ActionScript 2. // users_ds.. see the while statement in the ActionScript 2. Select Frame 1 of the Timeline. you need to avoid writing infinite loops. If the condition in a do.next(). users_ds.addItem({name:"Christopher". } while (i < 5). The statements execute only if the condition evaluates to true. About statements 161 . age:48 name:Walter.while loop continuously evaluates to true.currentItem["name"] + ". } 5.while loop that generates output even though the condition is not met. age:48}). However. users_ds. do { trace(i). The following information is displayed in the Output panel: name:Irving. // Output: 5 When you use loops. age:23}).0 Language Reference. age:23 For more information.while statement to create the same kind of loop as a while loop. age:34 name:Christopher.addItem({name:"Walter".hasNext()) { trace("name:" + users_ds. The following code shows a simple example of a do.

myArr[1] = {name:"Two". value:2}.in loop to iterate over each value and display the results in the Output panel. } trace("").length. // var i:Number.Using nested loops in your ActionScript The following example demonstrates how to make an array of objects and display each of the values in the nested structure. var item:String. Nesting a loop within another loop: 1. i < myArr. so you can loop over each item using a simple for loop. for (item in myArr[i]) { trace(item + ": " + myArr[i][item]). for (i = 0.. } 4. 2. myArr[0] = {name:"One".. The following is displayed in the Output panel. Create a new Flash document. 0 name: One value: 1 1 name: Two value: 2 You know how many items are in the array.fla. 3. 162 Syntax and Language Fundamentals . Select Control > Test Movie to test your code. Select File > Save As and name the document loops. Add the following code to Frame 1 of the Timeline: var myArr:Array = new Array(). you can use a for. Because each object in the array can have different name/value pairs.in loop to iterate through each key/ value pair in the nested objects. i++) { trace(i). value:1}. This example shows you how to use the for loop to loop through each item in the array and how to use the for.

"March". The following example is a simple array of month names. "April"]. You can also control and modify the array itself. you can store different kinds of data in a single array. The previous array of month names can also be rewritten as follows: var myArr:Array = new Array("January". myArr[3] = "April". you might want to move the engineering department to the basement of the building. and objects and even add a nested array at each array index. As such. the building (the array) contains floors (the elements). For example. as follows: var myArr:Array = ["January". myArr[0] = "January". you can use shorthand syntax. myArr[2] = "March".About arrays An array is an object whose properties are identified by numbers representing their positions in the structure. including other arrays. An array contains elements. an array is a list of items. "February". strings. As such. Each element has a numeric position (the index). myArr[1] = "February". "February". var myArr:Array = new Array(). Each floor of this building can contain multiple kinds of content (executives and accounting might share floor 3). dates. An array is like a structure for data. which are numbered floors (the index). You can mix numbers. which are equivalent to each floor of the building. This is similar to how each floor in a building has a floor number. and each floor contains one or more departments (the values). and they let you change the size of the array (say. and engineering on floor 5). Or. renovate the building and add more floors or remove floors). "April"). "March". where each floor contains a different piece of data (such as accounting on floor 3. you can add or remove elements and move values to different elements. Arrays let you move values around. Therefore. string. or even an array or object) or be empty. Each element can either hold a piece of data (which could be a number. About arrays 163 . Essentially. It’s important to remember that each element in an array doesn’t have to be the same data type. Boolean value. An array is like an office building. which is how you refer to each element's position in the array.

For information on adding and removing elements. Each object contains the song name. array. You can find a sample source file. see “Using dot and array access operators” on page 184. This sample illustrates array manipulation using ActionScript. Find the sample file in the following directories: ■ In Windows. or any other information that you might need to associate with a particular file. see “Creating multidimensional arrays” on page 169. If you load data from remote web servers. 164 Syntax and Language Fundamentals . For example. arrays contain data in a similar format. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Arrays. For more information on common arrays. The location of an item in an array is called the index. location of a sound file (such as an MP3). stored in objects. For information on the array access operator. see “Using arrays” on page 164. you might even receive data as an array of nested objects. Often. You can use them to store lists of objects. On the Macintosh. For information on using arrays and about indexes. you also use the array access ([]) operator. adds. you might have a user’s playlist stored as an array of song information. and removes items of two List components. To access the elements of an array. For information on the array access operator. For more information on multidimensional arrays. and so on. All arrays are zero-based. The code in the sample creates an array and sorts.For more information on modifying arrays. if you build an audio application in Flash. see “About arrays” on page 163. The built-in Array class lets you access and manipulate arrays. such as a bunch of returned items. For more information on associative arrays. you use the constructor new Array() or the array access operator ([]). browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Arrays. ■ Using arrays There are several different ways you can use arrays in your work. There are different kinds of arrays. the second element is [1]. see “Using dot and array access operators” on page 184. artist name. The second kind of array is called an associative array and uses a text index instead of a numerical index to look up information.fla. The most common arrays use a numerical index to look up a particular item in an indexed array. which means that the first element in the array is [0]. song duration. in the Samples folder on your hard disk. The next example uses an indexed array. see “Creating associative arrays” on page 172. which you'll discover in the following sections. see “About adding and removing elements” on page 168. see “About modifying arrays” on page 166. To create an Array object.

in loop to iterate over each of the items in that array and display the key/value pairs in the Output panel using a trace statement. The code in the sample creates an array and sorts.. in the Samples folder on your hard disk. Find the sample file in the following directories: ■ In Windows. adds.fla. Add the following ActionScript to Frame 1 of the Timeline: // define a new array var myArr:Array = new Array(). For information on how to create different kinds of arrays. This sample illustrates array manipulation using ActionScript.in loops” on page 158. value: value0 key: 1. myArr[0] = "value0". value: value1 For more information on for. browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Arrays.. Create a new Flash document. and removes items of two List components.fla. value: " + myArr[i]). for (i in myArr) { // trace the key/value pairs trace("key: " + i + ". 3. ■ About arrays 165 . } In the first line of ActionScript. On the Macintosh. You use a for. and save it as basicArrays. The following text is displayed in the Output panel: key: 0. you define a new array to hold the values. 2.. Then. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Arrays.To use arrays in your code: 1. you define data (value0 and value1) at two indexes of the array. // iterate over the items in the array var i:String. Select Control > Test Movie to test your code. see the following sections: ■ ■ ■ “Creating indexed arrays” on page 168 “Creating multidimensional arrays” on page 169 “Creating associative arrays” on page 172 You can find a sample source file.in loops. // define values at two indexes myArr[1] = "value1". see “Using for. array.

Engineering. You can move values around an array.undefined. if you use the following code instead. trace(buildingArr). The code in the sample creates an array and sorts. you can save the value and safely copy it back later in your code. ■ 166 Syntax and Language Fundamentals . On the Macintosh.undefined. in the Samples folder on your hard disk.undefined. if you want to exchange data at two indexes in an array. adds.Engineering You can find a sample source file. buildingArr[2] = "Accounting".Accounting. // wrong way (no temporary variable) buildingArr[2] = buildingArr[4].About modifying arrays You can also control and modify the array using ActionScript. and removes items of two List components. trace(buildingArr). array. If you copied the contents of array index 4 into array index 2 and vice versa. browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Arrays. This sample illustrates array manipulation using ActionScript. you can see that the value of array index 2 (Accounting) has been lost. buildingArr[4] = buildingArr[2]. Find the sample file in the following directories: ■ In Windows.undefined. // undefined. trace(buildingArr). buildingArr[4] = "Engineering". buildingArr[4] = temp_item. For example. // undefined. buildingArr[2] = buildingArr[4].Engineering var temp_item:String = buildingArr[2]. you can use the following code: var buildingArr:Array = new Array(). or you can change the size of the array. the original contents of array index 2 would be lost. Now you have two engineering teams but no accountants. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Arrays.Accounting You might wonder why you need to create a temporary variable in the previous example. When you copy the value from one of the array indexes into a temporary variable.fla.undefined. For example. // undefined.undefined.Engineering.

"Apr". "Oct".Nov.undefined. and not the actual number of items in the array as you might expect: var myArr:Array = new Array(). "Nov".MAY. On the Macintosh.Jun.OCT. and also the array’s length.toUpperCase().fla. adds. The contents are displayed.length). and removes items of two List components.undefined.length).Oct. the length of the array returns 6 (because the array is zero based).undefined.Aug. // undefined. // 12 var i:Number. for (i = 0.Feb. see “Using for loops” on page 157. Find the sample file in the following directories: ■ In Windows. myArr[5] = "five". browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Arrays.Apr. "Jun". This can be very useful when writing for loops that iterate through every element in the array and execute a series of statements. You can find a sample source file.SEP. The code in the sample creates an array and sorts.undefined.May. see “Using dot and array access operators” on page 184. you create an array and populate it with month names. if you create an element at array index 5 in an array.JUL. trace(monthArr). "Sep". i++) { monthArr[i] = monthArr[i]. "Dec").APR.length. and the array contents are displayed again.five For more information on for loops. This sample illustrates array manipulation using ActionScript. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Arrays. } trace(monthArr).About referencing and finding length When you work with arrays. i < monthArr. "Jul".AUG. A for loop iterates over each item in the array and converts the value to uppercase.Sep.FEB. "May". "Mar".MAR.DEC In the previous example. // Jan. ■ About arrays 167 . "Feb".Dec trace(monthArr. array.Mar. // JAN. you often need to know how many items exist in the array. For information on the array access operator.Jul. In the following ActionScript. You can see an example in the following snippet: var monthArr:Array = new Array("Jan". // 6 trace(myArr). in the Samples folder on your hard disk.NOV. trace(myArr. "Aug".JUN.

This helps you when you debug your applications. and the item at array index 5 changed to a blank string instead of disappearing completely.Feb. and removes items of two List components. "Mar". in the Samples folder on your hard disk.May. In “About referencing and finding length” on page 167. Each element can either hold a piece of data or be empty.Nov. which is how you refer to each element's position in the array. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Arrays. or even an array or object. "Jul". You can look up items by their position in the array.Sep. "Aug". This causes five undefined values to be inserted into the array.Jul. "Jun". "Apr". The following example demonstrates how to create a new array. trace(monthArr). and add and replace data at an index in an array: var monthArr:Array = new Array("Jan".undefined. On the Macintosh. "Oct". The first index is always the number 0.Aug. adds.Aug. "Nov". You can create an indexed array by calling the Array class constructor or by initializing the array with an array literal. delete monthArr[5]. which you might have done in earlier sections. delete an item at a particular index.Dec trace(monthArr. ■ Creating indexed arrays Indexed arrays store a series of one or more values. array. string. You can find a sample source file. The code in the sample creates an array and sorts. Find the sample file in the following directories: ■ In Windows.About adding and removing elements An array contains elements and each element has a numeric position (the index). When you create elements in an array. browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Arrays. trace(monthArr). // Jan.Feb. "Dec").Mar.JUN. An element can hold the following data: a number.fla. you should create the indexes sequentially whenever possible. the array length returns as 6.Sep. // 12 monthArr[5] = "JUN".Nov.Jul.Apr. Boolean. // Jan.Oct. "Sep". and the index increments by one for each subsequent element that you add to the array.May.Oct. the array length is still 12. You create arrays using the Array constructor and an array literal in the next example.Dec Even though you deleted the item at array index 5.Apr.length). This sample illustrates array manipulation using ActionScript. "Feb". you saw that if you assign a single value in an array at index 5.Mar. "May". 168 Syntax and Language Fundamentals .

"take out trash"]. // one.two. when you are programming. Add the following ActionScript to Frame 1 of the Timeline: var myArray:Array = new Array(). 5. trace(myArray). This code is the equivalent of the ActionScript you wrote in step 2. // one. "three"]. The following text is displayed in the Output panel: one.two. trace(myArray).To create an indexed array: 1. also known as multidimensional arrays. Each element contains an indexed array that stores the list of tasks.three In the first line of ActionScript. you can implement arrays as nested arrays that are essentially arrays of arrays. "two". and save it as indexArray. you define a new array to hold the values. and delete the code in the Actions panel. Create a new Flash document. When you use the array access operator. myArray. When you test the code. Add the following ActionScript to Frame 1 of the Timeline: var myArray:Array = ["one". consider a list of tasks that is stored as an indexed array of strings: var tasks:Array = ["wash dishes".push("one").push("three"). you might use multidimensional arrays to model these kinds of structures. Return to the authoring tool.two. For example.three In this code you use the array literal to define a new array for your code. 3. Creating multidimensional arrays In ActionScript. you can create a multidimensional array with one element for each day of the week. Nested arrays. C A UT I ON About arrays 169 . you see the same output appear in the Output panel. Therefore. each of which is also an array that contains eight elements.fla. If you want to store a separate list of tasks for each day of the week. a chess board is a grid of eight columns and rows. myArray. you could model the chess board as an array that contains eight elements. Select Control > Test Movie to test your code. the ActionScript compiler cannot check whether the accessed element is a valid property of the object. 2.push("two"). can be thought of as matrices or grids. myArray.three 4. For example.

var j:Number. for (i = 0. consists of two array elements.fla. Add the following ActionScript to Frame 1 of the Timeline: var twoDArray:Array = new Array(new Array("one". twoDArray is the main array that contains two nested arrays. Add the following ActionScript at the end of your code on Frame 1 of the Timeline: trace(twoDArray[0][0]). Add the following ActionScript to Frame 1 of the Timeline: var gridSize:Number = 3. // one trace(twoDArray[1][1]). 170 Syntax and Language Fundamentals . twoDArray. one four You can use nested for loops to create multidimensional arrays.four 4. Select Control > Test Movie to test the code. you use multiple array access ([]) operators after the name of the top-level array. Select Control > Test Movie to test the code.three. In this case. 6. new Array("three". and save it as multiArray2. These elements are themselves arrays consisting of two elements. one.To create a basic multidimensional array and retrieve elements from the array: 1. 5. var mainArr:Array = new Array(gridSize). Create a new Flash document. // four To retrieve elements of a multidimensional array. and save it as multiArray1. 3. 2."two"). The first [] refers to the index of the toplevel array. The next example shows you how. trace(twoDArray). Comment out the trace statement. i < gridSize. You see the following display in the Output panel. 2. Subsequent array access operators refer to elements of nested arrays. i++) { mainArr[i] = new Array(gridSize). This array. You see the following display in the Output panel. "four")). var i:Number. Return to the authoring tool and open the Actions panel.fla.two. as shown below: // trace(twoDArray). Create a new Flash document. To create a multidimensional array using a for loop: 1.

j++) { trace(mainArr[i][j]).for (j = 0. i++) { mainArr[i] = new Array(gridSize). j < innerArrayLength.[2][2] You can also use nested for loops to iterate through the elements of a multidimensional array. for (j = 0.[1][1]. Add the following ActionScript to Frame 1 of the Timeline: // from previous example var gridSize:Number = 3. This ActionScript creates a 3 x 3 array and sets the value of each array node to its index. for (i = 0. Then you trace the array (mainArr). 3. j++) { mainArr[i][j] = "[" + i + "][" + j + "]". } } trace(mainArr). j < gridSize. following the code you entered in step 2: // iterate through elements var outerArrayLength:Number = mainArr.[2][1]. The inner loop iterates through each nested array and outputs each array node.length. i++) { var innerArrayLength:Number = mainArr[i]. var i:Number. as shown in the next example. j++) { mainArr[i][j] = "[" + i + "][" + j + "]". j < gridSize. Create a new Flash document. You use the length property of each array as the loop condition. seen in the previous example.[1][2]. for (j = 0. About arrays 171 . and save it as multiArray3.[1][0]. Add the following ActionScript to Frame 1 of the Timeline. i < gridSize.[2][0]. 2. Select Control > Test Movie to test the code.[0][1]. } } In this code.fla. var mainArr:Array = new Array(gridSize). 3. } } This ActionScript iterates through the elements of the array. for (i = 0. the outer loop iterates through each element of mainArray.[0][2]. You see the following display in the Output panel: [0][0]. i < outerArrayLength. To use a for loop to iterate a multidimensional array: 1. var j:Number.length.

When you create code to find a value that’s associated with a key. a contact book might be considered an associative array. see “Using arrays” on page 164. That value can be a data type such as Number. 172 Syntax and Language Fundamentals . Creating associative arrays An associative array. Select Control > Test Movie to view the elements that are displayed in the Output panel. Array. if you had an array of names and ages that you needed to refer to a lot. which is like an object. The following example demonstrates how to create an object and define a series of properties in an associative array. NO T E When you use associative arrays. you can call the array element you need using a string rather than a number.4. Your code should not expect the keys of an associative array to be in a specific order. This is what you will probably use associative arrays for most often. which is often easier to remember. and so on. see “About adding and removing elements” on page 168. is made of unordered keys and values. They are useful when you need to look up by key values frequently. Object. You will see the following in the Output panel: [0][0] [0][1] [0][2] [1][0] [1][1] [1][2] [2][0] [2][1] [2][2] For information on using arrays. For information on the array access operator. For information on array elements. Each key is a unique string. For example. and it is associated with and used to access one value. To create a simple associative array: 1. where the names are the keys and email addresses are the values Associative arrays are unordered collections of key and value pairs. Associative arrays use keys instead of a numeric index to organize stored values. see “Using dot and array access operators” on page 184. The association between a key and value is commonly referred to as its binding. The downside is that these arrays aren't as useful in a loop because they do not use numbers as the index value. you are indexing or performing a lookup. Create a new Flash document. the key and value are mapped to each other. For example. you might use an associative array.

There are two ways to create associative arrays in ActionScript 2.myColor) and array syntax (someObj[‘myColor’]). someObj. you define a series of properties in someObj. Following this.myH = 360. var someObj:Object = new Object(). Finally. NO TE You can access variables in an associative array using two different methods: dot syntax (someObj.myColor = 0xDFDFDF. An instance of the Object class.myW = 480.0: ■ ■ Use an Object constructor Use an Array constructor Both of these ways are demonstrated in upcoming examples.myAlpha = 72. when it’s more convenient to have string keys rather than numerical indices. Each property name of the generic object serves as the key that provides access to a stored value. // 72 trace(someObj["myAlpha"]). someObj. You might use associative arrays for dictionary-like functionality. N OT E If you use the Object constructor to create an associative array. // Define a series of properties.myAlpha). you can take advantage of initializing your array with an object literal.2. For more information on classes.myX = 100. someObj.myY = 200. someObj. // 72 The first line of ActionScript defines a new object (someObj) that you use as the associative array. see Chapter 7. someObj. Select Control > Test Movie to test your ActionScript. For more information on literals. Object instances are essentially associative arrays.” on page 225. // Display a property using dot operator and array access syntax. 3. trace(someObj. someObj. is functionally identical to an associative array. see “About literals” on page 130. which represents both of the alpha levels that you traced. “Classes. someObj. In fact. The Output panel displays the number 72 twice. also called a generic object. Type the following ActionScript on Frame 1 of the Timeline: // Define the object to use as an associative array.myShape = "Rectangle". The previous example used an Object constructor to create an associative array. About arrays 173 . you display a property that you select using both dot operator and array access syntax.

as demonstrated in this code. " + monitorInfo["resolution"]). This is possible with the bracket operator.colors).7 million". monitorInfo. and uses an object literal to initialize the array with two key/value pairs. The code you just typed adds two new values to monitorInfo array. Add the following ActionScript to Frame 1 of the Timeline: var monitorInfo:Object = {type:"Flat Panel". " + monitorInfo. 5. For more information on well-formatted code. 1600 x 1200 4. following the code you entered previously: monitorInfo["aspectRatio"] = "16:10". trace(monitorInfo["aspectRatio"] + ".fla. but generates an error if you attempt this with the dot operator. For more information on bracket operators and dot operators. Select Control > Test Movie.To create an associative array using an Object constructor: 1. you can use the Object constructor to create the array: NO T E var monitorInfo:Object = new Object(). This code creates an associative array called monitorInfo. 16. The Output panel displays the following text: 16:10. If you do not need to initialize the array at declaration time. 2. see “About operators” on page 176. see “Formatting ActionScript syntax” on page 764. Add the following ActionScript to Frame 1 of the Timeline. 3. After you use using either an object literal or the Object class constructor to create the array. 174 Syntax and Language Fundamentals .7 million Note that a key can contain a space character. resolution:"1600 x 1200"}.colors = "16. Using spaces in your key names is not recommended. trace(monitorInfo["type"] + ".). and save it as assocArray. you can add new values to the array using either the bracket operator ([]) or the dot operator (. Select Control > Test Movie. Create a new Flash document. The Output panel displays the following text: Flat Panel.

you should use the Object class instead of an associative array. To create an associative array using the Array constructor: 1. and there is no advantage of creating associative arrays using the Array constructor. you cannot use any of the Array class’s methods and properties (such as sort() or length) when using an associative array. This code creates an associative array named monitorInfo using the Array constructor and adds a key called type and a key called resolution. 3. The Output panel displays the following text: Flat Panel. About arrays 175 . Select Control > Test Movie. There is no advantage to using the Array constructor to create an associative array.) to add key and value pairs to the array. Add the following ActionScript to Frame 1 of the Timeline: var monitorInfo:Array = new monitorInfo["type"] = "Flat monitorInfo["resolution"] = trace(monitorInfo["type"] + Array(). If you declare your associative array to be of type Array. 1600 x 1200 There is no advantage to using the Array constructor to create an associative array. " + monitorInfo["resolution"]). NO T E Associative arrays are essentially instances of the Object class. and save it as assocArray2. The Array constructor is best for creating indexed arrays. ".fla. "1600 x 1200". Even though you create an associative array using the new Array() constructor. The Array constructor is best for creating indexed arrays. Create a new Flash document. If you want to use key/ value pairs instead of a numeric index. along with their values. Panel". N OT E The next example demonstrates how to use the Array constructor to create an associative array. 2.The second way to create an associative array is to use the Array constructor and then use either the bracket operator ([]) or the dot operator (. you cannot use an object literal to initialize the array.

operator precedence. For example. and they are any legal combination of ActionScript symbols that represent a value. you can use the addition (+) operator to add values of a numeric literal. operator precedence. For information on every operator. An operand is the part of your code that the operator performs actions on. myNum and 3 are operands. see the ActionScript 2. For more information on expressions. a mathematical expression uses numerical operators to manipulate the values you use.About operators This section describes general rules about common types of operators. or you can call a function. This section describes how to use each type of operator. Operators are characters that specify how to combine. An expression consists of operators and operands. including special operators that don’t fall into the following categories. <. myNum + 3. or change values in an expression. An expression is any statement that Flash can evaluate and that returns a value. compare. You can combine operators and values to create an expression. You could do this to add the value of a variable called myNum. Examples of operator characters are +. N OT E ■ ■ ■ ■ ■ ■ The parts of your code that the operator performs actions on are called operands.0 Language Reference. *. For example. in the expression x + 2. statements. and expressions” on page 114. see “About syntax. however. there isn't space to cover each one. This section describes general rules about common types of operators. and =. and operator associativity. x and 2 are operands and + is an operator. For example. You can create an expression by combining operators and values or by calling a function. You use expressions and operators frequently throughout your code. and operator associativity: “Using operators to manipulate values” on page 177 “About operator precedence and associativity” on page 179 “About using operators with strings” on page 182 “Using dot and array access operators” on page 184 “About postfix operators” on page 186 “About unary operators” on page 186 176 Syntax and Language Fundamentals . In this example.

For more information on using many operators in a single code sample. For example. About operators 177 . you might want to create a game in Flash where the score changes depending on the user’s interaction with instances on the Stage.■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ “About multiplicative operators” on page 187 “About additive operators” on page 187 “Using numeric operators” on page 188 “About relational operators” on page 189 “About equality operators” on page 189 “Using relational and equality operators” on page 190 “About assignment operators” on page 193 “Using assignment operators” on page 194 “About logical operators” on page 194 “Using logical operators” on page 195 “About bitwise shift operators” on page 196 “About bitwise logical operators” on page 197 “Using bitwise operators” on page 197 “About the conditional operator” on page 199 “Using operators in a document” on page 199 For information on operators. see the ActionScript 2. see “Using operators in a document” on page 199. You can use a variable to hold the value and operators to manipulate the value of the variable. The following example demonstrates how to use the + (addition) and += (addition assignment) operators to add and increment values in your code. which contains information about all the operators you can use. For example.0 Language Reference. that do not fall into these categories. The following sections show you some common uses for operators. Using operators to manipulate values Operators are commonly used to manipulate values in Flash. you might want to increase the value of a variable called myScore.

In the first code example. It relies on the increment operator instead. // 4 3. Open the Actions panel (Window > Actions) and type the following code into the Script pane: // example one var myScore:Number = 0. myNum++. // 1 // example two var secondScore:Number = 1. You can see an example of the increment operator in the following ActionScript: var myNum:Number = 0. 178 Syntax and Language Fundamentals . because it handles an increment and assignment simultaneously. 2. You can rewrite the line myScore = myScore + 1 (from the previous exercise) as myScore++ or even myScore += 1. Create a new Flash document. trace(myNum). secondScore += 3.To manipulate values using operators: 1. The second code example uses the addition assignment operator to add and assign a new value in a single step. and then stores the result into the variable myScore. trace("Example two: " + secondScore). // 1 myNum++. Select Control > Test Movie. because it adds two values together. myScore = myScore + 1. it adds the current value of myScore and the number 1. trace("Example one: " + myScore). The increment operator (++) is a simplified way of saying myScore = myScore + 1. The Output panel displays the following text: Example one: 1 Example two: 4 The addition operator is fairly straightforward. trace(myNum). // 2 Notice that the previous code snippet doesn’t have assignment operators.

There is a table that outlines this hierarchy at the end of this section. see “About statements” on page 141. For example. You can control what happens by enclosing expressions in parentheses. } The Output panel displays the numbers 1 through 9. ActionScript has a hierarchy that determines which operators execute before others. ActionScript defines a default operator precedence that you can alter using the parentheses (()) operator. Such instructions are collectively referred to as operator precedence. // 18 Now the output of this statement is 18. which is i incrementing in value until it reaches the end condition (i is equal to 10). For more information on conditions and loops. 4 * 3 is evaluated first and the result is added to 2. About operator precedence and associativity When you use two or more operators in a statement. While that is true. trace(mySum). Therefore. you increment i one number higher using i++. because multiplication has a higher operator precedence. Although it may seem natural to those familiar with arithmetic or basic programming that the compiler processes the multiplication (*) operator before the addition (+) operator. var i:Number. mySum = (2 + 4) * 3. ActionScript performs the addition first: var mySum:Number. The last value displayed is 9. You can see an example of operator precedence when you work with the multiplication and addition operators: var mySum:Number. trace(mySum). i < 10. In the following code. and 9 after the trace completes. when it stops. you can use the increment operator (++) to increment the variable i while the condition is true. Therefore. for (i = 1.You can manipulate the value of a variable using operators while a condition is true. mySum = 2 + 4 * 3. About operators 179 . the value of i is 1 when the SWF file starts playing. the condition is true while i is less than the value of 10. some operators take precedence over other operators. Operator precedence and associativity determine the order in which operators are processed. // 14 You see the output of this statement is 14. i++) { trace(i). When you put parentheses around the addition expression. the compiler needs explicit instructions about which operators to process first.

// false trace((3 > 2) < 1). If both operators are used in the same expression. which results in a value of true because the operand 3 is greater than the operand 2. Consider the order of operands in your ActionScript. All of the binary operators. the compiler uses the rules of associativity to determine which operator to process first. For example. see “About the conditional operator” on page 199. mySum = 2 * 4 * 3. so the following two statements are the same. if you know that i will be greater than 50 in your condition. it’s checked first. which have the same precedence. the associativity determines the order in which the operators perform. var myOtherSum:Number. The value true is then passed to the less than (<) operator. var mySum:Number. trace(mySum). For more information on the conditional (?:) operator. 180 Syntax and Language Fundamentals . The assignment operators and the conditional (?:) operator are rightassociative. For more information on assignment operators. It has left-to-right associativity. which means that the operators on the right are processed before operators on the left. This means that the following two statements produce the same output: trace(3 > 2 < 1). myOtherSum = (2 * 4) * 3. Therefore. The less than (<) operator converts the value true to the numeric value 1 and compares that numeric value to the second operand 1 to return the value false (the value 1 is not less than 1). You can either have left-to-right associativity or right-to-left associativity. In these cases. and the second condition that you write doesn’t need to be checked as often. which means that operators on the left are processed before operators on the right. except the assignment operators. you need to write i<50 first. see “Using assignment operators” on page 194. For example. the operator on the left is processed first because both operators are left-associative. // 24 You might encounter situations in which two or more operators of the same precedence appear in the same expression. consider the less than (<) and greater than (>) operators. // 24 trace(myOtherSum). // false The greater than (>) operator is processed first. In this case. particularly when you set up complex conditions and you know how often one of those conditions is true. are left-associative. Take a look at the multiplication operator again.It’s also possible for operators to have the same precedence. along with the operand 1.

from highest to lowest precedence.” on page 764. [ ] ( ) function ( ) ++x --x ~ ! new delete typeof void * / % + << >> >>> instanceof Associativity Post-increment Post-decrement Object property access Array element Parentheses Function call Pre-increment Pre-decrement Unary negation.The following table lists all the ActionScript operators and their associativity. such as x = -1 Bitwise NOT Logical NOT Allocate object Deallocate object Type of object Returns undefined value Multiply Divide Modulo Unary plus Unary minus Bitwise left shift Bitwise right shift Bitwise right shift (unsigned) Instance of (finds the class of which the object is an instance) Requires Flash Player 6 or later Less than Left to right Left to right Left to right Left to right Left to right Left to right Right to left Right to left Left to right Right to left Right to left Right to left Right to left Right to left Right to left Left to right Left to right Left to right Right to left Right to left Left to right Left to right Left to right Left to right < Left to right About operators 181 . “Formatting ActionScript syntax. see Chapter 19. For more information and guidelines on using operators and parentheses. Operator Description Highest precedence x++ x-.

Comparison operators compare strings to determine which is first alphabetically. >=. If only one operand is a string. An exception to this rule is the strict equality (===) operator. =.Operator <= > >= == != & ^ | && || ?: = *=. Strings with uppercase characters precede strings that are lowercase. trace(c < e). ^=.sort()). // false var riddleArr:Array = new Array(c. >>=. see “Using numeric operators” on page 188. +=. >>>= . comparison operators (>.chicken 182 Syntax and Language Fundamentals . %=. /=. and <=) affect strings differently than when they operate on other values. trace(riddleArr).Egg trace(riddleArr. var c:String = "chicken". <. &=. // chicken. e). <<=. That means that "Egg" comes before "chicken". ActionScript converts both operands to numbers and performs a numeric comparison on them. Description Less than or equal to Greater than Greater than or equal to Equal Not equal Bitwise AND Bitwise XOR Bitwise OR Logical AND Logical OR Conditional Assignment Compound assignment Associativity Left to right Left to right Left to right Left to right Left to right Left to right Left to right Left to right Left to right Left to right Right to left Right to left Right to left Comma Left to right Lowest precedence About using operators with strings Comparison operators compare strings only if both operands are strings. Except for the equality operator (==). For more information on numeric operators. |=. var e:String = "Egg". // Egg.

0. this. If one of the operands is a string. About operators 183 . myTxt. trace("The variable is " + myNum + ". 20). the Output panel displays the following: The variable is 10. For example. var myNum:Number = 10. 10 large eggplants. myTxt. In the following ActionScript code. var e:String = "Egg". myTxt. 11. you might concatenate two strings from different variables in a single text field. the trace statement uses the + operator to concatenate instead of add. You can see that the value “Egg” comes before the value “chicken” because uppercase E comes before a lowercase c. trace(c. NO T E You can use operators to manipulate strings. both strings convert to lowercase strings and compare. When you test this code. the operators do not compare the values if one operand is a numerical value. you need to convert the strings to uppercase or lowercase before you compare them. You might have already used the addition operator to concatenate strings when you write trace statements. Lots of vegetable broth."). In the previous example.". see “About equality operators” on page 189 and “Using relational and equality operators” on page 190. You can use the addition (+) operator to concatenate string operands. and now the chicken comes before the egg: var c:String = "chicken". 100. You can use the toLowerCase() or toUpperCase() methods to convert strings to a similar case before you compare them. the variable myNum concatenates with a string. you might write the following: var myNum:Number = 10.toLowerCase()). For example. For more information on comparison operators. // true Comparison operators compare only two strings. " + myNum + " large eggplants. Flash sometimes concatenates instead of adding numerically. When you deal with strings and numbers.createTextField("myTxt".toLowerCase() < e. the sort() method of the Array class reorders the contents of the array alphabetically. For example. In the following example.autoSize = "left".text = "One carrot. 0. and the string is displayed in the myTxt text field on the Stage.text += " Lots of vegetable broth. This code outputs the following in a text field with the instance name myTxt: One carrot.In this ActionScript. If you want to compare the strings regardless of case. ActionScript converts both operands to numbers and then compares them numerically.".

If only one of the text string operands is actually a string. For example. The array access operator lets you dynamically set and retrieve instance names and variables. ActionScript treats spaces at the beginning or end of a string as a literal part of the string. Type in an instance name of myClip. create a movie clip on the main Timeline. Flash converts the other operand into a string.day = 9.. the value of myNum converts to a string in the previous example. as demonstrated in the following ActionScript: var someUser:Object = {name:"Hal". To use dot and array access operators: 1. and the fourth line of code uses the addition assignment operator to concatenate a string onto the existing value of the text field. The dot operator takes an identifier as its property.text = "My text". year. 3. Therefore.The previous example shows how you can use the addition (+) and addition assignment (+=) operators to concatenate strings.) and the array access operator ([]) to access built-in or custom ActionScript properties. 184 Syntax and Language Fundamentals . id:2001}.border = true. In a new Flash document. if you have an object that contains some user information. you can use a for. You use dot operators to target certain indexes in an object. you can specify a certain key name in the array access operator to retrieve a user’s name.in loop to iterate through an object or movie clip and display its contents. 2. The array access operator is useful if you don’t know exactly what keys are in an object. the following ActionScript uses the dot operator to set certain properties within objects: myTextField. Notice how the third line of code uses the addition operator to concatenate the value of the myNum variable into the text field.month. The dot operator and the array access operator are very similar. // User's id is: 2001 For example. but the array access operator evaluates the contents to a name and then accesses the value of that named property. myTextField. N OT E Using dot and array access operators You can use the dot operator (. Select the movie clip and open the Property inspector. When this occurs. // User's name is: Hal trace("User's id is: " + someUser["id"]). trace("User's name is: " + someUser["name"]).

About operators 185 . 6.0. because you don’t have to specifically target each instance. The Output panel displays 10. You save time. In ActionScript 2. You can also use the array access operator on the left side of an assignment. you can use the bracket operator to access properties on an object that are created dynamically. trace(myClip. nestedClip2. see “Creating multidimensional arrays” on page 169. the Property inspector to add the following instance names to each of the four new instances: nestedClip1. variable. as demonstrated in this ActionScript. You can also create multidimensional arrays using this operator. nestedClip3. 12. The Output panel displays 5.spam). This ActionScript toggles the visibility of each of the nested movie clips. // 5 If you want to set a value in the myClip instance on the current timeline you can use the dot or array access operators. Add the following code to Frame 1 of the main Timeline: var i:Number. Use 11. 5. If you write an expression inside the array access operator.4._visible = false. 9. for (i = 1. Select Control > Test Movie to test the document. For more information on creating multidimensional arrays using array access operators.spam = 5. Select Control > Test Movie to test the document. 10. 7. } 8. it evaluates that expression first and uses the result as the variable name. You’re using the array access operator to iterate over each nested movie clip in the myClip instance and set its visible property dynamically. and replace the first line of ActionScript with the following: myClip["spam"] = 10. and double-click the myClip instance. Add four new instances inside the myClip instance. Add the following ActionScript to Frame 1 of the Timeline: myClip. i++) { myClip["nestedClip" + i]. and object names dynamically: myNum[i] = 10. in case the class definition for that object is not given the dynamic attribute. nestedClip4. Now the four nested instances are invisible. Select Control > Test Movie to test the ActionScript you just added. Return to the authoring environment. which lets you set instance. Return to the authoring environment. i <= 4.

see “About unary operators” on page 186. which means that they appear before the operand in an expression. trace(++xNum). // 1 When you trace this code. For information on unary operators. Although these operators are unary operators. the following code shows how the value of the expression xNum++ is returned after the value is incremented.About postfix operators The postfix operators take one operator and either increment or decrement the operator’s value. For information on postfix operators. var xNum:Number = 0. the expression’s value is returned before the postfix operator is processed. trace(xNum++). The prefix operators differ from the postfix counterparts because the increment or decrement operation completes before the value of the overall expression is returned. // 1 trace(xNum). They can also appear after the operand. in which case they are postfix operators. see “About postfix operators” on page 186. the text in the Output panel reads: 0 1 The operators in this table have equal precedence: Operator ++ -- Operation performed Increment (postfix) Decrement (postfix) About unary operators Unary operators take one operand. For example. var xNum:Number = 0. When you use a postfix operator as part of a larger expression. // 1 186 Syntax and Language Fundamentals . The increment (++) and decrement (--) operators in this group are prefix operators. // 0 trace(xNum). the following code shows how the value of the expression xNum++ is returned before the value is incremented. they are classified separately from the rest of the unary operators because of their higher precedence and special behavior. For example.

(negation) Returns type information Returns undefined value About multiplicative operators The multiplicative operators take two operands and perform multiplication. Other numeric operators include multiplicative operators. see “Using numeric operators” on page 188. All of the operators in this table have equal precedence: Operator * / % Operation performed Multiplication Division Modulo For information on using multiplicative operators.All of the operators in this table have equal precedence: Operator ++ -+ ! typeof void Operation performed Increment (prefix) Decrement (prefix) Unary + Unary . see “About multiplicative operators” on page 187. see “Using numeric operators” on page 188. For information on additive operators. division. About additive operators The additive operators take two operands and perform addition or subtraction calculations. About operators 187 . see “About additive operators” on page 187. Other numeric operators include additive operators. The operators in this table have equal precedence: Operator + - Operation performed Addition Subtraction For information on using additive operators. or modulo calculations. For information on multiplicative operators.

if (++firstScore >= 30) { // should trace trace("Success! ++firstScore is >= 30"). see “About operator precedence and associativity” on page 179. commonly formed as i++. 188 Syntax and Language Fundamentals . you need to be very careful when you work with numeric operators. and multiply values in ActionScript. 29 compares against 30. For more information on the increment operator. } 3. FlashVars. The first example uses a preincrement (++firstScore) to increment and calculate firstScore before it’s tested against 30. Create a new Flash document. you need to manually convert the data from strings to numbers using the Number() function. divide.Using numeric operators You use numeric operators to add. you could add 3 and 7 with a result of 37 because both numbers are concatenated like strings instead of adding numerically. However. but the “Example two” code block does not. When you load data from external sources (such as XML files. In this case. and so on). Select Control > Test Movie to test the ActionScript The “Example one” code block traces. firstScore increments to 30 and then tests against 30. subtract. see “Using operators to manipulate values” on page 177. Type the following ActionScript into Frame 1 of the Timeline: // example one var firstScore:Number = 29. Therefore. There are more things you can do with this operator. One of the most common operators is the increment operator. You can add the increment before (preincrement) or after (postincrement) an operand. } // example two var secondScore:Number = 29. You can perform different kinds of arithmetic operations. To understand numeric operators in ActionScript: 1. 2. web services. and then increments to 30 after the evaluation. Example two uses a postincrement (secondScore++). Therefore. if (secondScore++ >= 30) { // shouldn't trace trace("Success! secondScore++ is >= 30"). Sometimes Flash treats the numbers like strings because the SWF file isn’t aware of the number’s data type. In this situation. For more information on operator precedence. which evaluates after the test is performed.

All of the operators in this table have equal precedence: Operator == != === !== Operation performed Equality Inequality Strict equality Strict inequality For information on using equality operators. All of the operators in this table have equal precedence: Operator < > <= >= instanceof in Operation performed Less than Greater than Less than or equal to Greater than or equal to Checks prototype chain Checks for object properties For information on using relational operators.About relational operators The relational operators take two operands. and return a Boolean value. see “Using relational and equality operators” on page 190. compare their values. About equality operators The equality operators take two operands. see “Using relational and equality operators” on page 190. and return a Boolean value. About operators 189 . compare their values.

and they return either true or false (a Boolean value). } When you select Control > Test Movie. if (myNum == 2) { // do something trace("It equals 2").Using relational and equality operators Relational and equality operators. You can use the equality (==) operator to figure out whether the values or references of two operands are equal. The string It equals 2 appears in the Output panel. you use the equality operator (==) to check for equality. You can use the equality operator to compare values. In this example. Type the following ActionScript into Frame 1 of the Timeline: var myNum:Number = 2. compare values of expressions."). you can see how to use the equality operator to test the array’s length and display a message in the Output panel if there are no items in the array. 190 Syntax and Language Fundamentals . Select Control > Test Movie.length == 0) { trace("the array is empty. String. but you cannot use the equality operator to set values. You check whether the variable myNum equals 2. Create a new Flash document. 3. Object and array operands are compared by a reference. 4. and this comparison returns a Boolean value. You might try to use the assignment operator (=) to check for equality. var myArr:Array = new Array(). also called comparison operators. 2. to: var myNum:Number = 4. Return to the authoring environment and change: var myNum:Number = 2. the string the array is empty appears in the Output panel. } In this ActionScript. You frequently use comparison operators in conditional statements and loops to specify the condition for when the loop should stop. number. if (myArr. or Boolean operand values compare using a value. To use relational and equality operators in your code: 1.

Flash sees the variables as two separate values. As a result. // true trace(num1 === num2). In this case. For more information on correctly using the assignment operator. Flash tries to convert the values to the same data type and then compare the values to see whether they are equal. and num2. instead of comparing myNum to 2. which can cause unexpected results when you test the Flash document. The string It equals 2 doesn’t appear in the Output panel. If two operands are different types. About operators 191 . trace(num1 == num2). the equality operator returns false. If you compare the variables using the equality operator. The strict inequality operator (!==) returns the opposite of the strict equality operator. When you use the strict equality operator (===) Flash doesn’t attempt to do any data type conversion before it compares the values. to if (myNum = 2) { 7. you’ll use the greater than or equal to (>=) operator to compare values and execute code based on the value a user enters into a text field. you assign the value of 2 to myNum. var num2:String = new String("32"). // false First. The string It equals 2 appears in the Output panel again.5. Return to the authoring environment and change: if (myNum == 2) { 6. The strict equality operator (===) is similar to the equality operator. In the following example. the if statement executes regardless of the previous value of myNum. except it doesn’t perform type conversion. you define numeric variables: num1. see “Using assignment operators” on page 194. Select Control > Test Movie again. In step 6. The following ActionScript demonstrates the key difference between the equality operator (==) and the strict equality operator (===): var num1:Number = 32. Select Control > Test Movie again.

To use the greater than or equal to operator in your code: 1. submit_mc. You can also check whether certain conditions are true and execute an alternative block if the condition is not true.endFill().beginFill(0xFF0000). 2. if (isNaN(myNum)) { trace("Please enter a number"). this.text). } 5.moveTo(0. 0.restrict = "0-9". submit_mc. Add the following code to Frame 1 of the main Timeline: this. Select File > New and then select Flash Document to create a new FLA file.onRelease = function(evt_obj:Object):Void { var myNum:Number = Number(myTxt. 100. } }. submit_mc. submit_mc. Change the condition in your ActionScript to the following. submit_mc. 4.lineTo(100. 3. 0)._x = 110. Select Control > Test Movie to test the ActionScript again. 20). submit_mc. myTxt. submit_mc.lineTo(0.border = true.type = "input". return. 0).createTextField("myTxt". 20). 192 Syntax and Language Fundamentals . submit_mc. Select Control > Test Movie to test the ActionScript. myTxt. submit_mc. 20. } else { trace("Your number is not 10"). } else { trace("Your number is less than 10"). 0). 30).lineTo(0.lineTo(100. 20). 0. } if (myNum >= 10) { trace("Your number is greater than or equal to 10").createEmptyMovieClip("submit_mc". myTxt. if (myNum == 10) { trace("Your number is 10").

If only one of the operands is a string. see “About operator precedence and associativity” on page 179. see “About using operators with strings” on page 182. For information on how order and operator precedence affect your ActionScript. About assignment operators The assignment operators take two operands and assign a value to one operand based on the value of the other operand. All of the operators in this table have equal precedence: Operator = *= /= %= += -= <<= >>= >>>= &= ^= |= Operation performed Assignment Multiplication assignment Division assignment Modulo assignment Addition assignment Subtraction assignment Bitwise left shift assignment Bitwise right shift assignment Bitwise unsigned right shift assignment Bitwise AND assignment Bitwise XOR assignment Bitwise OR assignment For information on using assignment operators.Except for the strict equality (===) operator. see “Using assignment operators” on page 194. both operands convert to numbers and perform a numeric comparison. About operators 193 . the comparison operators compare strings only if both operands are strings. For more information on strings and operators.

as follows: var myText:String = "ScratchyCat". When you work with the assignment operator. myNum += 15. both of these statements do the same thing: var myNum:Number = 0. myNum = myNum + 15. For example. as shown in the following code: trace("the sum of 5 + 2 is: " + (5 + 2)). as you can see in the following example: trace("the sum of 5 + 2 is: " + 5 + 2). // the sum of 5 + 2 is: 7 About logical operators You use logical operators to compare Boolean values (true and false) and then return a Boolean value based on the comparison. You can also use the assignment operator to assign several variables in the same expression. These operators perform the operation on both operands. For example. var numOne:Number. you can wrap the expression 5+2 in a pair of parentheses. and then they assign the new value to the first operand. To work around this.Using assignment operators You can use the assignment operator (=) to assign a given value to a variable. You can also use compound assignment operators to combine operations. You might assign a string to a variable. you can have problems if you try to add values in an expression. 194 Syntax and Language Fundamentals . the value of 10 is assigned the variables numOne. Or if one or both of the operands evaluate to true. numTwo. the logical AND (&&) operator returns true. numOne = numTwo = numThree = 10. var numThree:Number. In the following statement. // the sum of 5 + 2 is: 52 Flash concatenates the values 5 and 2 instead of adding them. and numThree. var numTwo:Number. the logical OR (||) operator returns true. The logical operators take two operands and return a Boolean result. if you have two operands that evaluate to true. see “Using logical operators” on page 195. The logical operators differ in precedence and are listed in the table in order of decreasing precedence: Operator && || Operation performed Logical AND Logical OR For information on using logical operators.

To use logical operators in your code: 1.lineTo(100. submit_mc. 20. 20).createTextField("myTxt". Open the Actions panel and type the following ActionScript on Frame 1 of the Timeline: this. submit_mc. This is demonstrated by the next example.createEmptyMovieClip("submit_mc". myTxt. The message depends on the value of the number you type into the text field. 0. submit_mc. this. Flash uses the logical operator to display a message in the Output panel. 20). In this ActionScript. 100. submit_mc.moveTo(0.lineTo(0. } }._x = 110. myTxt.endFill(). 0). 0).type = "input".lineTo(100. 2. About operators 195 . Select File > New and create a new Flash document. } else { trace("Your number is NOT between 10 and 20"). you create a text field at runtime.Using logical operators You often use logical operators with comparison operators to determine the condition of an if statement.restrict = "0-9". myTxt.border = true.text). submit_mc.beginFill(0xFF0000). if (isNaN(myNum)) { trace("Please enter a number"). return. 30).lineTo(0. If you type a number into the text field and click the button on the Stage.onRelease = function():Void { var myNum:Number = Number(myTxt. 0. submit_mc. submit_mc. submit_mc. submit_mc. } if ((myNum > 10) && (myNum < 20)) { trace("Your number is between 10 and 20"). 20). 0).

For specific information on each bitwise operator. If the number is less than 10 or greater than 20. About bitwise shift operators The bitwise shift operators take two operands and shift the bits of the first operand to the extent specified by the second operand. an alternate message is displayed in the Output panel. } }. if (isNaN(myNum)) { trace("Please enter a number"). } if ((myNum > 10) && (myNum < 20)) { trace("Your number is between 10 and 20"). see “Using bitwise operators” on page 197. All of the operators in this table have equal precedence: Operator << >> >>> Operation performed Bitwise left shift Bitwise right shift Bitwise unsigned right shift For information on using bitwise operators. 196 Syntax and Language Fundamentals .text). submit_mc. see its entry in the ActionScript 2. } else { trace("Your number is NOT between 10 and 20").onRelease = function():Void { var myNum:Number = Number(myTxt. Based on the result. return.When you use operands. This is particularly the case when you use complex conditions.0 Language Reference. you can see how you use the logical AND operator to check that a number is between 10 and 20. you display an appropriate message. you need to be careful of the order. In the following snippet.

"bill". "Dan". 2.sort(Array. Using bitwise operators in Flash isn’t very common. To use the bitwise OR operator: 1. Array.CASEINSENSITIVE | Array. The exact operation performed depends on the operator. // Bob.Dan.tom myArr. For a list of bitwise shift operators. you might want to build a permissions matrix for a Flash project. but can be useful in some circumstances. see “About bitwise logical operators” on page 197. For example.bill. The bitwise logical operators differ in precedence and are listed in the table in order of decreasing precedence: Operator & ^ | Operation performed Bitwise AND Bitwise XOR Bitwise OR For information on using bitwise operators. you might use bitwise operators. but you don’t want to create separate variables for each type of permission. see “Using bitwise operators” on page 197. "tom").DESCENDING).Hank. "Hank". Select File > New and create a new Flash document.Dan. For specific information on each bitwise operator. but all bitwise operations evaluate each binary digit (bit) of the 32-bit integer individually to compute a new value. trace(myArr). // tom.bill About operators 197 . "doug".doug. For a list of bitwise logical operators. In this case.Bob.0 Language Reference.doug. see “About bitwise shift operators” on page 196. see its entry in the ActionScript 2. Using bitwise operators Bitwise operators internally manipulate floating-point numbers to change them into 32-bit integers. trace(myArr).Hank.About bitwise logical operators The bitwise logical operators take two operands and perform bit-level logical operations.sort() The following example shows how you can use the bitwise OR operator with the method to specify sort options. Type the following ActionScript into the Actions panel: var myArr:Array = new Array("Bob".

CASEINSENSITIVE equals the numeric value of 1.40 var flags:Number = Array.1. The following text is displayed in the Output panel: Bob.DECENDING has a numeric value of 2 or a binary value of 10.base2) trace(scores. // adding the numbers Although it might not be immediately obvious.DESCENDING.toString(2)).doug. representing 5 in binary is 101.DESCENDING and Array. and so on.DESCENDING. Binary only has two possible values. // 202.20. // 1.CASEINSENSITIVE (binary = 1) 2 or Array. The constant value Array. instead of having a case-sensitive search where Z comes before a. // 10010 (binary -. If you want to display the number 3 in binary.sort(flags)).tom tom. The number 4 represented in binary is 100. The result of the sort method causes the items in the array to be sorted in reverse order (z to a).sort() method and specify two sort options using the constant values Array.CASEINSENSITIVE | Array. a and A are treated the same.198.100.Dan.bill.202. var scores:Array = new Array(100.DESCENDING (binary = 10) 4 or Array.198.NUMERIC|Array. 1 or 0.sort(Array.Hank. // numbers my_array.CASEINSENSITIVE and Array.1 198 Syntax and Language Fundamentals .sort()). The search is caseinsensitive.40.Hank.sort(3).40.198). // constants my_array.202.20.bill There are five options available in the sort method: ■ ■ ■ ■ ■ 1 or Array.Bob. trace(scores).1.RETURNINDEXEDARRAY (binary = 1000) 16 or Array. // 100. it would be 11 (1+10).202. Working with binary numbers can get confusing.NUMERIC constants together. The following ActionScript demonstrates how to sort an array of numeric values in descending order by using the bitwise AND operator to add the Array.40.100.Dan. which also happens to be the binary value of 1. trace(flags).The first line defines an array of random names and traces them to the Output panel.doug. 3.DESCENDING).198 trace(scores.sort(1 | 2).NUMERIC (binary = 10000) There are three different ways you can define the sort options for an array: my_array. the number values for the sort options are actually bitwise digits (binary or base 2).20. Then you call the Array. which is why the value 2 is represented as 10.20. // 18 (base 10) trace(flags.UNIQUESORT (binary = 100) 8 or Array. Select Control > Test Movie to test your ActionScript. The constant value Array.

To use operators in ActionScript: 1.round(correctAnswers / totalQuestions * 100 * 100) / 100. see “About the conditional operator and alternative syntax” on page 152.. After you slightly modify the ActionScript. 2. Using operators in a document In the following example. The user’s score can multiply by a number and display to get a score between 0% and 100%. //round to the nearest integer //var score:Number = Math. Then you use the addition operator to concatenate the user’s score into a string that is displayed in the Output panel. var totalQuestions:Number = 13. //round to two decimal places var score:Number = Math.About the conditional operator The conditional operator is a ternary operator. Type the following ActionScript on Frame 1 of the main Timeline: var correctAnswers:Number = 11. Create a new Flash document. you can make Flash round numbers to a certain number of decimal places instead. you also use the division and multiplication operators to calculate a user’s score based on the number of correct answers divided by the total number of questions that are asked. trace("You got " + correctAnswers + " out of " + totalQuestions + " answers correct. About operators 199 . for a score of " + score + "%.round(correctAnswers / totalQuestions * 100). you use the Math.else conditional statement: Operator ?: Operation performed Conditional For information on using the conditional operator and an example. and then returns the value.round() method to round calculations to an arbitrary number of decimal places. In the next example."). The conditional operator is a short-hand method of applying the if. which means that it take three operands. This method rounds the value of the x parameter up or down to the nearest integer.

the score rounds to the nearest integer (85) and is displayed in the Output panel. before you call Math. 4. If you multiply the number by an additional 100. This results in a more accurate score.round(). for a score of 84. you can make Flash round the number to 2 decimal places. Try changing the correctAnswers variable to 3 and select Control > Test Movie to test the SWF file again. and then divide by 100. The Output panel displays the following text: You got 11 out of 13 answers correct. you might want to create a series of true/false or multiple choice questions using the RadioButton and Label components. When you call Math.3.62%. After users finish answering each of the questions and click the submit button. Select Control > Test Movie. you can compare their answers to an answer key and then calculate their score. 200 Syntax and Language Fundamentals . If you are building a testing application.round() in this example.

Methods are merely functions that are located within an ActionScript class definition. as well as exercises in which you write and use functions and methods in Flash. . . . “Classes. . . In this chapter. . . . . . . . . . . . 201 . . . . animations. . . . . . . . . 201 Understanding methods . This chapter covers the kinds of functions that you can write in your Flash applications. Your functions can also return values. and other effects to your applications. . . . and how to write them. . . You can use functions in your code to add interactivity. . . . .222 6 About functions and methods Methods and functions are blocks of ActionScript code that you can reuse anywhere in a SWF file. . .” you’ll create custom classes in which you’ll write functions regularly.CHAPTER 6 Functions and Methods Understanding functions is important when you’re writing ActionScript. . . . . . . . . . you learn about functions and methods: how to use them in your applications when you use built-in classes. . . . . . In Chapter 7. and using methods. . . You’ll also learn how to write functions in ActionScript class files. . . . . . You can define functions to execute a series of statements on passed values. You might write your functions in the FLA file or in an external ActionScript file and then call the function from anywhere within your documents. . . . . . . . . . . After a function is defined. . see the following topics: About functions and methods . . . . . including a timeline of a loaded SWF file. . . creating classes. . .There are several different kinds of functions that you’ll work with. . . . . . . . . . . . . . it can be called from any timeline. For information on what functions and methods are. . .

function traceMe(favSoftware:String. I like " + favSoftware + ". yourMessage. you could use the following code: var yourName:String = "Ester". the function can perform calculations using the supplied values. This can cause errors during runtime. } traceMe(). output. Each function has individual characteristics. For information on writing named functions. is: function traceMe(yourMessage:String) { trace(yourMessage).yourName.yourAge). a person using the function does not need to understand exactly how it works internally. yourAge:String) { trace("I'm " + yourName + ". the function assigns the undefined data type to the empty parameters. see “Writing named functions” on page 207. Alternatively. the function ignores the extra values.If you pass values as parameters to a function. and some functions require that you pass certain types or numbers of values. that function’s definition must be in a frame that the playhead has reached. var yourAge:String = "65". Functions and Methods . N OT E 202 You can think of a well-written function as a “black box. if you want to pass multiple parameters. If you pass more parameters than the function requires. yourName:String. The basic syntax for a simple named function that builds on the previous example by passing a parameter. To call a function. var favSoftware:String = "Flash". If you don’t pass a required parameter. and purpose."). } traceMe("How you doing?"). } traceMe(favSoftware. A function can also return values (see “Returning values from functions” on page 220). The basic syntax for a simple named function is: function traceMe() { trace("your message"). and I'm " + yourAge + ".” If the function contains carefully placed comments about its input.

For information on writing code using Script Assist. and accessor methods (getters and setters). In the following example. and function literals. as well as links to sections on writing specific kinds of functions. see “Passing parameters to a function” on page 218. The following sections contain information on how to define these functions. callback functions.For more information on passing parameters. For information on writing class files. class methods. constructor functions. such as the following. including built-in functions. named and userdefined functions. “Creating a startDrag/stopDrag event using Script Assist” on page 331 and the ActionScript:Use Script Assist Mode tutorial (which begins with “Open the starter document” on page 213). anonymous functions. N OT E About functions and methods 203 . You can also write functions in an ActionScript class file. For more information on writing functions. “Classes. the Person class displays a constructor method. The comments in this code sample show where these methods occur in the code. You use these functions as methods in your scripts. For an example that compares methods and functions.” on page 225. see “Using Script Assist to write ActionScript” on page 328. There are several types of functions that you can use in your applications. NO TE ■ For more information about functions and methods. instance methods. There are numerous kinds of functions that you can write. see “About types of methods and functions” on page 203. see Chapter 7. see “Understanding methods” on page 222. see the following topics: “About types of methods and functions” on page 203 About types of methods and functions Functions that belong to a class are called the methods of that class.

// instance members private var _speed:Number. this._speed = 0. Examples of functions that are built in to the top level of the ActionScript language are trace() and setInterval(). see Chapter 7._speed = speed. } // getters/setters (accessor methods) public function get speed():Number { return this.class Person { public static var numPeople:Number = 0. } public function rest():Void { this. “Classes. The methods that you use in your code might belong to a class that is built into the ActionScript language._speed = speed. they are functions written in the built-in class (similar to the previous code sample). you could use methods from a custom class that you wrote yourself. Alternatively. } // instance methods public function walk(speed:Number):Void { this.numPeople++. } public function run():Void { this. } } For a full demonstration of how to write methods like the ones in the previous code sample. MovieClip and Math are examples of top-level classes that you might use in an application. Functions that don’t belong to a class are called top-level functions (sometimes called predefined or built-in functions). } // static methods public static function getPeople():Number { return Person.” on page 225._speed.numPeople. // constructor public function Person(speed:Number) { Person. 204 Functions and Methods . When you use methods from these classes in your code. meaning that you can call them without a constructor._speed *= 2.

“Creating a startDrag/stopDrag event using Script Assist” on page 331 and the ActionScript:Use Script Assist Mode tutorial (which begins with “Open the starter document” on page 213). A function can also return values. NO T E ■ ■ ■ ■ ■ ■ You can also define functions in numerous other ways. For more information on each kind of function. see the following related sections. you omit the parentheses after the method name because you’re passing a reference to the function: my_mc. see “About built-in and top-level functions” on page 205. a function is a block of ActionScript code that can be reused anywhere in a SWF file. NO T E About built-in and top-level functions As discussed in “About functions and methods” on page 201. see “Using Script Assist to write ActionScript” on page 328. see “Using functions in Flash” on page 214. see the following sections: “About built-in and top-level functions” on page 205 “Writing named functions” on page 207 “Writing anonymous and callback functions” on page 208 “About function literals” on page 211 “Targeting and calling user-defined functions” on page 213 “About constructor functions” on page 211 For information on writing and using functions and methods. For more information on top-level functions. However. For information on writing code using Script Assist. the top-level trace() function is called. and text appears in the Output panel. Remember: when you want to assign a method to a property. If you pass values as parameters to a function. For example. For information on using methods. For information on using functions.myMethod(). When you test the SWF file with this single line of code. the function operates on those values.To add a top-level function call to your code.myMethod = aFunction. when you want to invoke a method in your code. type the following: trace("my message"). just add a single line of code in the Script pane of the Actions panel. see “Understanding methods” on page 222. About functions and methods 205 . you need to include the parentheses following the method name: my_mc.

Calling a top-level function is like calling a user-defined function. For information on each function. N OT E 206 Top-level functions are easy to use. When you test the SWF file. To call a function. or the function might be in a built-in class. see “Targeting and calling user-defined functions” on page 213. You use built-in functions in ActionScript to perform certain tasks and to access information. which you use as a method in your application. Some built-in functions require you to pass certain values. 100). which can cause errors during runtime. the extra values are ignored. add the following ActionScript to Frame 1 of the Timeline: trace("my message"). as described in “About types of methods and functions” on page 203. To call a function. This code creates a simple timer using getTimer(). Functions that don’t belong to an object are called top-level functions and are found in subcategories of the Global Functions category of the Actions panel. that function’s definition must be in a frame that the playhead has reached. For more information. Add the following code to Frame 1 of the Timeline: function myTimer():Void { trace(getTimer()).0 Language Reference.You can use functions that are built into the ActionScript language. If you pass more parameters than the function requires.0 Language Reference). and uses the setInterval() and trace() top-level functions to display the number of milliseconds since the SWF file began to play in Flash Player. For example. the empty parameters are assigned the undefined data type. see the entry for the function in the ActionScript 2. The next example shows how to use both of these functions together. Or you can get the version number of Flash Player that hosts the file by using getVersion(). simply use the function name and pass any parameters required by that function. If you don’t pass a required parameter. They might be top level. such as Math or MovieClip. For example. Two other examples of top-level functions are setInterval() and getTimer(). Functions and Methods . my message appears in the Output panel. you can get the number of milliseconds the SWF file has been playing by using getTimer(). see its entry in ActionScript 2. } var intervalID:Number = setInterval(myTimer. Functions that belong to an object are called methods. (For information on required parameters.

start().onSoundComplete = myMessage. For example. see “Passing parameters to a function” on page 218.Writing named functions A named function is a kind of function that you commonly create in your ActionScript code to carry out all kinds of actions. if a function is defined in Frame 2 of a timeline. To use a named function: 1. 3. All function names in a document must be unique. my_sound. About functions and methods 207 . Parameters are sometimes called arguments. 5. as long as the function has been defined in the current or a previous frame. Right-click the sound file and select Linkage. The // function block comment is a placeholder for where your code for the function block would go.attachSound("mySoundID").fla.” You can put the code that you want to execute here. the named functions are compiled first. The standard format for named functions is as follows: function functionName(parameters) { // function block } This piece of code contains the following parts: ■ functionName is the unique name of the function. When you create a SWF file. For more information on parameters. ■ parameters contains one or more parameters that you pass to the function. 2. Import a short sound file into the library by selecting File > Import > Import to Library and selecting a sound file. Select Frame 1 of the Timeline and add the following code to the Actions panel: function myMessage() { trace("mySoundID completed"). which you use later in the script to call a trace() function. This part contains the statements that “do stuff. Type mySoundID in the Identifier text box. Create a new document called namedFunc. which means that you can reference the function anywhere in your code. my_sound. // function block ■ contains all of the ActionScript code that’s carried out by the function. you cannot access that function in Frame 1 of the timeline. In this code you create a named function called myMessage. my_sound. 4. } var my_sound:Sound = new Sound().

“Classes. see “Writing the constructor function” on page 268. you can reference the function later in your code. Also see Chapter 7. Select Control > Test Movie. //later in code you can add myWidth(). Therefore. including class files. Writing anonymous and callback functions A named function is a function that you reference in your script before or after you define it.6. You can associate an anonymous function with a certain event to create a callback function. the name of the function matches the class). The content between the curly braces ({}) is called the function block. Create a movie clip on the Stage. The next example shows you how to write an anonymous function.” on page 225 for information on and examples of writing functions in classes. 3. To write an anonymous function. }. if you don’t have parameters. such as an XML or LoadVars instance. you reference the anonymous function when you create it. Remember that parameters are optional. You use the function statement to create your own function in ActionScript. and type my_mc into the Instance Name text box. Open the Property inspector. You can write functions on the main timeline or within external ActionScript files. whereas an anonymous function is an unnamed function that references itself. You can also create a function inside an object. you will create many anonymous functions._width). and type the following code into the Actions panel: var myWidth = function () { trace(my_mc. you could store a function literal inside a variable. Select Frame 1 of the Timeline. Select Control > Test Movie to test the SWF file. 208 Functions and Methods . and then select the clip. 2. Anonymous functions are commonly used when you work with event handlers. 4. however. To write an anonymous function: 1. you still need to include the brackets. When you write ActionScript code. A function calls a callback function after a specific event occurs. For more information on constructor functions. such as after something finishes loading (onLoad()) or finishes animating (onMotionFinished()). You also write constructor functions in class files using this format (however. The width of the movie clip is displayed in the Output panel.

such as callback functions). as you can when you use a named function. You can see from the previous code snippet that the onLoad() event handler uses an anonymous function to handle the onLoad() event. If you place the following code on Frame 1. which uses setInterval() to call the anonymous function approximately every 1000 milliseconds (1 second): setInterval(function() {trace("interval"). About functions and methods 209 . sometimes you need to write ActionScript to handle data that loads into a SWF file from the server.load("http://www. 1000).” on page 329. my_xml. suppose that you have anonymous functions on Frame 5 of your FLA file. You can also forward-reference a named function.xml"). as seen in the following code. You could also use anonymous functions with the setInterval() function. as shown in the following example. my_xml.}. }. You cannot reference an anonymous function anywhere in your code (unless you assign it to a variable). After you finish loading data into a SWF file. It's important to use ActionScript to check whether the data has been fully loaded.com/crossdomain.For example. You use XML. such as the following: //with a movie clip called my_mc that spans the timeline stop(). }.helpexamples. in which you load a remote XML document. you associate an anonymous function with the onLoad() event. In the following callback function.load() and the callback function. var myWidth = function () { trace(my_mc. Named functions are often easier to read and understand (except in some circumstances. Type the following code on Frame 1 of the Timeline: var my_xml:XML = new XML(). you can access the data from that location.onLoad = function(success:Boolean):Void { trace(success). “Handling Events. see Chapter 10. You can use named functions instead of anonymous functions. it cannot reference the function: myWidth()._width). For example. For more information on callback functions. which means you reference it before the function exists on a timeline. You can use callback functions to send a signal that the data has been loaded into the document.

For more information. see “Using Script Assist to write ActionScript” on page 328. However. }._width). } // the following does not work because you are calling an anonymous function: myWidth(). the following code placed on any frame does not work: myWidth(). You could also place myWidth() on any frame that is after the frame that contains the myWidth function. }.Similarly. myWidth(). calling it in a frame script works. NO T E 210 NO T E When defining a named function. this code works properly: var myWidth:Function = function () { trace(my_mc. }. even though the equivalent code with an anonymous function does not work: // the following does work because you are calling a named function: myWidth(). For information on writing code using Script Assist. see “Writing named functions” on page 207._width). var myWidth:Function = function () { trace("foo"). Functions and Methods . var myWidth:Function = function () { trace(my_mc. “Creating a startDrag/stopDrag event using Script Assist” on page 331 and the ActionScript:Use Script Assist Mode tutorial (which begins with “Open the starter document” on page 213). function myWidth() { trace("foo").

Also. you use an anonymous function. if you don’t create a function whose name matches that of the class—the compiler automatically creates an empty constructor function for you. For example. overloaded constructor functions are not allowed in ActionScript 2. About constructor functions The constructor of a class is a special function that is called automatically when you create an instance of a class by using the new keyword (such as. etc) { // statements }.About function literals A function literal is an unnamed function that you declare in an expression instead of in a statement. param2. Function literals are useful when you need to use a function temporarily or to use a function in your code where you might use an expression instead. a custom Person class that you create would contain the following constructor function: public function Person(speed:Number) { Person. If you do not explicitly declare a constructor function in your class file—that is. the following code uses a function literal as an expression: var yourName:String = "Ester". When you redefine a function literal.}. To do so. the new function definition replaces the old definition.0. For more information on writing constructor functions in class files. var my_xml:XML = new XML(). this._speed = speed. NO T E N O TE You can store a function literal in a variable to access it later in your code. “Writing the constructor function” on page 268.). 200).numPeople++. see “Writing anonymous and callback functions” on page 208. A class can contain only one constructor function. } Then you could create a new instance by using: var myPerson:Person = new Person(). For more information. The constructor function has the same name as the class that contains it. For example. The syntax for a function literal is: function (param1. About functions and methods 211 . setInterval(function() {trace(yourName). a constructor function cannot have a return type.

For information on writing code using Script Assist. “About variables and scope” on page 96.” on page 225. and the ActionScript statements that indicate what the function does. see “Naming functions” on page 214. You can also define functions in numerous other ways. see “Using Script Assist to write ActionScript” on page 328. precede the function name with the identifier _global.myFunction = function(myNum:Number):Number { return (myNum * 2) + 3. you explored the different kinds of functions that are available in Flash. you can use the _global identifier to declare a global function that is available to all timelines and scopes without using a target path. as shown in the following example: _global. functions are attached to the timeline of the movie clip that defines them. see the following sections: ■ ■ ■ ■ ■ ■ “About built-in and top-level functions” on page 205 “Writing named functions” on page 207 “Writing anonymous and callback functions” on page 208 “About function literals” on page 211 “About constructor functions” on page 211 “Targeting and calling user-defined functions” on page 213 For information on naming functions. “Creating a startDrag/stopDrag event using Script Assist” on page 331 and the ActionScript:Use Script Assist Mode tutorial (which begins with “Open the starter document” on page 213).Defining global and timeline functions In “About functions and methods” on page 201. any parameters to be passed to the function. N OT E 212 Functions and Methods . }. To define a global function. and you must use a target path to call them. see “Using functions in Flash” on page 214 and Chapter 7. As with variables. For more information on each kind of function. } trace(areaOfCircle(8)). The following example is a function named areaOfCircle with the parameter radius: function areaOfCircle(radius:Number):Number { return (Math. “Classes. trace(myFunction(5)) // 13 For information on _global and scope. use the function statement followed by the name of the function. For a detailed example of using functions in an external class file. To define a timeline function.PI * radius * radius). As with variables.

name. About functions and methods 213 . type the target path to the name of the function. see “Passing parameters to a function” on page 218. and callback functions. see “Using functions in Flash” on page 214. helloWorld() You can also define your own named functions. including from a timeline of a loaded SWF file.fla. Create a new Flash document and save it as udf.functionsClip. For more information on parameters. The following code uses a path to call the initialize() function. world! The previous code creates a user-defined function named traceHello() that takes one argument. " + name + "!"). as opposed to functions in built-in classes that perform predefined functions. unnamed. // hello. } traceHello("world"). To call a function. The following example shows you how to use a user-defined function in a FLA file. For information on writing named functions. and for information on using functions. which was defined in the functionsClip movie clip: this. You name the functions yourself and add statements in the function block. if necessary.initialize(). which was defined on the current timeline and requires no parameters: this. The following example uses a relative path to call the list() function. and traces a greeting message. the following named function is user defined: function helloWorld() { trace("Hello world!"). you can call traceHello from the same timeline as the function definition and pass a single string value. Previous sections cover writing functions such as named. You can use a target path to call a function in any timeline from any timeline. and pass any required parameters inside parentheses. see “Writing named functions” on page 207. Add the following ActionScript to Frame 1 of the main Timeline: function traceHello(name:String):Void { trace("hello. 2. There are several forms of syntax for user-defined functions. see “Naming functions” on page 214. }. To call the user-defined function. For information on naming functions.list(6). For example._parent. To create and call a simple user-defined function: 1.Targeting and calling user-defined functions User-defined functions are simply functions that you create yourself to use in applications.

In the context of objectoriented programming (OOP). and “About class members” on page 250. For information on writing functions in class files. see Chapter 7. and the method name cannot start with a number. see “Using functions in Flash” on page 214. Some of the following code examples use ActionScript that resides in the FLA file. if any. as well as the size of your SWF file. “About public. For information on naming methods. For more information and examples on using functions in a class file. One way you can reuse code is by calling a function multiple times instead of creating different code each time. see “Writing named functions” on page 207. and static methods and properties (members)” on page 247. As with variables. Also see the following sections in Chapter 7. see “Naming conventions” on page 732.” on page 225. For detailed information and instruction on how to write functions for a class file. Reusing code lets you create efficient applications and minimizes the ActionScript code that you must write. try to reuse blocks of code whenever possible. Naming functions Function names should start with a lowercase letter. because ActionScript does not permit overloading. For more information on named functions. For example. For more information.3. To reduce the amount of work you have to do. “Classes. Functions can be generic pieces of code. Using functions in Flash This section shows you how to use functions in an application. you might name it getCurrentSong(). Your function names should describe the value the function returns. Select Control > Test Movie to test the Flash document. private. 214 Functions and Methods . “Classes”: “Using methods and properties from a class file” on page 245. you cannot use special characters. see “Example: Writing custom classes” on page 263. you can use the same blocks of code for slightly different purposes in a SWF file. which reduces development time. Establish a standard for grouping similar functions (functions that relate to each other based on functionality). see “Naming methods” on page 224. overloading refers to the ability to make your functions behave differently depending on what data types are passed into them. if the function returns the title of a song. Classes contain many user-defined functions. and other code examples place functions in a class file for comparison.

named) function called helloWorld(). nothing happens. you don’t see the trace statement in the Output panel. This ActionScript defines the (user-defined. you can use named functions and anonymous functions. Select Window > Actions to open the Actions panel. There are several different ways that you can write functions on the main timeline. The following text is displayed in the Output panel: Hello world! For information on passing values (parameters) to a function. }. drag it onto the Stage. or reuse blocks of code. For example.PI * radius * radius). To create and call a function in a FLA file: 1. For example. 2. and use the code that you store in the file. 3. see “Passing parameters to a function” on page 218. The following examples show you how to create functions on a timeline and in a class file. Type the following line of ActionScript code after the function: helloWorld(). such as the workflow for code-based components available in Flash (Window > Common Libraries > Classes). Users can install your component. } trace(myCircle(5)). If you test your SWF file at this time. Create a new Flash document and save it as basicFunction.You can create functions in a FLA file or a class file or write ActionScript code that resides in a code-based component. Type the following ActionScript code into the Script pane: function helloWorld(){ // statements here trace("Hello world!"). you have to call the helloWorld() function. To see the trace statement.fla. 5. you can use the following syntax when you create functions: function myCircle(radius:Number):Number { return (Math. TI P The following example shows you how to create and call a function in a FLA file. Select Control > Test Movie to test the FLA file. 4. distribute. Most notably. you can easily share. This code calls the helloWorld() function. About functions and methods 215 . By packing your code into class files or code-based components.

The following example also puts functions in a class file.random() * (max .floor(Math. } public function perimeter(radius:Number):Number { return (2 * Math. You can also place functions in class files when you use ActionScript 2. 2)).length == 0) { 216 Functions and Methods .PI * radius). because it lets you reuse your code easily in several applications. This is a good practice to adopt when you create large applications by using ActionScript 2.” on page 225. } public static function arrayMin(num_array:Array):Number { if (num_array. “Classes. var myCircle:Function = function(radius:Number):Number { // function block here return (Math.min + 1)) + min).pow(radius.as. Create a new ActionScript document and save it as Utils. Type the following ActionScript into the Script pane: class Utils { public static function randomRange(min:Number. you can import the existing class rather than rewrite the code from scratch or duplicate the functions in the new application. }.0. 2. To create functions in a class file: 1. } return (Math.0. As you can see in the previous code sample. trace(myCircle(5)).PI * radius * radius). } public function diameter(radius:Number):Number { return (radius * 2).Anonymous functions are often more difficult to read. } } For more information on writing functions in a class file. When you want to reuse the functions in other applications.PI * Math. min = max. as the following example shows: class Circle { public function area(radius:Number):Number { return (Math. max:Number):Number { if (min > max) { var temp:Number = min. max = temp. Compare the following code to the preceding code. you don’t need to place functions on a timeline. see Chapter 7.

} num_array. Create a new Flash document and save it as classFunctions. } } 3. trace("min: " + min). N OT E About functions and methods 217 .pop()).NUMERIC | Array.return Number. Select Window > Actions to open the Actions panel. 3. 1. 4.pop()). } public static function arrayMax(num_array:Array):Number { if (num_array.fla in the same directory as Utils. var min:Number = Utils. 6. var max:Number = Utils.arrayMin([3.arrayMax([3. // 34 7. 2. The following text is displayed in the Output panel: month: 7 min: -3 max: 34 For information on writing code using Script Assist. 5. 1. var min:Number = Number(num_array. “Creating a startDrag/stopDrag event using Script Assist” on page 331 and the ActionScript:Use Script Assist Mode tutorial (which begins with “Open the starter document” on page 213).randomRange(0.as. 1.NUMERIC). return min. Type the following ActionScript into the Script pane: var randomMonth:Number = Utils. 11). 2. Select Control > Test Movie to test the documents. 5.sort(Array. Select File > Save to save the ActionScript file. see “Using Script Assist to write ActionScript” on page 328. 1. -3]). return max.sort(Array. 34. // -3 trace("max: " + max). var max:Number = Number(num_array. trace("month: " + randomMonth).length == 0) { return undefined.DESCENDING). 3.NaN. 34. -3]). 5. } num_array.

if you modify regular variables. } 218 Functions and Methods .) You can pass parameters (values) to a function. For more information on variables and data. function traceMe(yourFavSoftware:String. You can then use these parameters for processing the function. var myAge:String = "65". The following function called myFunc() takes the parameter someText: function myFunc(someText:String):Void { trace(someText). You use the values within the function block (statements within the function). However. Select Control > Test Movie to test the Flash document. the terms parameter and argument are interchangeable. it is good practice to use script comments to document these modifications. see “Passing parameters to a function” on page 218. which may cause unexpected results in your SWF file. myName. yourName:String. and I'm " + yourAge + "."). If you do not pass enough parameters to a function. Flash also treats any parameters passed to a function as local variables. } traceMe(myFavSoftware.Using variables in functions Local variables are valuable tools for organizing code and making it easy to understand. “Data and Data Types. (In this book. 2. myAge). For more information on passing parameters.” on page 71 Passing parameters to a function Parameters. var myFavSoftware:String = "Flash". Flash sets the missing parameter values to undefined.fla. When a function uses local variables. local variables are invoked in the scope of the body of the function and cease to exist when the function exits. see Chapter 4. 3. You might even have some required and some optional parameters in a single function. Add the following ActionScript to Frame 1 of the main Timeline: var myName:String = "Ester". You can also use regular variables in a function. N OT E To use variables in functions: 1. are the elements on which a function executes its code. I like " + yourFavSoftware + ". yourAge:String) { trace("I'm " + yourName + ". Sometimes parameters are required. Create a new Flash document and save it as flashvariables. also referred to as arguments. and sometimes they are optional. it can hide its variables from all other scripts in the SWF file.

if any parameters are missing. right:Number. 3). left:Number. Flash sets their value to undefined.fla. bottom:Number):Void To pass a parameter to a function: 1. The first few lines of code create a user-defined function called traceMe(). top:Number. Many built-in functions in the ActionScript language have multiple parameters. right. } traceMe("How are you doing?"). 2. When you call the function. and bottom: startDrag(lockCenter:Boolean. 3. you should always pass the specified number of parameters unless your function checks for undefined values and sets default values accordingly. the startDrag() method of the MovieClip class takes five parameters. which can be as simple as the following: var birthday:Date = new Date(1901. width and height. 2. left. For example. About functions and methods 219 . 2. trace(birthday). top. The last line of code calls the traceMe() function and passes the string value “How are you doing?”. Create a new Flash document and save it as functionTest. height:Number):Number { return width * height. as follows: myFunc("This is what traces").After passing the parameter. you can pass a value to the function when you call the function. Add the following code to Frame 1 of the main Timeline: function getArea(width:Number. The function substitutes the passed values for the parameters in the function definition. Add the following code to Frame 1 of the Timeline: function traceMe(yourMessage:String):Void { trace(yourMessage). which takes a single parameter. You regularly pass parameters into functions when you write ActionScript code. Create a new Flash document and save it as parameters. Select Control > Test Movie to test the Flash document. To pass multiple parameters to a function: 1. } The getArea() function takes two parameters.fla. This value traces in the Output panel. You can also pass multiple parameters to a function. Each parameter is separated by a comma delimiter. lockCenter. The next example demonstrates how to pass multiple parameters to a function. yourMessage.

} trace(addNumbers(1. c:Number):Number { return (a + b + c). respectively. Add the following code to Frame 1 of the main Timeline: function addNumbers(a:Number. The return statement returns the result of an evaluation as a value of the function in which an expression executes. trace(area). You see 120 in the Output panel. c equals undefined trace(addNumbers(1. 2. b:Number.3. 4. they exist while the function is called and cease to exist when the function exits. 6. In the next example. 11. Select Control > Test Movie to test the SWF file. 3. 6)). 8)). The return statement returns its result immediately to the calling code. For more information. If you pass too many parameters. Create a new Flash document and save it as functionTest2. 4. 4)). Then you trace the values that you save in the area instance. // 120 The getArea() function call assigns the values 10 and 12 to the width and height. To pass a variable number of parameters to a function: 1. the excess parameters are ignored. 4. 12). NaN. // 11 If you don’t pass enough parameters to the addNumbers function. and you save the return value in the area instance. // 11 trace(addNumbers(1. // NaN (Not a Number). Returning values from functions You use the return statement to return values from functions. Select Control > Test Movie to test the Flash document. Flash displays the following values: 11. Type the following code after the function: var area:Number = getArea(10. 220 Functions and Methods .0 Language Reference. The return statement specifies the value that is returned by a function. see return statement in the ActionScript 2. the ActionScript returns the value NaN (not a number) if you don’t pass enough parameters to the addNumbers() function.fla. The parameters in the getArea() function are similar to values in a local variable. the missing arguments are assigned a default value of undefined.

4. they exist while the function is called and cease to exist when the function exits. including a return statement is optional. ■ ■ ■ For example. 12). To return a value and capture it in a variable: 1. it must not be followed by any value. Select Control > Test Movie to test the SWF file. The next example returns the processed value. Type the following code after the function: var area:Number = getArea(10. Regardless of the return type. Then you trace the values that you save in the area instance. The parameters in the getArea() function are similar to values in a local variable. 3. and then you can use that variable within your application. you can use a return statement to exit from the middle of a function.fla. width and height. and you save the return value in the area instance. you do not need to include a return statement. you must include a return statement and it must be followed by the returned value in the function. If you don’t specify a return type. Add the following code to Frame 1 of the main Timeline: function getArea(width:Number. } Some functions perform a series of tasks without returning a value. height:Number):Number { return width * height. If you specify a return type of Void. Create a new Flash document and save it as return. respectively. } The getArea() function takes two parameters. 2. but if you do. trace(area). You are capturing that value in a variable.The following rules govern how to use the return statement in functions: ■ If you specify a return type other than Void for a function. About functions and methods 221 . the following function returns the square of the parameter myNum and specifies that the returned value must be a Number data type: function sqr(myNum:Number):Number { return myNum * myNum. You see 120 in the Output panel. // 120 The getArea() function call assigns the values 10 and 12 to the width and height.

The class could be a custom class or built-in classes that are part of the ActionScript language. userArr. age:2}).". Understanding methods Methods are functions that are associated with a class. var i:Number. For example. Type the following code on Frame 1 of the Timeline: var myStr:String = "My marshmallow chicken is yellow.firstname).push({firstname:"Socks". trace("Original string: " + myStr). This lets you nest functions so that you can have them perform specific tasks in Flash. Create a new Flash document and save it as methods.push({firstname:"Dan". The formatText() and changeString() functions are both applied to the string when you call the formatText() function. } function changeString(newtext:String):Void { myStr = newtext.fla.sortOn("firstname"). To use the sortOn() method in a FLA file: 1.").push({firstname:"George". For information on comparing methods to functions. see “About functions and methods” on page 201 and “About types of methods and functions” on page 203. } // Call the function. userArr. 2. sortOn() is a built-in method associated with the Array class (sortOn is a function of the predefined Array class built into Flash). i < userArrayLenth. age:43}). Add the following code to Frame 1 of the Timeline: var userArr:Array = new Array(). formatText(). userArr. userArr. you can nest functions on a timeline to perform specific tasks on a string. age:39}). trace("Changed string: " + myStr). var userArrayLenth:Number = userArr.length. i++) { trace(userArr[i]. function formatText():Void { changeString("Put chicken in microwave. For example. } 222 Functions and Methods . for (i = 0. Select Control > Test Movie to test the nested function.About nested functions You can call a function from inside another function.

myHabits. To compare methods and functions: 1.fla. 3. Save your changes to EatingHabits. for example. Select Control > Test Movie to test the SWF file. Type the following ActionScript code onto Frame 1 of the Timeline: var myHabits:EatingHabits = new EatingHabits().eatCabbage().as. The array is populated by three objects that contain a first name and age. and save this file in the same directory as EatingHabits. 4. and save it as EatingHabits. Create a new ActionScript file. Create a new Flash document. function eatCabbage() { trace("tastes bad"). } } 3. and then the array is sorted based on the value of each object’s firstname property. 2. This code displays the following in the Output panel: Dan George Socks As demonstrated in “Writing named functions” on page 207. } eatCabbage(). 5. Understanding methods 223 . call eatCabbage() in the FLA file.as. The next examples show you how to create methods within a class.as. select File > Save As. then eatCabbage() is considered to be a method.You use the sortOn() method of the Array class to create a new Array object named userArr. Finally. select File > Save As. Type the following ActionScript code in the Script window: class EatingHabits { public function eatCabbage():Void { trace("tastes bad"). However. name it methodTest. you loop over each item in the array and display the first name in the Output panel and sort the names alphabetically by first letter. your ActionScript code defines a function called eatCabbage(). when you write the following code on Frame 1 of the Timeline. if you write the eatCabbage() function within a class file and.

When you use methods of any built-in class (in addition to the custom class you wrote earlier in this procedure). Select Control > Test Movie to test the SWF file. singLoud(). see “Naming conventions” on page 732. boogie(). you cannot use special characters. you write and call the eatCarrots() function. You use verbs for most method names because methods perform an operation on an object. you are using a method on a timeline. Naming methods You should use verbs to name methods. and words with mixed cases for concatenated words. you are calling the eatCabbage() method of the EatingHabits class. and the method name cannot start with a number. For example. After the previous line of ActionScript. 7. you might name methods in the following ways: sing(). danceFast().When you use this ActionScript. 224 Functions and Methods . } eatCarrots(). In this code. making sure that the first letter is lowercase. As with variables. For more information. add the following code: function eatCarrots():Void { trace("tastes good"). N OT E 6.

“Best Practices and Coding Conventions for ActionScript 2. and also feel comfortable reading other people’s class files. The rest of the chapter shows you how to create your own custom classes and how to use them within your Flash documents. This chapter begins by explaining some fundamental terminology and how it relates to classes and object-oriented programming (OOP). If you’re not familiar with ActionScript 2. Classes are the backbone of ActionScript 2.0. By the end of this chapter. and are more important than they were in earlier versions of Macromedia Flash.0.0.CHAPTER 7 Classes This chapter introduces you to using and writing classes using ActionScript 2.” on page 731. see Chapter 5. 7 225 . You will learn how important classes are in Flash throughout this chapter. You learn about the Flash classpath and how a class should be documented so that other people who read or use your code can easily understand the code and the class’s overall purpose. you should be able to write a typical class file.” on page 113 and Chapter 19. understand and recognize Flash classes.0. “Syntax and Language Fundamentals.0 scripting. This section contains code examples that you can use to become familiar with creating classes in ActionScript 2. Next you walk through a sample class file and understand how each section of the class file works and how the class is organized.

Classes are also considered like data types or templates that you can create to define a new type of object. . . . . . . . . . . . . . . . . . . . . . . . . . . . This defines the Lettuce object. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . For example. . . . . . . . . . . . you have an instantiation of the class. . . . . . . . . . . . . . . . . . . . . . . . . . . A class defines all of the properties that distinguish a series of objects. . . . . . . and that instance has all of the properties of the User class. . . . For example. . is one of the individual users—one of its members. .263 Example: Using custom class files in Flash. . . You can create an external script file in the Flash authoring tool by selecting File > New and then selecting ActionScript File. . Then. . . . . . . . OOP languages are based on the concept of classes and instances. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . a User class represents a bunch of users who are using your application. To define a class. . you use the class keyword in an external script file. .279 Compiling and exporting classes . The instantiation produces an instance of the User class. . . . . . . . . . . . . . . . . . . . . . 280 Understanding classes and scope . . . for the User class. . . . . . . . . . . .226 Writing custom class files . . .235 About working with custom classes in an application . .238 Example: Writing custom classes . . . . . . . . . Like ActionScript. . . . . . . . . which. . . . . . . . . . . . . . . . . . . . . . . . . .0 is an object-oriented language. . . . .For more information on working with custom and built-in classes. . if you need a data type of Lettuce in your application. . . . . . . . . . . . . . . .296 About object-oriented programming and Flash ActionScript 2. . . . . . . . . . . .286 About working with built-in classes . . . . . . . . and then you can assign your Lettuce methods (wash()) and properties (leafy or bugs). . . . . see the following topics: About object-oriented programming and Flash . . . . . . . . . you might write the Lettuce class. . . . . . . . . . . . . . . . . . . . . . . . . . . 226 Classes . . . . 276 Assigning a class to symbols in Flash . . . . . . . . . . . . . . . . . . . . . .283 About top-level and built-in classes . . . . . . . . . . . . .

About object-oriented programming and Flash 227 .Flash Player 8. “About class members” on page 250 in this chapter shows you how to make a custom Person class that contains custom properties for the person’s name and age. You write a custom class in an external ActionScript (AS) file and you can import it into your application when you compile the FLA file. Date. The programming language lets you build program structures that are reusable. adds several new features to the ActionScript language such as filter effects.0 provides several powerful and familiar OOP concepts and keywords (such as class. You can also write your own custom classes and integrate them into your Flash documents or even extend the top-level classes and add your own functionality or modify existing functionality. and so on). such as Java. ActionScript 2. raw binary data. Classes can be very useful when you build larger Flash applications because you can organize a lot of the application’s complexity in external class files. scalable. and more). A class describes the properties (data) and methods (behaviors) for an object. You can use ActionScript 2. to custom errors and events. see the following topics: ■ ■ ■ ■ “The benefits of using classes” on page 227 “About packages” on page 228 “About values and data types” on page 231 “Object-oriented programming fundamentals” on page 231 The benefits of using classes In OOP. This helps you prevent people from accessing sensitive information or changing data that shouldn’t be changed. Boolean. and the External API. images. Flash Basic 8 and Flash Professional 8 include approximately 65 top-level and built-in classes that provide everything from basic. For example. You can then treat this custom class as a new data type in your documents and create a new instance of the class using the new operator. and maintainable. and package) found in other programming languages. For more information on working with OOP. It can also decrease development time by providing users with thorough coding assistance and debugging information. robust. or “primitive. you can not only make the code easier to reuse. You learn how to create classes and use custom classes in this chapter.0 to create objects and establish inheritance and to create custom classes and extend the Flash top-level and built-in classes. a class defines a category of object. When you move a lot of the logic into a custom class. much like an architectural blueprint describes the characteristics of a building. interface. as well as several ways to load external content (XML. file upload and download. As always.” data types (Array. available in both Flash Basic 8 and Flash Professional 8. but you can also “hide” some of the methods and properties from other parts of the ActionScript code.

as: class Square {} // In Circle. and each subsequent character can be a letter. A package is a directory that contains one or more class files and that resides in a designated classpath directory (see “About importing class files” on page 239 and “About setting and modifying the classpath” on page 240). the first character can be a letter. and Triangle. Circle. For more information on naming packages. Square. Another benefit of using classes is code reusability. you could save the progress bar class in your classpath and reuse the same code in all of your Flash documents by importing the custom class. Assume that you’ve saved the ActionScript files to a directory specified in the classpath. you can also extend existing classes and add new functionality or modify existing functionality.as.as. A package can. package names must be identifiers. you can write a base class and then write two other classes that extend the base class. underscore. see “Naming packages” on page 741. or dollar sign. if you create three very similar classes. so that you don’t need to create three class files that all duplicate the same code and logic. as shown in the following example: // In Square. contain other packages.When you use a class. Circle. For example. For more information on setting the classpath. underscore (_). For example. which for example recommend that you avoid using underscores or dollar sign characters. if you create a custom class that creates a custom progress bar using the Drawing application programming interface (API). Like variables. called subpackages.as: class Triangle {} 228 Classes . that are defined in Square.as. that is.as: class Circle {} // In Triangle. number. For example. There are preferred ways to name packages. About packages When you are creating classes. and Triangle. each with its own class files. Packages are commonly used to organize related classes. in turn. you organize your ActionScript class files in packages. see “About importing class files” on page 239 and “About setting and modifying the classpath” on page 240. you might have three related classes. or dollar sign ($). These two classes can add additional methods and properties.

You might place related custom class files within a single directory. such as the top-level Math class. A class describes the properties (data) and behaviors (methods) for an object.as.as: class Shapes. The relationship between an instance and its class is similar to the relationship between a house and its blueprints. For example. To use the properties and methods defined by a class. a class defines a category of object.Because these three class files are related. as follows: // In Shapes/Square.as: class Shapes.Circle {} // In Shapes/Triangle.as. and WoodWidget. and “Static methods and properties” on page 249).as: class Shapes. For more information. you generally first create an instance of that class (except for classes that have all static members (see “About class (static) members” on page 298. Classes are essentially data types that you can create if you want to define a new type of object in your application. In this case. A comparison of classes and packages In OOP. For more information on packages. you can either specify its fully qualified class name or import the package by using the import statement. as well as the simple class name. you might have three related classes called SteelWidget. where each dot indicates a subdirectory. much like an architectural blueprint describes the characteristics of a building. PlasticWidget.) syntax. the fully qualified class name would contain the package path. The properties (variables defined within a class) and methods of a class are collectively called the class’s members. Package paths are denoted with dot (.as. you would need to change the name of each class file to reflect the new location. and WoodWidget that are defined in SteelWidget. if you placed each ActionScript file that defines a shape in the Shapes directory. About object-oriented programming and Flash 229 . you might decide to put them in a package (directory) called Shapes.Triangle {} To reference a class that resides in a package directory. For example. You would organize these classes in the Widget package.Square {} // In Shapes/Circle. Packages in Flash are directories that contain one or more class files and reside in a designated file path. see “Working with packages” on page 230 and “Creating and packaging your class files” on page 266. see “Working with packages” on page 230. PlasticWidget.

DropShadowFilter.BlurFilter(10. 10. To use the import statement. if you import it. For example.filters package Classes . and so on) in Flash 8. import flash.GlowFilter. If you were importing several classes within a package (such as the BlurFilter.BlurFilter = new flash.filters. // imports each class within flash. The following ActionScript shows an example of using a wildcard import: import flash.*.0 and Flash Player 6 or later in the Flash tab of your FLA file’s Publish Settings dialog box. import flash.filters.filters.filters.filters. lets you access the BlurFilter using only the class name instead of always having to use the fully qualified name. you must specify ActionScript 2. and GlowFilter) you could use one of two methods of importing each class. The second method of importing classes within a package is to use a wildcard import that imports all classes within a certain level of a package.filters package is a directory on your hard disk that contains several class files for each filter type (such as BevelFilter.filters. var myBlur:BlurFilter = new BlurFilter(10. Using individual import statements for each class within a package can quickly become very time consuming and prone to typing mistakes. 3).BlurFilter. If you don’t import the BlurFilter class. you must refer to it by its fully qualified name (flash.BlurFilter. N OT E 230 The import statement lets you access classes without specifying their fully qualified names. For example. your code needs to use the fully qualified class name (package name followed by class name) in order to use the filter: // without importing var myBlur:flash. The first method of importing multiple classes is to import each class using a separate import statement. 3).BlurFilter) or import it. BlurFilter. written with an import statement. if you want to use the BlurFilter class in a script. as seen in the following snippet: import flash. you can refer to it by its class name (BlurFilter). 10.DropShadowFilter.filters.Working with packages Packages are directories that contain one or more class files and reside in a designated classpath directory. The following ActionScript code demonstrates the differences between using the import statement and using fully qualified class names.filters. The same code. the flash. This can save typing and reduce the chance of making typing mistakes: // with importing import flash. DropShadowFilter.

“Data and Data Types. These principles are described in more depth in the rest of this chapter. For more information. you will examine some of the terminology used throughout this chapter before you start writing ActionScript code. You learned about data and types in Chapter 4. suppose on Frame 1 of a Flash document you import all the classes in the macr.transitions package. and String. such as the following example: var myNum:Number = 10. When you work with classes. it’s also important to note that classes are imported only for the level specified. the class isn't exported as part of the SWF file. Type compatibility means the type of a value is compatible with the type that is in use. if you imported all classes in the mx.transitions. only those classes within the /transitions/ directory are imported. you can reference classes in that package by their class names instead of their fully qualified names. The values that you can set and get to and from a property in your class must be compatible with that property. you would need to reference classes in that package by their fully qualified names or add an import statement to the other frame that imports the classes in that package. About object-oriented programming and Flash 231 .util package. If you wanted to use the class name on another frame script. For more information on strict data typing. This means you can import large packages without being concerned about the size of the SWF file. see “About data types” on page 72. If you import a class but don't use it in your script. however. When using import statements. values. such as Boolean. TIP About values and data types Data. while values and properties have types.” on page 71. remember that data types describe the kind of information a variable or ActionScript element can contain.The import statement applies only to the current script (frame or object) in which it’s called. This brief introduction to principles involved in developing object-oriented programs helps you follow the examples and sections within this chapter and the rest of this book. the bytecode associated with a class is included in a SWF file only if that class is actually used. Expressions have values. For example. Object-oriented programming fundamentals In the following sections. For example. along with details on how they are implemented in Flash 8.easing package). On that frame. and types are important when you start writing classes and using them. see “About assigning data types and strict data typing” on page 81. not all classes within subdirectories (such as the classes in the mx. Number.

In the world of OOP. a cat also has behaviors such as sleeping. and color) are called properties of the class and are represented as variables. see “About class members” on page 250 and “Using class members” on page 254. objects also have properties and behaviors. For more information on instances and class members. In OOP terminology. all cats are members of the same category. A cat could be said to have properties (or states). the behaviors (play. The characteristics (in the cat example. eating. the name. and names. sleep) are called methods of the class and are represented as functions. the subclass then inherits all the properties and methods of the class. Inheritance One of the primary benefits of OOP is that you can create subclasses of (or extend) a class. Objects Think of a real-world object. see “Object data type” on page 78. age. Subclasses can also override (provide their own definitions for) methods defined in a superclass. you can model a real-world object (such as a cat) or a more abstract object (such as a chemical process). Classes . such as a cat. such as name. a class defines a blueprint for a type of object. ages. The characteristics and behaviors that belong to a class are jointly referred to as members of that class. and purring. NO TE 232 For more information on objects. with different ways of eating and purring. age. or in OOP terms. Instances and class members Continuing with the real-world analogy of a cat. demonstrating how cats might compare to OOP concepts. each individual cat is said to be an instance of the Cat class. Likewise in OOP. But despite their individual differences. the same class: the class of cats. The subclass typically defines additional methods and properties or overrides methods or properties defined in the superclass. consider that there are cats of different colors. The word behaviors is used generically here and does not refer to the Behaviors panel in the Flash authoring environment.The following sections use the analogy of a cat. Using object-oriented techniques. and color.

the Siamese class. Any class that implements this interface must provide definitions for those methods. “Inheritance.” on page 313. You might create a Cat class that inherits from another class.0 supports extending only from a single superclass. each of whom is working on a different part (class) of the same application.One of the major benefits of using a superclass/subclass structure is that it is easier to reuse similar code between various classes. About object-oriented programming and Flash 233 . Next you could build several subclasses that inherit from the Animal superclass and add characteristics and behaviors specific to that type of animal. “Inheritance. their parameters. determining how to structure the hierarchy of your classes is an important part of the design process. You can use interfaces to add structure and ease of maintenance to your applications. otherwise.” on page 301. Writing subclasses lets you reuse code. suppose you are working with a team of programmers. see Chapter 9. but not necessarily how those parts are assembled. say. could extend (subclass) the Cat class. you might create a Mammal class that defines certain properties and behaviors common to all mammals. or how the parts work. and their return types. and so on. you agree on a set of methods that the different classes use to communicate. Another subclass. a compiler error results. Because ActionScript 2. see Chapter 8. For more information on inheritance. Using the cat analogy. You could then create a Cat subclass that extends the Mammal class. Make sure you determine this hierarchy before you begin to program. For example. “Interfaces. For more information on interfaces. see Chapter 8. You can also think of an interface as a “programming contract” that you can use to enforce relationships between otherwise unrelated classes. you can simply extend an existing class. an interface is similar to a blueprint of a cat: the blueprint tells you which parts you need. While designing the application. and classes that implement interfaces are required to implement that template of methods. So you create an interface that declares these methods. you can use interfaces as a form of limited multiple inheritance. For example. For example. TIP For more information on inheritance and subclasses. In a complex application.” on page 301. you could build a superclass called Animal. Interfaces Interfaces in OOP can be described as templates of class definitions. Instead of recreating all the code common to both classes. which contains common characteristics and behaviors of all animals.

Polymorphism OOP lets you express differences between individual classes using a technique called polymorphism. You then create Cat. Encapsulation is why ActionScript 2. “Inheritance. it lets the creator of the object change the object’s implementation without requiring any changes to code outside of the object—that is. as long as the programming interface doesn’t change. you would use the superclass implementation. and events (its programming interface). Monkey. for example.” on page 301 and “Using polymorphism in an application” on page 308.0 includes. A programmer should be able to interact with an object by knowing only its properties. For more information on encapsulation. objects are seen as “black boxes” that contain. This approach enables programmers to think at higher levels of abstraction and provides an organizing framework for building complex systems. for example. The subclasses override the play() method from the Mammal class to reflect the habits of those particular kinds of animals. you might start with a class called Mammal that has play() and sleep() methods. so details of the implementation can be made private and invisible to code outside an object. or encapsulate. For more information on polymorphism. 234 Classes . This approach provides some important benefits. Monkey implements the play() method to swing from trees. Because the sleep() functionality is similar among the animals. For example. Cat implements the play() method to pounce at a ball of yarn. see “About using encapsulation” on page 261. member access control.Encapsulation In elegant object-oriented design. subclasses can define specialized implementations of methods inherited from its superclass but cannot access the superclass’s implementation as in other programming languages. and Dog subclasses to extend the Mammal class. without knowing the details of its implementation. In Flash. functionality. Dog implements the play() method to fetch a ball. by which classes can override methods of their superclasses and define specialized implementations of those methods. The code outside the object is forced to interact with the object’s programming interface rather than with the implementation details (which can be hidden in private methods and properties). see Chapter 8. methods.

and following this illustration you create a class. as follows: class UserClass {. You learn how to write a class. such as the one in the following example: public function UserClass(username:String. Add instance variables.} ■ ■ ■ Include any necessary class or interface implementation comments. add information that is pertinent for the entire class or interface. Write the public member variables first. Add your import statements (if applicable). password:String) {. Write the getter/setter methods into the class file. class declaration. You begin by looking at a very simple class. you use the class keyword in an external script file (that is. ■ The class file begins with documentation comments that include a general description of the code as well as author and version information. In these comments. This structure is illustrated below. and how you can modify the class to extend the ways that you can use it with Flash. and follow them with private member variables. Group methods by their functionality. You learn about the parts of a class and how to import them as well as related information about working with custom class files in Flash. The class structure is also pertinent for interface files.Writing custom class files The following example examines the parts of a class file. Write the public class variables first and follow them with private class variables.. ■ The following example looks at a simple ActionScript class named User. Add all your static variables... not by their accessibility or scope. The following example shows the organization of a simple class called UserClass. or interface declaration.} ■ ■ ■ ■ Write your methods. To define a class. Write a package statement. not in a script you are writing in the Actions panel). Add the constructor statement. Writing custom class files 235 .. Organizing methods this way helps improve the readability and clarity of your code.

3.__username = p_username. } } 4.__password = value. Inc. version. copyright information. } public function get password():String { return this. p_password:String) { this. */ class User { // private instance variables private var __username:String. The previous code snippet begins with a standardized documentation comment. author.__password = p_password. } public function set username(value:String):Void { this. Type the following ActionScript code into the Script window: /** User class author: John Doe version: 0.__username = value. Select File > Save As and name the new file User. private var __password:String.as. } public function get username():String { return this. } public function set password(value:String):Void { this. and then click OK. Save your changes to the class file. Select File > New and then select ActionScript File. 2.To create class files: 1.__username.__password. // constructor statement public function User(p_username:String. which specifies the class name. 236 Classes . and a brief description of what the class does. date the class was last modified. This code defines a custom User class that allows you to create new users and specify user login information. this.8 modified: 08/21/2005 copyright: Macromedia.

Select File > New and then select Flash Document. trace("Before:"). which both return strings. You assign the user1 User object a value and define a username of un1 and a password of pw1.username and user1. then you would define a getter function. The remainder of the code in the class defines the getter and setter properties for the private instance variables. The first line of code imports the custom User class into your Flash document.password).username). The trace statements display the modified values that you set using the setter functions. and then select Control > Test Movie to test the files.password = "1wp". var user1:User = new User("un1". Type the following ActionScript into Frame 1 of the Timeline: import User.username = "1nu". but not a setter function. The next two lines use the User class’s setter functions to set new values for the username and password variables.fla.The User class’s constructor statement takes two parameters: p_username and p_password. Save the FLA file. 5. you use these files in an application.password). 7. 8. Writing custom class files 237 . Save the file in the same directory as User. user1. The following two trace statements display the current value of user1. 6. user1. trace("\t password = " + user1. Finally.as. trace("After:"). "pw1"). the ActionScript in the Flash document is also very straightforward. you would delete the username setter function in the User class file.username). If you want to create a read-only property. which are copied into the class’s private instance variables __username and __password. Select File > Save As and name the file user_test. trace("\t username = " + user1. trace("\t username = " + user1. you trace the values for username and password to the Output panel. A single instance of the User class is defined and assigned to a variable named user1. trace("\t password = " + user1. You see the results of the trace statements in the Output panel. In the next examples. Importing the User class lets you use the class as a custom data type. if you want to make sure a user name cannot be changed after it has been defined. For example.password using the User class’s getter functions. // un1 // pw1 // 1nu // 1wp Because the User class you created previously is very basic.

0. For more information on creating an instance of a class. For information on defining and writing a class file. For more information on setting the classpath. ■ On Windows. Save the class file to a designated classpath directory (a location where Flash looks for classes). see “Writing custom class files” on page 235. “Data and Data Types. see “About importing class files” on page 239. XmlMenu. ■ About working with custom classes in an application In “Writing custom class files” on page 235. If you’re not familiar with ActionScript 2. In the following sections. At the minimum. 3.0. see “Creating instances of classes in an example” on page 278. You can find the sample source file. the workflow for creating classes involves the following steps: 1. please read Chapter 4. Create an instance of the class in another script. browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\XML_Menu. “Syntax and Language Fundamentals.” on page 113. or in the same directory as the application’s FLA file. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/XML_Menu. Define a class in an external ActionScript class file. xmlmenu. you created a custom class file. On the Macintosh. see “About setting and modifying the classpath” on page 240. The sample calls the ActionScript XmlMenu() constructor and passes it two parameters: the path to the XML menu file and a reference to the current timeline. For a comparison and more information on importing class files. either in a FLA document or an external script file or by creating a subclass based on the original class.A sample file on your hard disk demonstrates how to create a dynamic menu with XML data and a custom class file. The following sections in this chapter contain code examples that you can use to become familiar with creating classes in ActionScript 2.fla. The rest of the functionality resides in a custom class file. in the Samples folder on your hard disk.” on page 71 and Chapter 5. 238 Classes . you use that class file in an application.as. 2.

xmlmenu. interface.0 Settings). select the Flash tab. ■ Document-level classpath About working with custom classes in an application 239 . Flash has two classpath settings—a global classpath and a document-level classpath: ■ Global classpath is a classpath that’s shared by all Flash documents.For more information on working with custom classes. ■ About importing class files In order to use a class or interface that you’ve defined. browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\XML_Menu. and then click ActionScript 2. Flash must locate the external ActionScript files that contain the class or interface definition so that it can import the file. ■ On Windows. click ActionScript in the Category list. function. The sample calls the ActionScript XmlMenu() constructor and passes it two parameters: the path to the XML menu file and a reference to the current timeline. and then click the Settings button). On the Macintosh. and variable definitions is called the classpath. The list of directories in which Flash searches for class. You set it in the Preferences dialog box (Edit > Preferences (Windows) or Flash > Preferences (Macintosh). see the following topics: ■ ■ ■ ■ ■ ■ ■ ■ ■ “About importing class files” on page 239 “Using a class file in Flash” on page 244 “Using methods and properties from a class file” on page 245 “About class members” on page 250 “About getter and setter methods” on page 255 “How the compiler resolves class references” on page 243 “About dynamic classes” on page 259 “About using encapsulation” on page 261 “About using the this keyword in classes” on page 262 A sample file on your hard disk demonstrates how to create a dynamic menu with XML data and a custom class file. It is set in the Publish Settings dialog box (File > Publish Settings. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/XML_Menu.as. The rest of the functionality resides in a custom class file. You can find the sample source file.fla. is a classpath that you specifically define for a single Flash document. XmlMenu. in the Samples folder on your hard disk.

Flash must locate the external ActionScript files that contain the class or interface definition.as: var fooProp. see #include directive in the ActionScript 2.0 Language Reference. function fooMethod() {} trace("Foo"). // This statement is not permitted in a class definition.display. 240 Classes .as" } // FooDef.display.*. see “About setting and modifying the classpath” on page 240. For more information on classpaths. only property and method definitions can exist in the included ActionScript file: // Foo.When you import class files.as class Foo { #include "FooDef. if you have an include statement inside a class definition. The following rules apply to the include statement: ■ include statements are essentially a copy and paste of the content inside the included ActionScript file. ■ ■ An include statement in a FLA file can only bring in code that is valid inside FLA files. For example. The list of directories in which Flash searches for class and interface definitions is called the classpath. packaged definitions using this syntax: import flash. ■ You import individual. and the same goes for other places that include statements can live.BitmapData. ■ You can import entire packages using the wildcard syntax: import flash. For more information on the include statement. About setting and modifying the classpath In order to use a class or interface that you’ve defined. include statements inside ActionScript class files are relative to the subdirectory that contains the file. You can also include ActionScript code in a Flash document (FLA) file using an include statement. the following rules apply: ■ The import statements can exist in the following locations: ■ ■ ■ Anywhere before the class definition in class files Anywhere in frame or object scripts Anywhere in ActionScript files that you include in an application (using the #include statement).

The order of directories in the dialog box reflects the order in which they are searched. The absolute path is denoted by $(LocalData)/Classes in the Preferences dialog box. you can add absolute directory paths (for example. When you click the Check Syntax button above the Script pane while editing an ActionScript file./my_classes or “. and you set it in the Preferences dialog box (Windows: Edit > Preferences (Windows) or Flash > Preferences (Macintosh). Macintosh: Hard Disk/Users/user/Library/Application Support/Macromedia/Flash 8/ language/Configuration/Classes. select ActionScript from the Category list. N OT E ■ ■ Using a global classpath The global classpath is a classpath that’s shared by all of your Flash documents. Otherwise. The global classpath is a classpath that’s shared by all of your Flash documents. (For more information on packages. You can set the document-level classpath in the Flash document’s Publish Settings dialog box (File > Publish Settings. . Flash uses this classpath to access built-in classes. that is. (You can modify the classpath to include the desired directory path). C:/my_classes) and relative directory paths (for example. ActionScript files aren't associated with FLA files in Edit mode and don't have their own classpath.”).When you create an ActionScript class file. The global classpath applies to external ActionScript files and to FLA files. By default. N O TE About working with custom classes in an application 241 . Subdirectories that you create within a classpath directory are called packages and let you organize your classes. In both cases. the global classpath contains one absolute path and one relative path. The location of the absolute path is shown here: Windows: Hard Disk\Documents and Settings\user\Local Settings\Application Data\Macromedia\Flash 8\language\Configuration\Classes.. and then click ActionScript 2. the class or interface specified in the script. The document-level classpath is a classpath that you specifically define for a single Flash document. Do not delete the absolute global classpath. Flash won’t be able to resolve. select the Flash tab.) Flash has two classpath settings: a global classpath and a document-level classpath. see “Creating and packaging your class files” on page 266. If you accidentally delete this classpath. the compiler looks only in the global classpath. reinstate it by adding $(LocalData)/Classes as a new classpath. To modify the document-level classpath setting. locate. You can modify the global classpath using the Preferences dialog box. and then click the Settings button).0 Settings). you use the Publish Settings dialog box for the FLA file. you need to save the file to one of the directories specified in the classpath or a subdirectory therein.

2. Click the ActionScript in the left column.The relative path portion of the global classpath is denoted by a single dot (. Select the path in the Classpath list. When you create classes. and then click the ActionScript 2. When you create and save a FLA file in a directory. in some cases you might want to store them in a directory that you then add to the list of global classpath directories in the following situations: ■ ■ If you have a set of utility classes that all your projects use If you want to check the syntax of your code (click the Check Syntax button) that’s within the external ActionScript file Creating a directory prevents the loss of custom classes if you ever uninstall and reinstall Flash. Click the Browse to Path button to browse to the directory you want to add. and then click ActionScript 2. Browse to the path that you want to add and click OK. N OT E For information on importing packages. that directory becomes a designated classpath directory. Click the Remove from Path button. 242 Classes . 2. You set the document-level classpath in the Publish Settings dialog box for a particular FLA file (File > Publish Settings. Flash uses this classpath to access built-in classes. 3. You can use the following steps to add a global classpath or edit an existing classpath. 4. Be aware that relative classpaths can point to different directories. especially if the default global classpath directory is deleted and overwritten. The document-level classpath is empty by default.0 Settings). because you would lose any classes that you stored in that directory. Select Edit > Preferences (Windows) or Flash > Preferences (Macintosh) to open the Preferences dialog box.0 Settings button. depending on the location of the document being compiled or published. If you accidentally delete this classpath. then click the Flash tab. Using a document-level classpath The document-level classpath applies only to FLA files.) and points to the current document directory. you can reinstate it by adding $(LocalData)/Classes as a new classpath. To modify the global classpath: 1. To delete a directory from the classpath: 1. Do not delete the absolute global classpath. see “Working with packages” on page 230.

Macintosh: Hard Disk/Users/user/custom classes. To delete a directory from the classpath. when you click the Check Syntax button while editing an ActionScript file. ActionScript files aren’t associated with FLA files in Edit mode and don’t have their own classpath. you would add this path to the list of global classpaths (see “Using a global classpath” on page 241). select the path in the Classpath list. you might create a directory such as the following for your custom classes: ■ ■ Windows: Hard Disk\Documents and Settings\user\custom classes. In Flash Professional. To edit an existing classpath directory. 4. click the Browse to Path button. If Flash doesn’t find the class in that classpath. see “About packages” on page 228. Flash searches the global classpath. If the class is not found in that classpath. If the class is not found in the global classpath. and click OK. To modify the document-level classpath: 1. Click the Flash tab. N OT E NO T E For more information on packages. it first searches the documentlevel classpath specified for that FLA file. About working with custom classes in an application 243 . or if that classpath is empty. Select File > Publish Settings to open the Publish Settings dialog box. browse to the directory you want to add.For example. Then. or if that classpath is empty. it first searches the documentlevel classpath specified for that FLA file. a compiler error occurs. and click the Remove Selected Path (-) button. 3. 2. the compiler looks only in the global classpath. How the compiler resolves class references When Flash attempts to resolve class references in a FLA script. You can either manually type a file path or you can click the Browse to Path button to browse to the directory you want to add to the classpath. If Flash doesn’t find the class in the global classpath. a compiler error occurs. select the path in the Classpath list. Click the Settings button next to the ActionScript Version pop-up menu. it searches the global classpath. When Flash attempts to resolve class references in a FLA script.

Using a class file in Flash To create an instance of an ActionScript class. In some cases. see “Writing the constructor function” on page 268. see “Example: Using custom class files in Flash” on page 276. trace(myArray. Classes . For example. and the name of the property on the right side.) operator to access the value of a property in an instance. you would write the following code to create a new User object: var firstUser:User = new User(). you don’t need to create an instance of a class to use its properties and methods. For more information on class (static) members. firstUser is the instance and username is the property: firstUser. For information on the constructor function. "bananas"). NO T E 244 Use the dot (. which you typically assign to a variable. see “About class (static) members” on page 298 and “Static methods and properties” on page 249. "oranges". in the following statement.length). For example. Type the name of the instance on the left side of the dot. the following code creates a new Array object and then shows its length property: var myArray:Array = new Array("apples". The constructor function always has the same name as the class and returns an instance of the class. if you were using the User class from “Writing custom class files” on page 235.username You can also use the top-level or built-in classes that make up the ActionScript language in a Flash document. use the new operator to invoke the class’s constructor function. For example. // 3 For more information on using custom classes in Flash.

} } Next you could invoke that method in your document. // Invoke the showInfo() method.” on page 201. Instance members are created for each instance of the class. To invoke an instance method or access an instance property. For more information on functions and methods. About working with custom classes in an application 245 . The following example shows you how you would create a method in a class file: class Sample { public function myMethod():Void { trace("myMethod"). Methods are functions that you associate with a class.Using methods and properties from a class file In OOP. In the following example. picture01. they are defined to the prototype of the class when they are initialized in the class definition.showInfo(). img1. see Chapter 6. In contrast. (Class members are also known as static members. “Functions and Methods. you reference an instance of the class.helpexamples. class members are created once per class. members (properties or methods) of a class can be instance members or class members. length is a property of all arrays that specifies the number of elements in the array. an instance of the custom Picture class (available in the following exercise).) Properties are attributes that define an object. For example. invokes the showInfo() method: var img1:Picture = new Picture("http://www.com/flash/images/ image1.jpg"). The next example demonstrates how you can write a custom Picture class to hold various pieces of information about a photo.

Save it as picture_test. public function Picture(src:String) { this. */ class Picture { private var __infoObj:Object. You write your custom Picture class in this document.fla in the same directory as you saved the Picture class file. } public function get src():String { return this.__infoObj = new Object(). Inc.53 modified: 6/24/2005 copyright: Macromedia. } public function set src(value:String):Void { this. Select File > New and then select Flash Document to create a new FLA file.src + "]". Select File > New and then select ActionScript File. } private function toString():String { return "[Picture src=" + this. } public function showInfo():Void { trace(this. Save the document as Picture. Type the following ActionScript code into the Script window: /** Picture class author: John Doe version: 0.src = value. 4. Save the ActionScript file. this.src = src. } } 2.__infoObj. The Picture class is used as a container for an image and its URL.__infoObj. 246 Classes .__infoObj.__infoObj.src.To use the Picture and PictureClass classes in a FLA file: 1. 3.toString()).as and then click OK.

Select Control > Test Movie to test the document.createEmptyMovieClip("img_mc".helpexamples. Type the following ActionScript code into Frame 1 of the Timeline: var picture1:Picture = new Picture("http://www. You can find the sample source file. 6. there are four types of methods and properties that you can create: public methods and properties.loadMovie(picture1.5. These methods and properties define how Flash can access variables. whether the application is small or large. in the Samples folder on your hard disk. For example. public static methods and properties. On the Macintosh.jpg"). Considering this ensures that your code is as secure as possible. xmlmenu. XmlMenu. it is especially important to consider whether a method or property should be private or public. By setting the class property (sometimes referred to as an instance member) to private. if you were building a User class.helpexamples. private.jpg] A sample file on your hard disk demonstrates how to create a dynamic menu with XML data and a custom class file. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/XML_Menu.src). this.com/flash/ images/image1. ■ About public.com/flash/images/image1. 9). you might not want to allow people using the class to be able to change a user’s ID. picture1.showInfo(). 7. you can limit access to the property to code within the class or subclasses of that class. private methods and properties. Save the Flash document. ■ On Windows. The sample calls the ActionScript XmlMenu() constructor and passes it two parameters: the path to the XML menu file and a reference to the current timeline.fla. About working with custom classes in an application 247 . and they allow you to specify what parts of your code can access certain methods or properties. and static methods and properties (members) When you write ActionScript class files in an external script file. browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\XML_Menu. The rest of the functionality resides in a custom class file. and private static methods and properties. img_mc. When you are building class-based applications.as. meaning that no users can change that property directly. The following text is displayed in the Output panel: [Picture src=http://www.

The following Sample class already has a public method named myMethod(): class Sample { private var ID:Number. The this keyword can be used with either the public or private keyword. public function myMethod():Void { trace("myMethod"). For example.ID = 15. you can change it within the Sample class.ID). } } Because the email property is public. a variable or function is public. Use the this keyword if you want to restrict access to a variable or function. Private methods and properties The private keyword specifies that a variable or function is available only to the class that declares or defines it or to subclasses of that class. trace(this.” as you can see in the following sample code: class Sample { private var ID:Number. public var email:String. } } If you want to add a public property. you use the word “public” instead of “private. By default. the this keyword is used primarily for stylistic and readability benefits. Because variables and functions are public by default. or directly within a FLA. public function myMethod():Void { this. as you can see in the following example: class Sample { private var ID:Number.Public methods and properties The public keyword specifies that a variable or function is available to any caller. // 15 trace("myMethod").ID = 15. indicating that the variable exists in the current scope. // 15 trace("myMethod"). } } 248 Classes . and available to any caller.ID). you might want to use the this keyword for consistency in a block of code that also contains private or static variables. trace(this. public function myMethod():Void { this.

The message indicates that the member is private and cannot be accessed. trace("count updated: " + Sample. as you saw earlier in this section when you called the Math. You can access a static class member without creating an instance of the class. also called class members. Some of the top-level ActionScript classes have class members (or static members). not to any instance of the class.count). // 0. you could create a static variable to keep track of how many instances of the class have been created.If you want to add a private property to the previous class.PI property. you don’t create an instance of the class to use those properties and methods.count++. public function Sample() { Sample. as shown in the following code: trace(Math. Static methods and properties The static keyword specifies that a variable or function is created only once per class rather than in every object based on that class. public var email:String. the constructor method traces the total number of Sample class instances that have been defined so far. as demonstrated in the following code: class Sample { public static var count:Number = 0. If you attempt to access the private ID property from outside the Sample class. private var ID:Number.PI / 8). Therefore. you simply use the keyword private before the var keyword. To invoke a class method or access a class property. About working with custom classes in an application 249 . For example.392699081698724 If you type this single line of code in the script pane of the Actions panel. Static members. Static methods and properties can be set in either the public or private scope. not on an instance of the class. } public function myMethod():Void { trace("myMethod"). you get a compiler error and a message in the Output panel. Class members (properties and methods) are accessed or invoked on the class name. you see a result trace in the Output panel. you reference the class name. } } Every time you create a new instance of the Sample class. are assigned to the class. rather than a specific instance of the class. in the previous Sample class example.

sqrt(4). Another type of member is a class member. and you use it for the entire class. the email member variable of the Sample class has an instance member. public var username:String. The following code calls the sqrt() method of the Math class: var squareRoot:Number = Math. see “About class members” on page 250 and “Using class members” on page 254. The rest of the functionality resides in a custom class file. ■ About class members Most of the members (methods and properties) discussed so far in this chapter are of a type called instance members. 20). in the Samples folder on your hard disk. XmlMenu.For example.max(10. you simply call the methods on the Math class itself. ■ On Windows. browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\XML_Menu.as. The sample calls the ActionScript XmlMenu() constructor and passes it two parameters: the path to the XML menu file and a reference to the current timeline. Any variable declared within a class. trace(squareRoot). the Person class has two properties. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/XML_Menu. you don’t create an instance of the Math class. For example. In the following example. For each instance member. is a property of the class. there’s a unique copy of that member in every instance of the class. which determines the larger of two numbers: var largerNumber:Number = Math. Instead. On the Macintosh. respectively: class Person { public var age:Number. // 2 The following code invokes the max() method of the Math class. age and username. } 250 Classes . of type Number and String. To call any of its methods. A sample file on your hard disk demonstrates how to create a dynamic menu with XML data and a custom class file. There is only one copy of a class member.fla. because each person has a different e-mail address. but outside a function. You can find the sample source file. // 20 For more information on creating class members. trace(largerNumber). the top-level Math class consists only of static methods and properties. xmlmenu.

It would be wasteful to store a unique copy of the string "Homo sapiens" for every instance of the class. the following code results in a compiler error because the class method getAge() references the instance variable age: class Person { public var age:Number = 15. public function getInfo():String { // getInfo() method definition } } In the previous code snippet the Person class’s getInfo() method.. you can create a method called getInfo(): class Person { public var age:Number. you could either make the method an instance method or make the variable a class variable. About working with custom classes in an application 251 . The age property would not be a good class member. not instance properties.. */ } } To solve this problem. the species is Homo sapiens.. so this member should be a class member. as shown in the following code: public static function getSpecies():String { return Person. Only properties and methods that are shared by all individuals of the class should be class members. public var username:String. For example. In the Person class example. // . because each person has a different age. Class members are declared with the static keyword. For every Person object. } Static methods can access only static properties. } You can also declare methods of a class to be static. Suppose that you want every class to have a species variable that indicates the proper Latin name for the species that the class represents. you could declare the species class member with the following code: class Person { public static var species:String = "Homo sapiens". /* **Error**: Instance variables cannot be accessed in static functions. any function declared within a class is considered a method of the class. For example.species.Similarly. // . as well as the age and username properties.. are all public instance members. public static function getAge():Number { return age.

html. in a chess game. The sample calls the ActionScript XmlMenu() constructor and passes it two parameters: the path to the XML menu file and a reference to the current timeline. For detailed information on the Singleton design pattern. but global variables are not desirable for most projects. However. Typically. such as Singleton. 252 Classes . in the Samples folder on your hard disk. A sample file on your hard disk demonstrates how to create a dynamic menu with XML data and a custom class file.as. see www. and in a country. A better approach is to make the class manage the single instance of the object itself using class members. see “Static methods and properties” on page 249. you should encapsulate the functionality of this object in a class. there is only one chessboard. Often you encounter situations when you need exactly one object of a particular type in a system. ■ Using the Singleton design pattern A common way to use class members is with the Singleton design pattern. browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\XML_Menu. You can find the sample source file. there is only one capital city. On the Macintosh. ■ On Windows. A design pattern defines a formal approach for structuring your code. The Singleton design pattern makes sure that a class has only one instance and provides a way of globally accessing the instance. The rest of the functionality resides in a custom class file. Using a global variable is one way to do this. Even though there is only one object. where the Singleton instance is created only once.For more information on class members (also called static properties).com/devnet/mx/coldfusion/articles/ design_patterns.macromedia. you might structure a design pattern as a solution for a common programming problem.fla. The following example shows a typical Singleton design pattern usage. xmlmenu. For example. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/XML_Menu. XmlMenu. you might need to manage and access the one instance of that object. There are many established design patterns.

"). 4. Select Control > Test Movie to test the document. 2. */ class Singleton { private static var instance:Singleton = null. About working with custom classes in an application 253 .53 modified: 6/24/2008 copyright: Macromedia. 6. public function trackChanges():Void { trace("tracking changes. Save the Flash document. Save the document as Singleton. } } 3.To use the Singleton design pattern: 1. } return Singleton.instance = new Singleton(). Inc. var s:Singleton = Singleton. Select File > New and then select Flash Document to create a new FLA file. The Singleton object is not created until you need it—that is.getInstance().getInstance(). s.trackChanges().as.as document. // tracking changes. 7.instance. This is typically called lazy creation. Type the following ActionScript code into the Script window: /** Singleton class author: John Doe version: 0. Save the Singleton. and it can help make your code more efficient in many circumstances. Select File > New and then select ActionScript File. } public static function getInstance():Singleton { if (Singleton. // tracking changes. until some other code asks for it by calling the getInstance() method. Singleton.fla in the same directory as you saved the Singleton class file."). 5.trackChanges().instance == null) { trace("creating new Singleton. Type the following ActionScript code into Frame 1 of the Timeline: Singleton. and save it as singleton_test.

For example. static instance counter named widgetCount. suppose you want to keep track of the number of instances that have been created from a particular class. 2. } } The widgetCount variable is declared as static. you’ll create a class called Widget that defines a single. the value of widgetCount increments by 1 and the current value of widgetCount is displayed in the Output panel. Each time the Widget class’s constructor statement is called.as. In the following example. however. 3. Using class members One use of class (static) members is to maintain state information about a class and its instances. avoid creating many classes that have only a small amount of functionality or only a few classes that handle a lot of functionality. An easy way to do this is to use a class property that increments each time a new instance is created. public function Widget() { Widget.fla in the same directory as Widget. Save your file as Widget. which are not beneficial to the application’s performance or to your workflow. it adds 1 to widgetCount and then shows the number of the current instance that’s being created. Both of these scenarios might indicate poor design. and then click OK.as. 4. and save it as widget_test. trace("Creating widget #" + Widget.widgetCount++. because doing so can lead to poorly designed class files. so it initializes to 0 only once.Remember not to use too few or too many class files for your application. Each time a new instance of the class is created. Type the following code into the Script window: class Widget { //Initialize the class variable public static var widgetCount:Number = 0. 254 Classes . Select File > New and then select Flash Document to create a new FLA. To create an instance counter using a class variable: 1. Select File > New and then select ActionScript File.widgetCount). You should always attempt to use class files instead of placing code in other places (such as timelines).

widgetCount is zero (0). They also let you create read-only and write-only properties. type the following code into Frame 1 of the Timeline: // Before you create any instances of the class.5. among other issues. like public members. Even though getter and setter methods are useful. OOP practice discourages direct access to properties within a class.widgetCount). Select Control > Test Movie to test the file. they can make code maintenance more difficult in certain situations. meaning that they are generally a public interface to change private class members. Save the changes to widget_test. you should be careful not to overuse them because. In widget_test.fla. // 1 var widget2:Widget = new Widget(). Also. // 2 var widget3:Widget = new Widget(). Those properties outside the class can have a different name from the property name in the class.widgetCount). Flash displays the following information in the Output panel: Widget count at Creating widget Creating widget Creating widget Widget count at start: 0 # 1 # 2 # 3 end: 3 About getter and setter methods Getter and setter methods are accessor methods. trace("Widget count at start: " + Widget. // 3 trace("Widget count at end: " + Widget. 7.fla. // 0 var widget1:Widget = new Widget(). // Widget. You use getter and setter methods to define a property. About working with custom classes in an application 255 . they provide access to your class implementation. There are some advantages to using getter and setter methods. such as the ability to let you create members with sophisticated functionality that you can access like properties. even though you define them within the class as methods. You access getter and setter methods as properties outside the class. // 3 6.

that would be implemented as shown in the next example. A setter method always takes a parameter and never returns a value. you don’t want a user to modify that counter using code. for example). public function Login(username:String) { this. 2. To use getter and setter methods: 1. For example. Instead of allowing instances of the class to directly access this property (user. Select File > New and then select ActionScript File.When you write classes. In this situation. Type the following code into the Script window: class Login { private var __username:String. the class might have two methods.__username = value. } public function getUserName():String { return this. Creating a getter without a setter is a simple way of making certain variables in your class read-only. you might create a private instance variable and allow a getter method only for the counter variable. and then click OK.userName = "Buster". you are always encouraged to make as many as possible of your instance variables private and add getter and setter methods accordingly.__username. Using getter and setter methods The syntax for getter and setter methods is as follows: ■ ■ A getter method does not take any parameters and always returns a value. imagine a class that contains a property called userName: private var userName:String. } } 256 Classes . getUserName() and setUserName(). which means users are able to retrieve the current value only by using the getter method. Only the constructor statement should increment that variable whenever it’s called. This is because there are several times when you may not want to let users change certain variables within your classes. and they won’t be able to set new values using the setter method. For example. if you have a private static method that tracks the number of instances created for a specific class. } public function setUserName(value:String):Void { this. Classes typically define getter methods that provide read access and setter methods that provide write access to a given property.__username = username.

setUserName("EnriqueI"). 5. Add the following ActionScript to Frame 1 of the main Timeline: var user:Login = new Login("RickyM"). NO T E About working with custom classes in an application 257 . getUserName() returns the current value of userName. you can use implicit getter and setter methods. Select Control > Test Movie to test the file. and save it as login_test. // RickyM // calling setUserName() method user.addProperty() method found in ActionScript 1. Implicit getter and setter methods let you access class properties in a direct manner.0.getUserName()). To define these methods. Select File > New and then select Flash Document to create a new FLA. as shown in the next example. You create methods that get or set the value of a property. 4. and setUserName() sets the value of userName to the string parameter passed to the method. trace(user. use the get and set method attributes. and add the keyword get or set before the method name.as. trace(userName).3. while maintaining good OOP practice. Implicit getter and setter methods are syntactic shorthand for the Object. // EnriqueI 6. As you can see. if you want to use a more concise syntax. Save the ActionScript document as Login. // calling getUserName() method var userName:String = user.getUserName().fla in the same directory as Login. Flash displays the following information in the Output panel: RickyM EnriqueI However.as.

Getter and setter methods cannot have the same names as other properties. Type the following code into the Script window: class Login2 { private var __username:String. trace(user.as. 4. A setter method can have the same name as a getter method in the same scope. in the previous example code you defined getter and setter methods named userName. Save the ActionScript document as Login2. Remember that a getter method does not take any parameters.as. } public function get userName():String { return this. 5. Select File > New and then select Flash Document to create a new FLA. A setter method must take exactly one required parameter.userName = "EnriqueI". you invoke getter and setter methods without any parentheses or arguments.To use implicit getter and setter methods: 1.__username. // EnriqueI Unlike ordinary methods. 258 Classes .__username = username. Add the following ActionScript to Frame 1 of the main Timeline: var user:Login2 = new Login2("RickyM").fla in the same directory as Login2. } public function set userName(value:String):Void { this. For example. and then click OK. in this case you could not also have a property named userName in the same class.userName. You invoke getter and setter methods as you would a property by the same name.__username = value. // calling "get" method var userNameStr:String = user.userName). // RickyM // calling "set" method user. public function Login2(username:String) { this. } } 3. trace(userNameStr). 2. and save it as login2_test. Select File > New and then select ActionScript File.

the properties and methods of a class are fixed. the compiler generates an error. Creating dynamic classes By default. however. public var age:Number. 5. } If.6. because members accessed inside the class definition and on class instances are not compared with those defined in the class scope. 3. can still be type checked for return types and parameter types. an instance of a class can’t create or access properties or methods that weren’t originally declared or defined by the class. 4. Type the following ActionScript into the Script window: class Person { public var userName:String. Save the file on your hard disk as Person.as. and then click OK.fla. see “Creating dynamic classes” on page 259. You should create dynamic classes only if you specifically require this functionality. and then click OK. Flash displays the following information in the Output panel: RickyM EnriqueI You cannot use getter and setter method attributes in interface method declarations. Type checking on dynamic classes is less strict than type checking on nondynamic classes. For information on creating dynamic classes. name the file person_test. Select File > Save As. you create an instance of the Person class and try to access a property of the class that doesn’t exist. and save the file in the same directory as the Person class you created earlier. userName and age. Save the Flash document and select Control > Test Movie to test the file. in another script. Select File > New and then select ActionScript File. About working with custom classes in an application 259 . consider a Person class that defines two properties. To create a class that is not dynamic: 1. Class member functions. That is. Select File > New and then select Flash Document to create a new FLA file. NO T E About dynamic classes Adding the dynamic keyword to a class definition specifies that objects based on the specified class can add and access dynamic properties at runtime. For example. 2.

var firstPerson:Person2 = new Person2().6. 5. This code causes a compiler error because the Person class doesn’t declare a property named hairColor. however.hairColor = "blue".as. There is no property with the name 'hairColor'. Save the Flash document. Select File > New and then select Flash Document to create a new FLA file. In some cases. firstPerson. 3. The dynamic class modifier lets you do just that. and try to assign a value to a property called hairColor (which doesn’t exist in the Person class): var firstPerson:Person = new Person(). Save your changes to the ActionScript file. Add the following code to create a new instance of the Person class (firstPerson). but they are very beneficial to programmers: good error messages help you to write correct code by pointing out mistakes early in the coding process.hairColor). this is exactly what you want to happen. Select File > New and then select ActionScript File. Compiler errors might not seem desirable. Select File > Save As and name the new file person2_test. 6.hairColor = "blue". Type the following code to create a new instance of the Person2 class (firstPerson). 7. // blue 260 Classes . Select File > Save As and name the file Person2. } This ActionScript adds the dynamic keyword to the Person class in the previous example. public var age:Number. In most cases.fla. you might want to add and access properties or methods of a class at runtime that aren’t defined in the original class definition. Save the file on your hard disk. Select Control > Test Movie to test the code. 2.as. 4. // Error. To create a dynamic class: 1. and then click OK. Type the following code into the Script window: dynamic class Person2 { public var userName:String. and then click OK. Save it in the same directory as Person2. 7. and assign a value to a property called hairColor (which doesn’t exist in the Person2 class). 8. firstPerson. Instances of the Person2 class can add and access properties and methods that are not defined in this class. trace(firstPerson.

The code outside the object is forced to interact with the object’s programming interface rather than with the implementation details. you can add methods and properties to the class at runtime (when the SWF file plays). A programmer should be able to interact with an object by knowing only its properties. This approach enables programmers to think at higher levels of abstraction and provides an organizing framework for building complex systems. even though the MovieClip class itself is dynamic. or encapsulate. Because the custom Flash class is dynamic. however. Save your changes to the person2_test. 9. This approach provides some important benefits.0 includes. you wouldn’t want to make classes dynamic unless you needed to. can still be type checked for return types and parameter types. so that details of the implementation can be made private and invisible to code outside an object. This implementation provides you with more control over subclasses of the MovieClip class. it lets the creator of the object change the object’s implementation without requiring any changes to code outside of the object. About working with custom classes in an application 261 . without knowing the details of its implementation. for example. because members accessed inside the class definition and on class instances are not compared with those defined in the class scope. functionality. One reason not to use dynamic classes is that type checking on dynamic classes is less strict than type checking on nondynamic classes. Subclasses of dynamic classes are also dynamic. because you can choose to make your subclasses dynamic or not: class A dynamic class C class D dynamic extends class B extends extends class E MovieClip {} extends A {} B {} A {} extends MovieClip{} // // // // // A B C D E is is is is is not dynamic dynamic dynamic not dynamic dynamic For information on subclasses. Class member functions. When you test the code the text blue should be displayed in the Output panel. When you develop applications. objects are seen as “black boxes” that contain. About using encapsulation In elegant object-oriented design. Encapsulation is why ActionScript 2.fla file. Select Control > Test Movie to test the code. member access control. see Chapter 8. methods. Subclasses of the MovieClip class are not dynamic by default. for example.8. as long as the programming interface doesn’t change. “Inheritance. and events (its programming interface).” on page 301. with one exception.

An example of encapsulation in Flash would be setting all your member and class variables to private and forcing people who implement your classes to access these variables using getter and setter methods. and some developers feel it is unnecessary. Macromedia recommends adding the this keyword as a prefix. This helps qualify the references you make. you cannot tell whether the property or method belongs to the superclass. } public function set userName(value:String):Void { this. } public function set age(value:Number):Void { this. You can also use a class name prefix for static variables and methods. and define getter and setter methods for the private instance members: class Person { private var __userName:String.__age. public function get userName():String { return this. } public function get age():Number { return this. the this keyword makes it easy to tell that a property or method belongs to a class when it has a prefix.__userName. adding prefixes might also trigger code hints. you would need only to change the behavior of the getter and setter functions rather than force every developer to change the way he or she accesses the class’s variables. Performing encapsulation this way ensures that if you ever need to change the structure of the variables in the future. even within a class. The following code shows how you could modify the Person class from earlier examples.__age = value. without the keyword. private var __age:Number. N O TE 262 Classes . set its instance members to private. Depending on the coding environment you use. because it can aid readability and helps you write clean code by providing context for your methods and variables. which makes code readable. You do not have to add these prefixes.__userName = value. } } About using the this keyword in classes Use the this keyword as a prefix within your classes for methods and member variables. Although it is not necessary.

Therefore. Everything between the braces is called the class body and is where the class’s properties and methods are defined. In its most basic form. test. you can’t define a class in a frame script in a FLA file. This example includes the following topics: “About general guidelines for creating a class” on page 264 “Creating and packaging your class files” on page 266 “Writing the constructor function” on page 268 “Adding methods and properties” on page 270 “Controlling member access in your classes” on page 273 “Documenting the classes” on page 274 Example: Writing custom classes 263 . The second example shows you how to use those class files with a FLA file. as shown in the following example: class className { // class body } Remember: you can define classes only in external ActionScript files. By the end of this example. For example. in this case). followed by the class name (Person. and then left and right curly braces ({}). see Chapter 8. Everything inside the braces is the class body.” on page 301. a class declaration consists of the class keyword. The first example in this chapter shows you how to write classes and package them. the basic ordering of your class files is as follows: Documentation comments Class declaration Constructor function Class body You do not write subclasses in this chapter. The class declaration consists minimally of the class statement.Example: Writing custom classes Now that you’ve explored the basics of a class file. you must save the file and recompile any FLA files that use it. CAUTION ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ As discussed in “Writing custom class files” on page 235. and then left and right curly braces ({}). For more information on inheritance and subclassing. if you make any changes to an external file. you create a new file for this example. ActionScript code in external files is compiled into a SWF file when you publish. export. “Inheritance. it’s time to learn some of the general guidelines for creating a class file. or debug a FLA file. a class consists of two main parts: the declaration and the body. followed by an identifier for the class name. Therefore. and what kinds of things it contains.

For information on initializing variables.as. var i:Number. browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\XML_Menu. function myMethod() { var counter:Number. } } 264 Classes . They help you write correct and well-formed classes. xmlmenu. for (counter = 0.fla. for (i = 0 . as the following example shows: // bad code var counter:Number = 0. // quantity of product ■ Initialize local variables when you declare them. The sample calls the ActionScript XmlMenu() constructor and passes it two parameters: the path to the XML menu file and a reference to the current timeline. The rest of the functionality resides in a custom class file. i < my_array. // product SKU (identifying) number private var quantity:Number.length. For example. } ■ ■ Avoid using local declarations that hide higher-level declarations. You practice these guidelines in upcoming examples. Format your declarations as the following example shows: private var SKU:Number. ■ About general guidelines for creating a class The following points are guidelines to follow when you write custom class files. the following code predeclares the loop iterator variable (i) before using it in the for loop: var my_array:Array = new Array("one". do not declare a variable twice. XmlMenu. "three"). place only one declaration per line. On the Macintosh. and do not place either the same or different types of declarations on a single line. ■ In general. unless that initial value is determined by a calculation. i++) { trace(i + " = " + my_array[i]). You can find the sample source file. Declare variables before you first use them (including loops). counter <= 4. see “Adding methods and properties” on page 270. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/XML_Menu. ■ On Windows. in the Samples folder on your hard disk.A sample file on your hard disk demonstrates how to create a dynamic menu with XML data and a custom class file. counter++) { // statements. "two". For example.

See the section “Creating and packaging your class files” on page 266 to create. Set most member variables to private unless there is a good reason to make them public. Make sure that these variables are explicitly public before you create them this way. including capitalization. the first character must be a letter. because it is difficult to read. the ActionScript file that contains the class definition must be named Rock. name. For more information on naming class files.This code declares the same variable inside an inner block.as: // In file Rock. or dollar sign ($). ■ Do not assign many variables to a single value in a statement. or public static. It is much better from a design standpoint to make member variables private and allow access only to those variables through a small group of getter and setter functions.as class Rock { // Rock class body } You name and create a class definition in the following section. and each subsequent character must be a letter. As a preferred practice. Example: Writing custom classes 265 . } ■ Have a good reason for making public instance variables. try to always limit class names to letters. and package the class files. In the following example. class. or dollar sign. m_password:String. or member variables. see “Naming classes and objects” on page 739. ■ About naming class files Class names must be identifiers—that is. or // bad form class User { private var m_username:String. underscore. The class name must exactly match the name of the ActionScript file that contains it. if you create a class called Rock. underscore (_). as you can see in the following ActionScript code samples: // bad form xPos = yPos = 15. number.

can create AS files. the class won’t compile. if these two names don’t match exactly. such as Macromedia Dreamweaver and Macromedia Flex Builder. you create. and then click OK. see “About setting and modifying the classpath” on page 240. Select File > Save As and create a new subdirectory named com. Select File > Save As. Typically.ClassA { } The preceding code creates a new class named ClassA in the com. “A comparison of classes and packages” on page 229. Select File > New and then select Flash Document to create a new FLA document. Class files are also called ActionScript (AS) files.as. You’ll add content to this Flash document in a future step. in the macromedia subdirectory. Several external editors. For information about classpaths. and package your class files for this example (“Example: Writing custom classes” on page 263). including capitalization. c. You create AS files in the Flash authoring tool or by using an external editor. In the following steps. if you want to check syntax. Type the following code into the Script window: class com. you also need to tell Flash how it can find the file. 4.as). The name of a class (ClassA) must exactly match the name of the AS file that contains it (ClassA. and save the Flash document to the current directory. name the new file package_test. when you create an application. N OT E To create a class file and class declaration: 1.utils package. For detailed information on packages.Creating and packaging your class files In this section. and then do the following: a. This is very important. 266 Classes . create an new subdirectory named utils. name. decide where you want to store the file. and then click OK.utils. create a new subdirectory named macromedia. The following sections show you how to write complete (yet simple) class files.fla. Select File > New and then select ActionScript File. 2.macromedia. 3. you’ll save the class file and the application FLA file that uses the class file in the same directory for simplicity. and “Working with packages” on page 230.macromedia. However. When you create a class file. In the com subdirectory. see “About packages” on page 228. you add the directory in which you store your application and class files to the Flash classpath. Save the current ActionScript document in the utils directory and name the file ClassA. b. 5.

Select File > Save As.as class files. A package is a directory that contains one or more class files and resides in a designated classpath directory. Decide on the package name you’d like to use. it must reflect the directory (package) in which it is stored. name the new file ClassB. Package names should be intuitive and easily identifiable by fellow developers. Save your changes to both the ClassA. Save the ClassA.as.utils package. if you decide to move class files after you create them. 7.macromedia.as file looks like this: class com.YourClass { // your class } You write the class declaration that reflects the package directory in the following section. which are discussed in the following sections.utils package needs to be placed in a com/macromedia/utils folder on your hard drive. To package your class files: 1. a class named com. Otherwise. macromedia/docs For example.utils.6. use packages to organize your class files. N OT E For this reason. 10. If you are creating multiple custom classes.macromedia. The class declaration in the YourClass.macromedia. Example: Writing custom classes 267 . For example. Select File > New and then select ActionScript File. Type the following code into the Script window: class com. 8. Remember that the package name also matches a specific directory structure. A class name must be fully qualified within the file in which it is declared—that is. you will have to modify the class declaration statements to reflect their new location.as ActionScript document. “Example: Writing custom classes” on page 263.as created in an earlier step.ClassB { } The previous code creates a new class named ClassB in the com.YourClass is stored in the com/ directory. The class files you use in a FLA file import into a SWF file when you compile it. and then click OK.macromedia. The code you write in a class file should have a certain methodology and ordering. and save it in the same directory as ClassA.docs.macromedia.docs.as and ClassB. see “About setting and modifying the classpath” on page 240. For more information on classpaths. it’s good practice to plan your package structure before you begin creating classes. any classes in the com. 9.

In this part of the chapter. For example. A class’s constructor is a special function that is called automatically when you create an instance of a class using the new operator.utils.2. 3. if your class name was ClassA.__name = uname.macromedia. Writing the constructor function You have already learned how to write the class declaration in “Creating and packaging your class files” on page 266.utils prefix for any class you create in this package. but the package name within each class file. statements. To continue writing the class files.macromedia. Create the required directory structure after you’ve chosen a package name.macromedia. age:Number) { this.as class file. remember to modify not only the directory structure. } Classes .utils. For example. the constructor function initializes each new instance of a class. as well as every import statement or reference to a class within that package. the Person class you created contained the following constructor function: // Person class constructor function public function Person (uname:String. 4. NO TE 268 Constructors are functions that you use to initialize (define) the properties and methods of a class. and declarations in later sections. In OOP. Use the com. you write what’s called the class file’s constructor function. For example. the following code defines a Person class and implements a constructor function. If you change your package structure at a future point. You learn how to write the comments.ClassA within the com/macromedia/utils/ClassA. you would need to create a directory structure of com/macromedia/utils and place your classes in the utils folder. the full class name would need to be com.__age = age. constructors are functions within a class definition that have the same name as the class. The constructor function has the same name as the class that contains it. this. For example. see “Writing the constructor function” on page 268. if your package was named com. By definition.

A constructor function should have no return type. 3. "Wed". if you don’t create a function whose name matches that of the class—the compiler automatically creates an empty constructor function for you. "Sat"). N OT E To add the constructor functions to your class files: 1. } } The previous code defines a constructor method for the ClassA class. you can download the class files from www. 30).helpexamples. } } Example: Writing custom classes 269 . Open the ClassA. Next you’ll add a special function called a constructor function. Open the ClassB.ClassA { function ClassA() { trace("ClassA constructor"). A class can contain only one constructor function.com/flash/learnas/classes/. ■ ■ The term constructor is also typically used when you create (instantiate) an object based on a particular class.Consider the following points when you write constructor functions: ■ If no constructor function is explicitly declared—that is. The following statements are calls to the constructor functions for the toplevel Array class and the custom Person class: var day_array:Array = new Array("Sun".ClassB { function ClassB() { trace("ClassB constructor").utils.macromedia.as class file in the Flash authoring tool. 4. 2. If you do not wish to progress through the example. This constructor traces a simple string to the Output panel.macromedia. Modify the class file so it matches the following code (the changes to make appear in boldface): class com. var somePerson:Person = new Person("Tom".0. which will let you know when a new instance of the class has been created.as class file in the Flash authoring tool.utils. "Mon". The following exercise is part of “Example: Writing custom classes” on page 263. Modify the existing class file so it matches the following code (the changes to make appear in boldface): class com. "Tue". overloaded constructor functions are not allowed in ActionScript 2. "Fri". "Thu".

When you type a variable using the var variableName:variableType format. function ClassA() { trace("ClassA constructor"). Save both ActionScript files before you proceed. which contains the name of the current class. If you do not wish to progress through the example. NO TE To add properties to the ClassA and ClassB classes: 1.as ActionScript file to match the following code (the changes to make appear in boldface): class com. see “About assigning data types and strict data typing” on page 81. To continue writing your class file. Modify the ClassB class and add the static variable so it is similar to the previous code. The following three exercises are part of “Example: Writing custom classes” on page 263. var username:String and var age:Number) in the variable declarations. } } The previous block of code adds a single new static variable. TI P You use the post-colon syntax (for example.5. Modify the ClassA.utils. If the correct data type is not used in the FLA file importing this class. 3. 270 Classes .helpexamples. 4. Open ClassA. you can download the class files from www. Defining them at the top makes the code easier to understand.as and ClassB. By convention.as in the Flash authoring tool. Adding methods and properties To create the properties for the ClassA and ClassB classes. 2. use the var keyword to define variables.com/flash/learnas/classes/.macromedia. Save both ActionScript files before you proceed. _className. For more information on strict data typing. class properties are defined at the top of the class body. This is an example of strict data typing. the compiler throws an error. the ActionScript compiler ensures that any values assigned to that variable match the specified type.ClassA { static var _className:String. but isn’t required. see “Adding methods and properties” on page 270.

utils. } function doSomething():Void { trace("ClassA . } } The block of code in boldface creates a new method in the class. If any errors appear in the Output panel. In ClassA. 2. select Tools > Check Syntax to check the syntax of your ActionScript file. function ClassA() { trace("ClassA constructor").utils. 3. You must declare and define all properties and methods inside the class body (the curly braces [{}]).macromedia. If you cannot fix the code errors. Save both ActionScript files before you proceed.doSomething()").as. For information on members. and static methods and properties (members)” on page 247.doSomething()"). To add methods to the ClassA and ClassB classes: 1. } } 5. see “About public. an error occurs during compilation.ClassB { static var _className:String.macromedia.as.A class’s members consist of properties (variable declarations) and methods (function definitions).ClassA { static var _className:String. copy and paste the complete code into the Script window before you proceed: class com. compare the ActionScript in your script to the complete code written in the previous step. 4. function ClassB() { trace("ClassB constructor"). otherwise. Modify the ClassA class file so it matches the following code (the changes to make appear in boldface): class com. Example: Writing custom classes 271 .as as you did in ClassA.as and ClassB. copy and paste the complete code into the Script window before you proceed. which traces a string to the Output panel. If any errors are reported in the Output panel. Open ClassA. Check the syntax of ClassB.as in the Flash authoring tool. } function doSomething():Void { trace("ClassB . private.

utils. numbers. Save both ActionScript files before you proceed. That is. as well as constructor functions for the following top-level classes: Array. Boolean values. not class variables (variables that belong to the class). the expression on the right side of an assignment must be a compile-time constant.ClassA { static var _className:String = "ClassA". the expression cannot refer to anything that is set or defined at runtime.as and ClassB. Boolean. Modify the ClassB class file and add the inline property. Modify the ClassA class file so the code matches the following ActionScript (the changes to make appear in boldface): class com. This rule applies only to instance variables (variables that are copied into each instance of a class). } } The only difference between the existing class file and the previous block of code is there is now a value defined for the static _className variable. 3. and undefined. as shown in the following example: class Person { var age:Number = 50. N O TE 272 To continue writing your class file.doSomething()"). 4. } function doSomething():Void { trace("ClassA .You can initialize properties inline—that is. } When you initialize properties inline. Open ClassA. only one array is created for all instances of the class. null.as in the Flash authoring tool. To initialize properties inline: 1. Classes . var username:String = "John Doe". changing the value to “ClassB”. when you declare them—with default values. “ClassA”. 2. When you initialize arrays inline. function ClassA() { trace("ClassA constructor"). Compile-time constants include string literals. Number. see “Controlling member access in your classes” on page 273.macromedia. Object. and String.

The following class (LoginClass) defines a private property named userName and a private method named getUserName(): class LoginClass { private var userName:String. In the following example.as in the Flash authoring tool. cannot access privately declared properties and methods. in some cases you might want to protect data or methods of a class from access by other classes. N OT E To control member access: 1. not at the instance level.userName. the following code declares a private variable (a property) and a private method (a function). doSomething():Void { . private members are accessible only within class definitions.as and ClassB. } // Constructor: public function LoginClass(user:String) { this. public function trace("ClassA } public function trace("ClassA } } ClassA() { constructor").Controlling member access in your classes By default. you change member access in your class files. This exercise is part of “Example: Writing custom classes” on page 263. However.userName = user.ClassA { private static var _className:String = "ClassA". } } Private members (properties and methods) are accessible only to the class that defines those members and to subclasses of that original class.macromedia.utils. any property or method of a class can be accessed by any other class: all members of a class are public by default. Instances of the original class. that is. If you do not wish to progress through the example. private function getUserName():String { return this. Open ClassA. 2. you can download the class files from www. You need to make those members private (available only to the class that declares or defines them). For example.as ActionScript file so its contents match the following ActionScript (the changes to make appear in boldface): class com. Example: Writing custom classes 273 .helpexamples. Modify the ClassA. You specify public or private members using the public or private member attribute.com/flash/learnas/classes/. or instances of subclasses of that class.doSomething()").

you might want to distribute your class files into the Flash community. Include one documentation comment per class. For example. Flash Player does not distinguish between private or public members. The member is private and cannot be accessed. 3. var a:ClassA = new ClassA(). There are two kinds of comments in a typical class or interface file: documentation comments and implementation comments. and place it directly before the declaration. You use documentation comments to describe the code’s specifications. or member. and constructors. and implementation comments are delimited with /* and */. added to Frame 1 of the Timeline in a FLA file. However. To continue writing your class file. the following code.ClassA. trace(a.This previous code sets both methods (the ClassA constructor and the doSomething() method) as public. would result in a compiler error indicating that the method is private and can’t be accessed: import com. meaning that they can be accessed by external scripts. For example. Documentation comments are not a language construct in ActionScript 2.as ActionScript file and add the same method and property access as the ClassA class. The two kinds of comments use slightly different delimiters.utils. at runtime. The static _className variable is set as private. N O TE 274 Use documentation comments to describe interfaces. they are a common way of structuring comments in a class file that you can use in your AS files. see “Documenting the classes” on page 274. but not the implementation. Documentation helps other users understand the purpose and origins of the class.macromedia. or you might be working with a team of designers or developers who will use your class files in their work or as part of a project you’re working on. An instance of ClassA or ClassB cannot access the private members. meaning the variable can be accessed only from within the class and not from external scripts. Documenting the classes Using comments in your classes and interfaces is an important part of documenting them for other users. // Error. Modify the ClassB. classes._className). Documentation comments are delimited with /** and */. You use implementation comments to comment out code or to comment on the implementation of particular sections of code. 4. Classes . interface.0. Save both ActionScript files before you proceed. methods. Member access control is a compile-time-only feature.

If you have to document additional information that does not fit into the documentation comments. changing the class name and any other information as you see fit. you can download the class files from www. use implementation comments (in the format of block comments or single-line comments.as and ClassB. copyright information. public function trace("ClassA } public function trace("ClassA } } ClassA() { constructor"). N OT E To document your class files: 1. doSomething():Void { .as ActionScript file.1 6/21/2005 copyright Macromedia. do not include comments that describe the corresponding package.ClassA { private static var _className:String = "ClassA". 4. or any potential issues/bugs that may be present in the file. NO T E Open ClassA.as in the Flash authoring tool.macromedia. directly follow the declaration. If you do not wish to progress through the example. 3.com/flash/learnas/classes/.helpexamples.utils. Save both ActionScript files before you proceed. Modify the ClassA class file and add the new code to the top of the class file (the changes to make appear in boldface): /** ClassA class version 1. */ class com. Inc. Example: Writing custom classes 275 . Do not include comments that do not directly relate to the class being read. if you add them. date last modified. as described in “About comments” on page 131). Add a similar comment to the top of the ClassB. For example.doSomething()"). Implementation comments. The code above added a comment to the top of the class file. It’s always a good idea to add comments to your ActionScript and Flash files so that you can add useful information such as the author of the class. The following exercise is part of “Example: Writing custom classes” on page 263. 2.

as well as how to import classes and packages. locate ClassA. To learn how to use these custom class files in a SWF file. and final. Save both the ClassA. 276 Classes . you learn how classpaths work. In the following exercises.macromedia. or you can download them from www. you use the custom classes to create a small application in Flash. see “Writing good comments” on page 743. single-line.You might also add the block.com/flash/learnas/ classes/. For general information about comments. subdirectory within the macromedia folder named utils.helpexamples. you must prefix the class name with the class’s package name. Example: Using custom class files in Flash This example uses class files that are written in the example called “Example: Writing custom classes” on page 263. or trailing comments within the class’s code. If you completed “Example: Writing custom classes” on page 263. proceed to “Importing classes and packages” on page 276. The combination of a class’s name and its package path is the class’s fully qualified class name.as and ClassB. Add a third. Now you are ready to proceed with this example. see “Single-line comments” on page 132. You can use the custom classes written in “Example: Writing custom classes” on page 263 with a FLA file.as on your hard disk. Since the package name of the ClassA class file is com. you’ll need to make sure that you save the class files in the proper directory structure. To continue this example. and then everything works together. “Multiline comments” on page 133. how to use class files in your application.ClassA.as class files within this utils folder. see “Example: Using custom class files in Flash” on page 276. In this example. and “Trailing comments” on page 134. Create a subfolder named com in the current directory. add a new folder named macromedia. Importing classes and packages To reference a class in another script. Within the com folder. If a class resides in a top-level classpath directory—not in a subdirectory in the classpath directory—then its class name is also its fully qualified class name. Your classes compile into the SWF file when you publish the document.as and ClassB. For information on writing good comments within your code.utils.

and the class isn’t available to any SWF files that the FLA file containing the import statement might load. If an imported class is not used in a script. each dot represents a nested directory. If you use the wildcard character.learnAs2.ClassName = new com. You can use the wildcard character (*) to import all the classes in a given package.com/flash/learnas/classes/.macromedia. use dot (. You can also use the fully qualified class name to type your variables. you don’t need to use the fully qualified class name each time you use the class.learnAs2.macromedia.docs.as and ClassB.helpexamples.as. you can download the class files from www.macromedia. you could reference that class by its abbreviated name. The following exercise is part of “Example: Using custom class files in Flash” on page 276 which continues the examples “Example: Writing custom classes”. suppose you create a class named ClassName that resides in a com/macromedia/docs/learnAs2 package in your classpath.macromedia. If you need ClassA and ClassB.util. Package paths are hierarchical. as shown in the following example: var myUser:UserClass = new UserClass().*. You can also use the wildcard character (*) to import all the classes in a package. as shown in the following code: import com. The import statement applies only to the current script (frame or object) in which it’s called.utils. Suppose you have a package named com. in the same script. The following example shows that you can then reference either of the classes directly in the same script: var myA:ClassA = new ClassA(). as shown in the following example: var myInstance:com. suppose that in a script you imported the above class using the import statement. you could import both classes in that package using the wildcard character.) notation to separate package directory names. you could specify the fully qualified class name. You can use the import statement to import packages into a script. NO T E Example: Using custom class files in Flash 277 . To create an instance of that class. For example.To specify package paths.macromedia. which lets you use a class’s abbreviated name rather than its fully qualified name. that is. For example.ClassName().docs.utils that contains two ActionScript class files. ClassA. Later.UserClass. the class is not included in the resulting SWF file’s bytecode. as shown in the following example: import com. In another script.docs. var myB:ClassB = new ClassB().learnAs2.

so you can use any of the methods or properties of the Array class with any array instance.fla Flash document. N O TE 278 Classes . // ClassA constructor var b = new ClassB().utils. Continuing the example you started in “Example: Using custom class files in Flash” on page 276. The next step in this example (“Example: Using custom class files in Flash” on page 276) is to create an instance of the ClassA and ClassB classes in a script. An instance of the ClassB class is also created.fla. you modified FLA file to import the classes you wrote so that you don’t have to always refer to them by their fully qualified names. or import the class (as demonstrated in “Importing classes and packages” on page 276. such as a frame script in a package_test. Type the following code into the Script window: import com. To create an instance of a custom class.macromedia.macromedia. you create a new instance of the ClassA class. see “Creating instances of classes in an example” on page 278.) The following exercise is part of “Example: Using custom class files in Flash” on page 276 which continues the examples “Example: Writing custom classes”. and assign it to a variable. Save your changes to the Flash document before you proceed. arrays are instances of the Array class. 2. For example. you use the new operator in the same way you would when creating an instance of a toplevel ActionScript class (such as the Date or Array class). such as UserSettings. // ClassB constructor The previous block of code begins by importing each of the classes within the com. To continue using these class files in a Flash file. which causes the constructor method to trace a message to the Output panel. Open the file called package_test. Creating instances of classes in an example Instances are objects that contain all the properties and methods of a particular class. Next.To import a class or package: 1. which sends debugging messages to the Output panel. 3. Or you can create you own class. var a = new ClassA(). and then create an instance of the UserSettings class.*. You refer to the class using its fully qualified class name.utils package by using the wildcard (*) character.

// call the ClassB's doSomething() method Data typing your objects in this code example enables the compiler to ensure that you don’t try to access properties or methods that aren’t defined in your custom class. Type the following boldface code into the Script window: import com. Select File > Save As. // ClassB constructor b. To assign a class to a movie clip symbol: 1. name the file Animal. 3. Select File > New and then select ActionScript File.as. see “About assigning data types and strict data typing” on page 81. To continue using these class files in a Flash file.doSomething().utils. 3. Open the file called package_test. For more information on strict data typing.macromedia. Assigning a class to symbols in Flash You can also assign a class to symbols that you might use in a Flash file. Save your changes to the FLA file before you proceed. 4. see “Assigning a class to symbols in Flash” on page 279. See “Creating dynamic classes” on page 259. var a:ClassA = new ClassA(). and save the file on your hard disk. 2.doSomething().*. Assigning a class to symbols in Flash 279 . such as a movie clip object on the Stage. 2.fla. Type the following code into the Script window: class Animal { public function Animal() { trace("Animal::constructor"). The exception to data typing your objects is if you declare the class to be dynamic using the dynamic keyword.To create a new instance of the ClassA and ClassB classes: 1. // call the ClassA's doSomething() method var b:ClassB = new ClassB(). Save your changes to the ActionScript file. // ClassA constructor a. } } This ActionScript creates a new class called Animal that has a constructor method that traces a string to the Output panel. You should now have a basic understanding of how to create and use classes in your Flash documents. and then click OK. Remember that you can also create instances of top-level ActionScript or built-in classes (see “About working with built-in classes” on page 296).

Click the Export for ActionScript check box in the Linkage section. 9. name the file animal_test. Select 13. N OT E 12.5. classes used by a SWF file are packaged and exported in the SWF file’s first frame. the Export in First Frame check box and click OK to apply your changes and close the dialog box. Select File > Save As. 8. Select File > New and then select Flash Document.fla. the user has to wait until all the class code has downloaded before that frame appears. The Output panel displays the text from your Animal class’s constructor function.0 Class to Animal (to match the class name specified in step 3). and save the file to the same folder as the Animal. you can right-click the symbol in the document’s library and select Properties or Linkage from the context menu. Enter a symbol name of animal. Compiling and exporting classes By default. Select File > New and then select Flash Document to create a new FLA file. and then click OK. Enter an identifier value of animal_id. Select Insert > New Symbol to launch the Create New Symbol dialog box. To specify the export frame for classes for a Flash document: 1. 6. 11. 10. You can also specify a different frame where your classes are packaged and exported. Save the Flash document and select Control > Test Movie. if a SWF file uses many classes that require a long time to download (such as components). 7. If you need to modify the Movie Clip’s Linkage properties.fla. for example. and set the ActionScript 2. you could display a short-loading animation in the first few frames of the timeline while the class code in the later frame downloads. By specifying a later frame in the timeline. Save the new document as exportClasses. 280 Classes . and select the Movie Clip option. The Advanced button is available when you are in the basic mode of the Create New Symbol dialog box. Click the Advanced button in the lower-right corner of the Create New Symbol dialog box to enable more options. If the classes are exported in the first frame.as file you created in step 2. This is useful. Enabling this option allows you to dynamically attach instances of this symbol to your Flash documents during runtime.

10. If the frame specified does not exist in the timeline. and click OK. 8. Click 13. and give it an instance name of my_pb. In the Linkage Properties dialog box. Click OK to close the ActionScript Settings dialog box. 4. 3. gotoAndPlay(1). enter the number of the frame where you want to export your class code (Frame 10). In the Export Frame for Classes text box. the Settings button next to the ActionScript version pop-up menu to open the ActionScript Settings dialog box. drag it above the content layer. deselect the Export in First Frame check box. Right-click each component (except the ProgressBar) in the Library panel and select Linkage from the context menu to launch the Linkage Properties dialog box. } 6. make sure that Export for ActionScript is selected. and then click OK to close the Publish Settings dialog box.getBytesTotal() + " bytes loaded"). Create a new keyframe on Frame 10 of the content layer and drag several components onto the Stage. File > Publish Settings. In the Publish Settings dialog box. Compiling and exporting classes 281 . Select 11. Create a new layer.indeterminate = true. you get an error message when you publish your SWF file. Add the following ActionScript code to Frame 1 of the actions layer on the main Timeline: my_pb. and rename it actions.2. 14. } else { gotoAndStop(classesFrame). drag a ProgressBar component from the Components panel to the Stage. select the Flash tab. 9. Create a new keyframe on Frame 2 of the actions layer and add the following ActionScript code: var classesFrame:Number = 10. Create a new keyframe on Frame 10 of the actions layer and add the following ActionScript: stop(). 12. Rename the default layer to content. 7. 5.getBytesLoaded() + " of " + this. if (_framesloaded < classesFrame) { trace(this.

It is not a documented file format and is not intended to be redistributed. If you plan to delete ASO files. Select Control > Test Movie to test the Flash document. The file contains the bytecode that’s produced from the associated ActionScript (AS) file. select View > Simulate Download from the SWF file. ActionScript files included by the corresponding ActionScript file have been modified.15. Flash simulates downloading the Flash document at a lower speed. such as checking syntax or exporting SWFs. Using ASO files During compilation. For more information on ASO files. ActionScript files that contain definitions imported or used by the corresponding ActionScript file have been modified. For unchanged AS files. This is because only the AS files that have changed are recompiled into ASO files. delete them when Flash is not performing other operations. Flash generates an ASO file. which allows you to see the progress bar component animate as the class files download.aso extensions in the /aso subdirectory of the default global classpath directory (see “About setting and modifying the classpath” on page 240). 282 Classes . If the Components load too quickly. Flash sometimes creates files with . these files contain the compiled form (the bytecode) of a class file. the compiler reads the already-compiled bytecode directly out of the ASO file instead of recompiling the AS file. Therefore.0 file that is implicitly or explicitly imported and successfully compiled. If you experience problems in which Flash appears to be compiling older versions of a file you have edited. ■ The compiler creates ASO files for caching purposes. see “Using ASO files” on page 282. For each ActionScript 2.aso extension stands for ActionScript object (ASO). The ASO file format is an intermediate format developed for internal use only. Flash needs to regenerate an ASO file only when the following scenarios occur: ■ ■ The corresponding AS file has been modified. You might notice that your first compilation is slower than subsequent compilations. delete the ASO files and then recompile. The .

In general. If the bytecode is larger than that limit. Select Control > Delete ASO Files and Test Project to delete ASO files and then test the application. In this situation. if you have a class method that uses a callback function (such as the LoadVars class’s onLoad() method). You can’t predict the size of the bytecode representation of a given class.767 bytes. it might be necessary to create a pointer to the current class. as the next example shows. Understanding classes and scope 283 . select one of the following in the authoring environment: ■ ■ Select Control > Delete ASO Files to delete ASO files and continue editing. but classes up to 1.500 lines usually don’t go over the limit. move some of the code into another class. you might have to change how you use the this keyword. If you are editing an ActionScript document in the Script window: ■ ■ There is a limit to how much code you can place in a single class: the bytecode for a class definition in an exported SWF file cannot be larger than 32.To delete ASO files: If you are editing a FLA file. Understanding classes and scope When you move ActionScript code into classes. For example. it can be difficult to know whether the this keyword refers to the class or to the LoadVars object. If your class goes over the limit. Select Control > Delete ASO Files to delete ASO files and continue editing. it is good OOP practice to keep classes relatively short. a warning message appears. and you want to delete an ASO file. Select Control > Delete ASO Files and Test Movie to delete ASO files and test the application.

string. } } Because you are trying to reference the private member variable within an onLoad handler. You can now use this class with a Flash document. you can reference the current class instead of only the XML packet. */ thisObj. you must create a pointer to the local class file so that you can directly reference the class from the onLoad handler.as */ class Product { private var productsXml:XML. contains the path to an XML file function Product(targetXmlStr:String) { /* Create a local reference to the current class. the this keyword actually refers to the prodXml instance and not the Product class. set the class's productsXml variable to the parsed XML document and call the init function. thisObj. // constructor // targetXmlStr . which you might expect. trace(this. */ var thisObj:Product = this. prodXml. and then click OK. 2. } else { /* There was an error loading the XML file. */ trace("error loading XML"). Type or paste the following code into the Script window: /** Product class Product. Select File > New and then select ActionScript File. prodXml.init(). // Create a local variable.ignoreWhite = true. } }. } public function init():Void { // Display the XML packet. For this reason.productsXml = this. 284 Classes . // Begin loading the XML document. Even if you are within the XML's onLoad event handler.To understand scope and external class files: 1. var prodXml:XML = new XML().productsXml).onLoad = function(success:Boolean) { if (success) { /* If the XML successfully loads and parses.load(targetXmlStr). prodXml. which is used to load the XML file.

numInstances.username. Because the numInstances variable is static.as. 3. Understanding classes and scope 285 . } public static function get instances():Number { return User.numInstances) is incremented within the constructor method. Select File > New and then select ActionScript File. not for every single instance.3. 6. and then click OK.helpexamples. The static keyword specifies that a variable or function is created only once per class rather than being created in every instance of that class.fla in the same directory. Type the following ActionScript into the Actions panel: var myProduct:Product = new Product("http://www. the variable is created only once for the entire class.xml"). Select Frame 1 of the main Timeline. Another type of scope you encounter when working with these classes is static variables and static functions. see “About public. Create a new Flash document named testProduct. public function User() { User. A private. Save the document as User. } } The previous code defines a User class that tracks the number of times the constructor has been called. To use the static keyword: 1.as. 2. The following example demonstrates how you can use the static keyword to create a counter that tracks how many instances of the class Flash has created. 7. Select Control > Test Movie to test this code in the test environment. The contents of the specified XML document appear in the Output panel. 4.com/ crossdomain. You can access a static class member without creating an instance of the class by using the syntax someClassName. static variable (User. and static methods and properties (members)” on page 247 and “Using class members” on page 254. private. Save the previous ActionScript code as Product. Type the following code into the Script window: class User { private static var numInstances:Number = 0. Another benefit of static variables is that static variables don’t lose their values after the variable’s scope has ended. For more information on static variables and functions. 5.numInstances++.

are written into Flash Player. “Syntax and Language Fundamentals. There are many classes that ship with Flash that you use to create interactivity and functionality in your SWF files. trace(User. trace(User. and Math classes. these classes are located in the ActionScript 2.instances). 6. ActionScript also provides several built-in classes (complex data types). Select File > New and then select Flash Document to create a new FLA file.0 Classes directory. Top-level classes. The rest of the code creates new instances of the User class and displays the current value returned by the instances() getter method. Some of the top-level classes are based on the ECMAScript (ECMA-262) edition 3 language specification and are called core ActionScript classes. and Booleans) described earlier in this manual (see Chapter 4. In the Actions toolbox. For example. Examples of core classes are the Array. see “About using the this keyword in classes” on page 262. 5. listed in “Top-level classes” on page 288.instances). and you can even build complex applications using them. Type the following ActionScript code in Frame 1 of the Timeline: trace(User. Select Control > Test Movie to test the documents. you can use the Math class to perform equations in your applications. for example) and primitive data types (numbers.4. Date. For information on using the this keyword in classes. “Data and Data Types. // 1 var user2:User = new User(). For more information on packages. see “Working with packages” on page 230. About top-level and built-in classes In addition to the ActionScript core language elements and constructs (for and while loops.as. 286 Classes . These classes provide a variety of scripting features and functionality.instances). You have used top-level classes and other built-in classes that are part of the ActionScript language in earlier chapters. // 0 var user1:User = new User(). strings. and you will use them throughout the remaining chapters. // 2 The first line of code calls the static instances() getter method. which returns the value of the private static numInstances variable.” on page 113).” on page 71 and Chapter 5. Boolean. Or you might use the BitmapData class to create pixels and scripted animations. and save the FLA file in the same directory as User.

For more information on top-level and built-in classes. Code examples using these classes are included throughout the entire Learning ActionScript 2. To understand the distinction between core ActionScript classes and those specific to Flash.lang package” on page 295 “The System and TextField packages” on page 295 About top-level and built-in classes 287 . see the following topics: ■ ■ ■ ■ ■ ■ ■ ■ ■ “Top-level classes” on page 288 “The flash. For information on language elements (such as constants. For an overview of working with classes and objects in object-oriented programming.text package” on page 295 “The mx. and the classes specific to Flash provide runtime control over the appearance and behavior of a Flash application. You can find the classes folders here: ■ Windows: Hard Disk\Documents and Settings\user\Local Settings\Application Data\Macromedia\Flash 8\language\Configuration\Classes. operators. Examples of these classes are the Camera. consider the distinction between core and client-side JavaScript. such as flash. The following sections introduce the built-in ActionScript classes. The rest of the built-in ActionScript classes are specific to Macromedia Flash and the Flash Player object model. “Syntax and Language Fundamentals.0 in Flash manual.” on page 113. and directives). ■ Do note the Read Me document located in this directory for more information about its structure.display package” on page 292 “The flash.You can find the ActionScript classes installed on your hard disk. Other classes are organized into packages. The client-side JavaScript classes provide control over the client environment (the web browser and web page content). and describe the fundamental tasks you perform with these built-in classes.external package” on page 292 “The flash. and LoadVars classes. Macintosh: Hard Disk/Users/user/Library/Application Support/Macromedia/Flash 8/ language/Configuration/Classes.filters package” on page 293 “The flash. MovieClip.display. see “About working with built-in classes” on page 296.geom package” on page 294 “The flash. see Chapter 5.net package” on page 294 “The flash. All of these classes are sometimes referred to as built-in classes (predefined classes that you can use for adding functionality to your applications).

outside of classes. The CustomActions and XMLUI classes are available only in the Flash authoring environment. The Array class represents arrays in ActionScript and all array objects are instances of this class. “Functions and Methods” You can find a list of these language elements in the following sections of the ActionScript 2.>. Object. include Array. See Array. Provides event notification and listener management capabilities that can be added to other objects.0 Language Reference: ■ ■ ■ ■ ■ ■ Compiler Directives Constants Global Functions Global Properties Operators Statements Top-level classes The top level contains the ActionScript classes and global functions. global properties. buttons. See AsBroadcaster. For information on how to use each of these language elements. String. global functions. see the following table. operators. many of which provide core functionality for your applications. Error. Math. borrowed directly from ECMAScript. To find more information on each class. Function. constants. The Boolean class is a wrapper for Boolean (true or false) values. and statements. These include directives. and text fields at runtime. Core classes. Array AsBroadcaster Boolean Classes . Date. see the following topics: ■ ■ Chapter 5. The Array class contains methods and properties for working with array objects. N OT E 288 Class Accessibility Description The Accessibility class manages communication between SWF files and screen reader applications. See Accessibility. and System. Number. “Syntax and Language Fundamentals” Chapter 6. See Boolean. You use the methods of this class with the global _accProps property to control accessible properties for movie clips. Boolean.Other language elements There are other language elements that make up ActionScript.

The Key class provides methods and properties for getting information about the keyboard and key presses. You add new menu items that you create with this class to the Flash Player context menu by using the ContextMenu class. When used with Flash Communication Server. See CustomActions.ColorTransform). your SWF file can capture.finally statement. Button. see ColorTransform (flash. associated with the version 2 component. See ContextMenuItem. See Function.. properties. broadcast.geom.catch. The ContextMenuItem class lets you create new menu items that appear in the Flash Player context menu. The Camera class provides access to the user’s camera. See Button. Note that the built-in Button class is different from the Button component class. including those native to ActionScript and those that you define. The Color class is deprecated in Flash Player 8 in favor of the ColorTransform class. For information on color transforms. See ContextMenu.Class Button Description The Button class provides methods. The Color class lets you set the RGB color value and color transform of movie clip instances and retrieve those values after you set them. See Camera. The Date class also provides the means for obtaining the current date and time from the operating system. See Error. See Date. and record images and video from a user’s camera. Camera Color ContextMenu ContextMenuItem CustomActions Date Error Function Key About top-level and built-in classes 289 . which you can handle using a try. The ContextMenu class lets you control the contents of the Flash Player context menu at runtime. You can also add custom menu items to a ContextMenu object by using the ContextMenuItem class. The CustomActions class lets you manage any custom actions that are registered with the authoring tool. or TextField objects by using the menu property available to those classes. See Key. and event handlers for working with buttons. The Date class shows how dates and times are represented in ActionScript. Button. The Function class is the class representation of all ActionScript functions.. if one is installed. You can associate separate ContextMenu objects with MovieClip. and it supports operations for manipulating dates and times. The Error class contains information about runtime errors that occur in your scripts. You typically use the throw statement to generate an error condition.

The Microphone class provides access to the user’s microphone. and PNG files load into movie clip instances. See NetConnection.constant. The LocalConnection class lets you develop SWF files that send instructions to each other without using the fscommand() method or JavaScript. See Selection. See Mouse. See LocalConnection. The Mouse class provides control over the mouse in a SWF file. See Object. all other classes inherit its methods and properties. The NetConnection class establishes a local streaming connection for playing a Flash Video (FLV) file from an HTTP address or from the local file system. Math Microphone Mouse MovieClip MovieClipLoader NetConnection NetStream Number Object PrintJob Selection 290 Classes . This class lets you implement listener callbacks that provide status information while SWF. The NetStream class controls playback of FLV files from a local file system or HTTP address. including content that is rendered dynamically. your SWF file can broadcast and record audio from a user’s microphone. When used with Flash Communication Server.Class LoadVars LocalConnection Description The LoadVars class lets you transfer variables between a SWF file and a server in name-value pairs. for example. JPEG.method(parameter) or Math. See MovieClipLoader. See LoadVars. GIF. The Math class provides convenient access to common mathematical constants and provides several common mathematical functions. Every movie clip in a SWF file is an instance of the MovieClip class. and multipage documents. See MovieClip. You use the methods and properties of this class to control movie clip objects. See Microphone. if one is installed. See PrintJob. this class lets you hide or show the mouse pointer. The Number class is a wrapper for the primitive number data type. See Math. The PrintJob class lets you print content from a SWF file. The Selection class lets you set and control the text field in which the insertion point is located (the text field that has focus). The Object class is at the root of the ActionScript class hierarchy. See Number. All the properties and methods of the Math class are static and must be called with the syntax Math. See NetStream.

It also lets you show or hide the Flash Player Settings panel and modify SWF file security settings. See XML. or within Flash to display a Flash Video (FLV) file. See TextFormat. screen resolution and current system language). The String class is a wrapper for the string primitive data type. The TextSnapshot object lets you access and lay out static text inside a movie clip. Sound Stage String System TextField TextFormat TextSnapshot Video XML XMLNode About top-level and built-in classes 291 . and changing properties such as alpha or background color. and scale mode. See System. which lets you use the methods and properties of the String object to manipulate primitive string value types. alignment. This class contains methods and properties for working with XML objects. You can use this class with Flash Communication Server to display live streaming video in a SWF file. The System class provides information about Flash Player and the system on which Flash Player is running (for example. See Video. See String. See Sound. See TextSnapshot. The TextField class provides control over dynamic and input text fields. See TextField. See SharedObject. It also reports Stage resize events. The Stage class provides information about a SWF file’s dimensions.Class SharedObject Description The SharedObject class offers persistent local data storage on the client computer. This class offers real-time data sharing between objects on the client’s computer. It is the XML class’s superclass. See Stage. such as retrieving formatting information. The TextFormat class lets you apply formatting styles to characters or paragraphs in a TextField object. The Video class lets you show video objects in a SWF file. The XMLNode class represents a single node in an XML document tree. similar to cookies. See XMLNode. invoking event handlers. The Sound class provides control over sounds in a SWF file.

and Tools). XMLUI The flash. See XMLUI. Effects.display package contains the BitmapData class that you can use to build visual displays. such as that which is required for real-time chat applications. if you embed a SWF file in an HTML page. See XMLSocket.Class XMLSocket Description The XMLSocket class lets you create a persistent socket connection between a server computer and client running Flash Player. 292 Classes . See BitmapData (flash. that HTML page is the container. Client sockets enable low-latency data transfer.external package lets you communicate with the Flash Player container using ActionScript code. Commands. Also called the External API. The XMLUI object enables communication with SWF files that are used as a custom user interface for the Flash authoring tool’s extensibility features (such as Behaviors.display. The flash. Class BitmapData Description The BitmapData class lets you create arbitrarily sized transparent or opaque bitmap images in the document and manipulate them in various ways at runtime.external package The flash. Class ExternalInterface Description The ExternalInterface class is the External API. You would be able to communicate with the HTML page using the ExternalInterface class and JavaScript.external. a subsystem that enables communications between ActionScript and the Flash Player container (such as an HTML page using JavaScript) or a desktop application that uses Flash Player.ExternalInterface). See ExternalInterface (flash.BitmapData). For example.display package The flash.

DropShadowFilter GlowFilter GradientBevelFilter The DropShadowFilter class lets you add a drop shadow to a movie clip.The flash. For more information on each class.filters.GlowFilter). See ConvolutionFilter (flash.filters. GradientGlowFilter About top-level and built-in classes 293 .GradientBevelFilter). Class BevelFilter BitmapFilter BlurFilter ColorMatrixFilter Description The BevelFilter class lets you add a bevel effect to a movie clip instance.DisplacementMapFilter). ConvolutionFilter DisplacementMapFilter The DisplacementMapFilter class lets you use the pixel values from a specified image (the displacement map image) to spatially displace the original instance (a movie clip) that you apply the filter to. bevel. The ColorMatrixFilter class lets you apply a 4 x 5 matrix transformation on the ARGB color and alpha values of every pixel on the input image.filters.ConvolutionFilter). See BitmapFilter (flash. See GlowFilter (flash. The GradientBevelFilter class lets you apply a gradient bevel effect to a movie clip. See GradientGlowFilter (flash. See GradientBevelFilter (flash. glow.GradientGlowFilter). See ColorMatrixFilter (flash. The GradientGlowFilter class lets you apply a gradient glow effect to a movie clip. you can produce a result with a new set of ARGB color and alpha values. The BitmapFilter class is a base class for all filter effects. The GlowFilter class lets you add a glow effect to a movie clip.filters.filters. The BlurFilter class lets you apply a blur effect to movie clip instances. see the cross references provided in the following table. See DropShadowFilter (flash.BitmapFilter).filters. to Image and MovieClip instances. and drop shadows.filters.filters. After applying the transformation.DropShadowFilter).filters package The flash. See BlurFilter (flash.filters. The ConvolutionFilter class lets you apply a matrix convolution filter effect.ColorMatrixFilter). See BevelFilter (flash. such as blur.BlurFilter). Filters let you apply rich visual effects.filters package contains classes for the bitmap filter effects available in Flash Player 8.filters.BevelFilter). See DisplacementMapFilter (flash.

Point). For more information on each class. FileReferenceList 294 Classes . See FileReference (flash. See FileReferenceList (flash.Matrix). For more information on each class.net package The flash.geom. These classes support the BitmapData class and the bitmap caching feature. see the cross references provided in the following table. where x represents the horizontal axis and y represents the vertical axis.Rectangle). Class FileReference Description The FileReference class lets you upload and download one or more files between a user’s computer and a server. rectangles.The flash. See Point (flash.geom package contains geometry classes. You can retrieve these values after they have been set. See Rectangle (flash. Represents a transformation matrix that determines how to map points from one coordinate space to another. such as points.geom package The flash. and transformation matrices. See Transform (flash. The Point object represents a location in a two-dimensional coordinate system.net package contains classes that let you upload and download one or more files between a user’s computer and the server. See ColorTransform (flash. The Rectangle class is used to create and modify Rectangle objects.FileReference). Class ColorTransform Description The ColorTransform class lets you mathematically set the RGB color value and color transform of an instance.geom.geom. see the cross references provided in the following table.ColorTransform). The FileReferenceList class lets you upload one or more files from a user’s computer to a server.geom.net. Matrix Point Rectangle Transform The flash.Transform).FileReferenceList).geom.net. Collects data about color transformations and coordinate manipulations that are applied to an object instance. See Matrix (flash.

text package contains the TextRenderer class for working with advanced antialiasing in available in Flash Player 8. See Locale (mx. See security (System.capabilities). and security classes. The mx. Class Locale Description This class lets you control how multilanguage text displays in a SWF file. See TextRenderer (flash. These classes deal with client settings that might affect your application in Flash Player. The security class contains methods that specify how SWF files in different domains can communicate with each other. Class TextRenderer Description This class provides functionality for the advanced anti-aliasing capability in Flash Player 8. The System and TextField packages The System package contains the capabilities. See IME (System.security).Locale). IME.text.TextRenderer). IME security About top-level and built-in classes 295 . see the cross references provided in the following table. See capabilities (System.lang package The mx.lang.The flash.text package The flash.IME). The IME class lets you directly manipulate the operating system’s input method editor (IME) that’s within the Flash Player application running on a client computer. Class capabilities Description The capabilities class determines the abilities of the system and Flash Player that’s hosting the SWF file.lang package contains the Locale class for working with multilanguage text. For more information on each class. This lets you customize content for different formats.

as discussed in “About top-level and built-in classes” on page 286. 296 Classes . A class describes the properties (data) and behavior (methods) for an object. which you typically assign to a variable. and other formatting styles.The TextField package contains the StyleSheet class that you can use to apply CSS styles to text. which helps you easily add interactivity to your applications. About working with built-in classes In object-oriented programming (OOP). To use the properties and methods defined by a built-in class. The constructor function always has the same name as the class.StyleSheet). See StyleSheet (TextField. much like an architectural blueprint describes the characteristics of a building. Class StyleSheet Description The StyleSheet class lets you create a style sheet object that contains text formatting rules such as font size. use the new operator to invoke the class’s constructor function. see the following sections: ■ ■ “Object-oriented programming fundamentals” on page 231 “Writing custom class files” on page 235 Flash 8 has many built-in classes that you can use in your code (see “About top-level and builtin classes” on page 286). you generally first create an instance of that class (except for classes that have static members). and returns an instance of the class. see the following topics: ■ ■ ■ ■ ■ ■ “About creating a new instance of a built-in class” on page 296 “Accessing built-in object properties” on page 297 “About calling built-in object methods” on page 298 “About class (static) members” on page 298 “Preloading class files” on page 299 “Excluding classes” on page 298 About creating a new instance of a built-in class To create an instance of an ActionScript class. color. a class defines a category of object. For information on classes and other object-oriented programming concepts. For more information on using classes that are built into Flash 8. The relationship between an instance and its class is similar to the relationship between a house and its architectural blueprints.

see Chapter 12.in loop traces each property in the results object and traces their value to the Output panel. t:"L"}. age. and TextFormat classes. see “About class (static) members” on page 298. for (var i:String in results) { trace("the value of [" + i + "] is: " + results[i]). trace(my_array. including dot and array access operators. Accessing built-in object properties Use the dot (. Put the name of the object on the left side of the dot. 3. For example. and put the name of the property on the right side. String. About working with built-in classes 297 . For more information on methods and properties. Select Control > Test movie to test the Flash document. To loop over the contents of an object: 1. For more information on operators. The following example loops over an object to display each of its properties. lastName:"G". 2. you don’t need to create an instance of a class to use its properties and methods. and t. Add the following ActionScript to Frame 1 of the main Timeline: var results:Object = {firstName:"Tommy". For more information. "oranges". see “About operators” on page 176. avg.fla. b. the following code creates a new Sound object: var song_sound:Sound = new Sound(). see Chapter 6. "bananas"). avg:0.” on page 201. age:7. Create a new Flash document and save it as forin.) operator to access the value of a property in an object. In some cases. lastName.” on page 351 For examples of working with the properties of the TextField. “Working with Text and Strings. in the following statement.” on page 381. // 3 You can also use the array access operator ([]) to access the properties of an object. For examples of working with properties of the builtin MovieClip class.For example.firstName The following code creates a new Array object and then shows its length property: var my_array:Array = new Array("apples". “Functions and Methods.. “Working with Movie Clips. such as using the array access operator for debugging purposes.336. } The previous code defines a new Object named results and defines values for firstName. TextRenderer.length). my_obj is the object and firstName is the property: my_obj. b:"R". A for. see Chapter 11.

especially those that access many of the same classes. my_sound. see Chapter 12. Class members (properties and methods) are accessed or invoked on the class name. see Math in the ActionScript 2. and TextFormat classes. Excluding classes helps you avoid duplicating classes in those files. and examples of using them. For example. String. you might want to do this if you are developing an application that uses multiple SWF files or shared libraries.0 Language Reference. not on an instance of the class. About class (static) members Some built-in ActionScript classes have class members (static members). Therefore. see Chapter 11. TextRenderer. “Working with Text and Strings. “Working with Movie Clips. For examples of working with methods of the built-in TextField. trace(largerNumber). you don’t create an instance of the class to use those properties and methods.max(10. all the properties of the Math class are static.) operator followed by the method. Excluding classes To reduce the size of a SWF file. you might want to exclude classes from compilation but still be able to access and use them for type checking. 20). The following code invokes the max() method of the Math class to determine the larger of two numbers: var largerNumber:Number = Math.” on page 381. For more information on excluding classes.” on page 351. // 20 For more information on static methods of the Math class. For example. For examples of working with methods of the built-in MovieClip class. For example. see the following topics: ■ “Preloading class files” on page 299 298 Classes .setVolume(50).About calling built-in object methods You call an object’s method by using the dot (. the following code creates a new Sound object and calls its setVolume() method: var my_sound:Sound = new Sound(this).

For example. About working with built-in classes 299 . 3.screens. 4.UIObject and mx. if your FLA file is sellStocks. It is similar for the component classes. Therefore. but before you use components. 2. because you probably want the progress bar to reflect the loading progress of all data (including classes). Save the file in the same directory as the FLA file.Slide classes from the SWF file: <excludeAssets> <asset name="mx.To exclude classes from compilation: 1. the loading time can be lengthy when you must import data. as the following procedures show. because the framework for components also loads into the first frame of a SWF file.Slide" /> </excludeAssets> For information on preloading classes. The following procedure shows you how to change the frame in which classes load into a SWF file. Preloading involves loading some of the data for a SWF file before the user starts interacting with it. you want to load the classes after other parts of the SWF file. Flash imports classes on the first frame of a SWF file when you use external classes. Name the XML file FLA_filename_exclude. Add as many as you require for your application. For example. the following XML file excludes the mx.xml.UIObject" /> <asset name="mx. Because the classes are the first data to load. see “Preloading class files” on page 299.core. where FLA_filename is the name of your FLA file without the extension. Place the following tags in the XML file: <excludeAssets> <asset name="className1" /> <asset name="className2" /> </excludeAssets> The values you specify for the name attributes in the <asset> tags are the names of classes you want to exclude from the SWF file.screens.xml. you might have problems creating a progress bar or loading animation if the classes load before the progress bar. the XML filename must be sellStocks_exclude.core. so you must deal with this data intelligently.fla. Preloading class files This section describes some of the methodologies for preloading and exporting classes in Flash 8 (including the classes that components in version 2 of the Macromedia Component Architecture use). Create a new XML file. When you build large applications. and this data is the first element to load into a SWF file.

version 2 components require classes for their functionality. Select the Flash tab. In the Export Frame for Classes text box. You cannot use any classes until the playhead reaches the frame you choose to load them into. 2. C AU T I ON 300 Classes . 3. you must preload the components in the SWF file. You must export components after the ActionScript classes that they use. type the number of a new frame to determine when to load the classes. so make sure that you deselect Export in First Frame from the component’s Linkage dialog box. so you must load components after the Export frame for ActionScript 2. If you want to preload a file that uses classes. If components do not load on the first frame.0 classes. By default. the UI components export in Frame 1 of the SWF file. For example. Do not reference any components in your ActionScript or include any components on the Stage until you load the classes for the frame you specified in the Export Frame for Classes text box. Select File > Publish Settings.To select a different frame for the classes to load into a SWF file: 1. you can create a custom progress bar for the first frame of the SWF file. you must set your components to export for a different frame in the SWF file. and click the Settings button. such as version 2 component classes. If you export for Frame 3. To accomplish this. you cannot use anything from those classes until the playhead reaches Frame 3 and loads the data. Click OK. 4.

. . . . . . . . . . . . . . . . .” on page 201. . . . . . . . . Now that you’re familiar with the basics of creating your own custom classes. . . . . . For example. . . which lets you create new classes based on an existing class. . . see “About inheritance” on page 301. Your subclass inherits all of the properties and methods of the MovieClip class. . see the following topics: About inheritance . . . . . . . For example. . Or you might create a set of classes that extends from a custom superclass. “Classes. . . . . . . . .” you learned how to write class files and how classes help you organize code into external files. .” you saw how you could create a class file to create your own custom data types. . . . . Learning how to create custom class files shows you how to move code off the timeline and into external files. . . . For more information on inheritance. . . . “Functions and Methods. “Classes. . . . . . . . . . . . . . . . . . . . . . . . see Chapter 6. . the Lettuce class might extend from the Vegetable superclass. . if you extend (or subclass) the MovieClip class. . . . Moving code into external files makes it easier to edit your code. . . 303 Using polymorphism in an application . . . . . . . . . . . 301 About writing subclasses in Flash. . . . . . . One of the benefits of OOP is that you can create subclasses of a class. because you might find yourself extending your own custom classes or existing classes so that you can add new methods and properties. . . you are creating a custom class that extends the MovieClip class. . you learn about an object-oriented programming (OOP) technique called subclassing or extending a class. . For more information on methods and properties. . . 308 8 About inheritance In Chapter 7. For more information on inheritance. . . 301 . . . . The subclass inherits all the properties and methods of a superclass. This chapter aims to show you how to write more advanced classes that extend the functionality of an existing class. . The chapter also demonstrated how you can organize class files into related packages. .CHAPTER 8 Inheritance In Chapter 7. . . . . . . . This is a useful subject. . . . .

You would have to spend a lot more time not only coding. because they let you create a series of related classes that can share functionality. hence it extends the superclass. the Siamese class. you’d have to rewrite each method and property in each separate class file. If each class wasn’t related. such as Manager. 302 Inheritance . Inheritance and subclassing are very useful in larger applications. Using subclasses lets you reuse code so that instead of re-creating all the code common to both classes you could simply extend an existing class. You could even extend a subclass. you use the extends keyword to establish inheritance between a class and its superclass. For more information on using the extends keyword. In a complex application.Your subclass typically defines additional methods and properties that you can use in your application. or it could override methods and properties that are defined in the Employee superclass. fire(). For example. Subclasses can also override (provide their own definitions for) methods inherited from a superclass. even if the functionality was the same in the fellow classes. For example. You could then create a new class called Contractor that extends the Employee class and inherits all of its methods and properties. which again adds new methods or overrides existing methods. you call the superclass’s constructor using the super statement. The Contractor class could add its own specific methods and properties. raise(). Each time that you extend an existing class. Another subclass. and so on. see “About writing subclasses in Flash” on page 303 and “About writing a subclass” on page 303. You could then create a new class called Manager. or to extend an interface. if you are within the subclass’s constructor function. see “Overriding methods and properties” on page 306. You could then create a Cat subclass that extends the Mammal class. and create a new class called Director. In ActionScript. the new class inherits all the current methods and properties of the subclass. For more information on overriding. but also debugging your application and maintaining a project if similar logic changed in multiple files. you might create a Mammal class that defines certain properties and behaviors that are common to all mammals. If a subclass overrides a method inherited from its superclass. you could create an Employee class that defines the basic methods and properties of a typical employee within a company. and promote(). The only exception to the above rule is that. which also extends the Employee class and defines additional methods and properties such as hire(). see extends statement in the ActionScript 2. could extend the Cat class. determining how to structure the hierarchy of your classes is a large part of the design process.0 Language Reference. you can no longer access the superclass’s definition within the subclass. For additional information on the extends keyword.

To create this kind of relationship between two classes. you might create a Mammal class that defines properties and methods common to all mammals. you would extend the Mammal class—that is. and static methods and properties (members)” on page 247. public function playSong(songID:Number):Void { super. For an example that creates a subclass. such as a Marsupial class. Key. About writing a subclass The following code defines the custom class JukeBox.mp3". You cannot extend the TextField class or static classes.mp3". called the superclass. which plays a song and invokes the loadSound() method that it inherits from the Sound class. For example. To specify a superclass.loadSound(song_arr[songID]. private. see the following topics: ■ ■ “About writing a subclass” on page 303 “Overriding methods and properties” on page 306 For more information on private members. a subclass can inherit the properties and methods of another class. It defines an array called song_arr and a method called playSong(). which extends the Sound class. "bach. you use the class statement’s extends clause. see “Example: Extending the Widget class” on page 304. } } About writing subclasses in Flash 303 . To create a variation of the Mammal class. class JukeBox extends Sound { public var song_arr:Array = new Array("beethoven. You can extend your own custom classes as well as many of the core and Flash Player ActionScript classes. "mozart.About writing subclasses in Flash In object-oriented programming. such as the Math. see “About public. create a subclass of the Mammal class.mp3"). you use the following syntax: class SubClass extends SuperClass {} The class you specify in SubClass inherits all the properties and methods defined in SuperClass. as follows: class Marsupial extends Mammal {} The subclass inherits all the properties and methods of the superclass. For more information on extending classes. and Mouse classes. true). including any properties or methods that you have declared to be private using the private keyword.

see super statement in the ActionScript 2.as. public function Widget() { Widget. Multiple inheritance. as shown in the following example: // not allowed class C extends A. 4. The next example demonstrates how you could create a Widget class. 2. “Interfaces.as in the same directory as the Widget class.If you don’t place a call to super() in the constructor function of a subclass.0. To create the Widget class and SubWidget subclass: 1. or inheriting from more than one class. For an example that creates a subclass.widgetCount++. B {} // **Error: A class may not extend more than one class. if the superclass takes parameters in its definition. // allowed class B extends A {} class C extends B {} You can also use interfaces to implement a limited form of multiple inheritance. the compiler automatically generates a call to the constructor of its immediate superclass with no parameters as the first statement of the function. For additional information on super. } } 3. Add the following code to the new document: class Widget { public static var widgetCount:Number = 0.” on page 313. you must create a constructor in the subclass and call the superclass with the required parameters. However.0 Language Reference. classes can effectively inherit from multiple classes if you use individual extends statements. the compiler creates an empty constructor function and then generates a call to it from the subclass. which you extend (subclass) by writing a class named SubWidget. If the superclass doesn’t have a constructor. 304 Inheritance . For more information on interfaces. Example: Extending the Widget class Class members propagate to subclasses of the superclass that defines those members. Save your changes to the ActionScript file. see Chapter 9. Create a new ActionScript file and save it as SubWidget. Create a new ActionScript file and save it as Widget. see “Example: Extending the Widget class” on page 304. is not allowed in ActionScript 2. However.

widgetCount = 2 10. Save your changes to the document. 9.0 compiler can resolve static member references within class definitions. var sw2:SubWidget = new SubWidget(). About writing subclasses in Flash 305 . you can access the widgetCount property through the SubWidget class.widgetCount = " + Widget.as. the compiler throws an error. not in your ActionScript file) as Widget. The Output panel displays the following output: Creating subwidget #1 Creating subwidget #2 Widget.widgetCount = 2 SubWidget. and save it as subWidgetTest. Control > Test Movie to test the Flash document. } } 6.widgetCount).widgetCount). Select You see this output because even though the Widget class’s constructor is never explicitly called. In SubWidget.widgetCount).fla in the same directory as the previous ActionScript class files.widgetCount property. If you try to access the static widgetCount property off of instances of the Widget or SubWidget class. Because the SubWidget class is a subclass of the Widget class. 8.as. In the subWidgetTest. like sw1 or sw2. Each call to the SubWidget constructor traces the current value of the static Widget. trace("SubWidget. 7. and the compiler rewrites the reference (in the bytecode. Create a new FLA file. This causes the Widget class’s constructor to increment the Widget class’s static widgetCount variable.widgetCount. trace("Widget. type the following code into Frame 1 of the main Timeline: var sw1:SubWidget = new SubWidget(). Save your changes to SubWidget.widgetCount = " + SubWidget.5. type the following code into the Script window: class SubWidget extends Widget { public function SubWidget() { trace("Creating subwidget #" + Widget.fla file. The ActionScript 2. the SubWidget class’s constructor calls it for you. The previous code creates two instances of the SubWidget class: sw1 and sw2.

not in your ActionScript file) as Widget.as.0 compiler resolves the reference to Widget. public function Widget() { Widget. Macromedia recommends that you always use explicit references to static member variables in your code. Using explicit references means that you can easily identify where the definition of a static member resides.If you don’t specify the class name for the Widget. Similarly. CAUTION For optimal readability of your code. You could create a new method in your superclass (Widget) and then either override the method in your subclass (SubWidget) or just use the inherited method from the Widget class. For example. consider the Widget class that you created in “Example: Extending the Widget class” on page 304. modify the existing code by adding the doSomething() method. as shown in the previous example. In Widget.widgetCount property but instead refer only to widgetCount. 2. } public function doSomething():Void { trace("Widget::doSomething()"). as follows: class Widget { public static var widgetCount:Number = 0. the ActionScript 2. Overriding methods and properties When a subclass extends a superclass. Flash generates an error telling you that static members can be accessed only directly through classes.widgetCount because SubWidget is a subclass of the Widget class. To override methods in a subclass: 1. type the following ActionScript code into the Script window. the compiler rewrites the reference (in the bytecode.widgetCount++. The following example shows how you can override existing methods in your classes.widgetCount. the subclass inherits all of the superclass’s methods and properties. Create a new ActionScript document and save it as Widget. if you refer to the property as SubWidget. Note: If you created the Widget class in an earlier example. If you try to access the static widgetCount variable from the Widget class using the sw1 or sw2 instances. } } 306 Inheritance .as.widgetCount and correctly exports that property. One of the advantages of working with classes and extending classes is that it allows you not only to provide new functionality to an existing class but also to modify existing functionality.

Create a new Flash document and save it as subWidgetTest.as. which inherits from the superclass. var sw2:SubWidget = new SubWidget(). Save your changes to SubWidget. you can use this file instead. Save your changes to the ActionScript document. type the following ActionScript code into the Script window: class SubWidget extends Widget { public function SubWidget() { trace("Creating subwidget # " + Widget. In SubWidget. Create a new ActionScript file named SubWidget. In subWidgetTest. The SubWidget’s constructor traces the superclass’s static property and calls the doSomething() method. Select This output shows that the SubWidget class’s constructor calls the constructor of its superclass (Widget). If you created the SubWidget class in “Example: Extending the Widget class” on page 304. } } 6. Save your changes to the Flash document. The Widget class now defines a constructor and a public method called doSomething(). 5. 7.as.as.3. NO TE 4. Control > Test Movie to test the Flash document.as and save it in the same directory as Widget. doSomething(). 8.fla. About writing subclasses in Flash 307 .fla in the same directory as the ActionScript documents.widgetCount). which increments the static widgetCount property. 9. type the following ActionScript into Frame 1 of the main Timeline: var sw1:SubWidget = new SubWidget(). You see the following output in the Output panel: Creating subwidget # 1 Widget::doSomething() Creating subwidget # 2 Widget::doSomething() 10. Notice that the SubWidget class’s constructor calls the doSomething() method that you defined in the superclass.

} public function doSomething():Void { trace("SubWidget::doSomething()"). Open the SubWidget class again.doSomething(). For additional information on super. 308 Inheritance .fla again. } As demonstrated. Save the SubWidget class file with the modified constructor and select Control > Test Movie to republish the Flash document. The Output panel displays the contents of the Widget class’s doSomething() method. Modify your class so that it matches the following code (add the code that’s in boldface): class SubWidget extends Widget { public function SubWidget() { trace("Creating subwidget # " + Widget.11. and modify the SubWidget class’s constructor to call the superclass’s doSomething() method (add the code that’s in boldface): public function SubWidget() { trace("Creating subwidget # " + Widget. by which classes can override methods of their superclasses and define specialized implementations of those methods. Open the SubWidget class and add a new method named doSomething(). and then open subwidgetTest. doSomething(). you can add the super keyword to call the superclass’s doSomething() method instead of the doSomething() method in the current class.widgetCount). Using polymorphism in an application Object-oriented programming lets you express differences between individual classes using a technique called polymorphism. your changes to the class file. super.0 Language Reference. You see the following output in the Output panel: Creating subwidget # 1 SubWidget::doSomething() Creating subwidget # 2 SubWidget::doSomething() The previous output shows that the doSomething() method in the SubWidget class’s constructor is calling the doSomething() method in the current class instead of the superclass. see the super entry in the ActionScript 2. Select Control > Test Movie to test the file. 14.widgetCount). } } 12. Save 13.

You then create Cat. In Mammal. Dog implements the play() method to fetch a ball. The subclasses override the play() method from the Mammal class to reflect the habits of those particular kinds of animals. } } Using polymorphism in an application 309 . } public function set speciesName(value:String):Void { this. } public function get speciesName():String { return this. } public function get gender():String { return this.For example. To use polymorphism in an application: 1. Cat implements the play() method to pounce at a ball of yarn. you might start with a class called Mammal that has play() and sleep() methods. Monkey. } public function toString():String { return "[object " + speciesName + "]". private var _name:String = "Mammal".".". Because the sleep() functionality is similar among the animals. Create a new ActionScript document and save it as Mammal._gender. The following procedure demonstrates this example in Flash. } public function sleep():String { return "Close eyes. type the following ActionScript code into the Script window: class Mammal { private var _gender:String.as. // constructor public function Mammal(gender:String) { this. Monkey implements the play() method to swing from trees. and Dog subclasses to extend the Mammal class._name = value. This document is the base class for a few different animal classes that you create in upcoming steps._gender = gender. } public function play():String { return "Chase another of my kind.as. you would use the superclass implementation. 2._name.

Save your changes to the ActionScript document. a constructor and a play() method. and sleep(). and Monkey classes. Save the ActionScript document. 310 Inheritance .as. In Cat. Next. which it uses to set the private _gender variable defined earlier. The final three methods are getter and setter methods for the mammal’s _gender and _name properties. which are used to store the animal’s gender and mammal type.as in the same directory as the two previous class files. 5.The previous class defines two private variables. which you create shortly. each of which returns string objects. gender.as class file you created in step 1. Since the Cat class extends the Mammal class. } } Notice that you are overriding the play() method in the Mammal superclass. 7. play(). Three additional public methods are also specified: toString(). the Mammal classes’s methods and properties are inherited by the Cat class. For more information on overriding. You can use the toString() method of the Mammal class to display a string representation of any Mammal instance (or any instance that extended the Mammal class). This class serves as the superclass for the Cat.as in the same directory as the Mammal. Create a new ActionScript file and save it as Cat. Create a new ActionScript document and save it as Dog. The Cat class defines only two methods. 6. type the following ActionScript code into the Script window: class Cat extends Mammal { // constructor public function Cat(gender:String) { super(gender). } public function play():String { return "Pounce a ball of yarn. speciesName = "Cat". 4.". the Mammal constructor is defined. Dog. _gender and _name. 3. The constructor takes a single parameter. see “Overriding methods and properties” on page 306.

Cat and Dog. type the following ActionScript code into the Script window: class Monkey extends Mammal { // constructor public function Monkey(gender:String) { super(gender). In Monkey.".as. Mammal. and save it as Monkey. another ActionScript document in the same directory as your other files.".as.8. speciesName = "Monkey".fla. The speciesName variable is also overridden and set to the string Dog. Similar to the previous two classes. speciesName = "Dog". your changes to the ActionScript document. type the following ActionScript code into the Script window: class Dog extends Mammal { // constructor public function Dog(gender:String) { super(gender). the Dog class extends the Mammal class and inherits all its methods and properties. Using polymorphism in an application 311 . The Dog constructor takes a single property. The Monkey class’s constructor calls the constructor for the Mammal class. 12. Save your changes to the ActionScript document. gender. Create 11. } } Notice that the Dog class is very similar in structure to the Cat class. Now that you’ve created three subclasses of the Mammal class. as well as setting speciesName to the string Monkey. which it passes to the Dog class’s parent class. except that a few of the values have changed.as. 9. } public function play():String { return "Fetch a stick. The play() method is also overridden from the parent class. In Dog. passing the gender to the Mammal’s constructor. the Monkey class extends the Mammal class. The Monkey class also overrides the behavior of the play() method. } public function play():String { return "Swing from a tree. Save 13. } } 10. create a new Flash document called mammalTest. Again.

i++) { info_txt. mammals_arr. mammals_arr. info_txt.play() + "</p>".htmlText += "<p>" + mammals_arr[i].push(new Mammal("Male")). i < len. 80). // The trace statement calls the Mammal. } The mammalTest.speciesName + "\t" + mammals_arr[i].fla code is a bit more complex than the previous classes. info_txt. info_txt.toString() method.html = true.gender + "\t" + mammals_arr[i]. info_txt. // Display Mammal info in 4 columns of HTML text using tab stops. this.push(new Cat("Male")). } function createReport():Void { var i:Number. for (i = 0.htmlText += "</textformat>".htmlText += "<b>Mammal\tGender\tSleep\tPlay</b>". trace(mammals_arr[i]). 450. Save the Flash document.14.push(new Monkey("Female")). mammals_arr.wordWrap = true. 200. 300]'>".border = true. and the following text in the Output panel: [object [object [object [object Dog] Cat] Monkey] Mammal] 312 Inheritance . createMammals() createReport() function createMammals():Void { mammals_arr. info_txt. and then select Control > Test Movie to test the document.createTextField("info_txt".length.multiline = true. 15. You see the Mammal information displayed in a text field on the Stage. 10.fla. First it imports the three animal classes.htmlText = "<textformat tabstops='[110. 10. info_txt. var len:Number = mammals_arr. } info_txt. In mammalTest. 10. type the following ActionScript code into Frame 1 of the main Timeline: var mammals_arr:Array = new Array().sleep() + "\t" + mammals_arr[i].push(new Dog("Female")).

. . . . .” before you try the tutorials and examples in this chapter. . . . These methods must be implemented when developers use each interface. . . . . . . . . . . . . . . . . . . . or build larger applications in Flash. . . . . . . . . . . . . . . . Another class can then implement the methods declared by the interface. . Therefore. . . . . . . . . . 313 Creating interfaces as data types . . . . . . . . . . . . . . . . . . . . . . . . . . and by the end of the chapter you are able to build your own interface files. . see the following topics: About interfaces . . . . . . . make sure that you read Chapter 7. . . . “Classes. This chapter walks you through a few sample interfaces. . . . interfaces are like classes whose methods are not implemented (defined)—that is. For more information on working with interfaces. . . . . . . 318 Understanding inheritance and interfaces . . 321 Example: Creating a complex interface . . . . . . . . . . . . . 313 . . . . . . . . . . . . . . . . . . . . . . Interfaces allow developers to easily identify the base methods in ActionScript classes. . When you work in teams of developers. . . . . an interface is a document that lets you declare (but not define) the methods that must appear within a class. . . . If you are not familiar with building classes. . . . . . . . they otherwise don’t “do” anything. . . . . . an interface consists of “empty” methods. . . interfaces can be very beneficial during development. . . . . . . . . . . . . . . . . . . . In ActionScript. . . . . . . . . . . . . . .CHAPTER 9 Interfaces In object-oriented programming (OOP). . .323 9 About interfaces In object-oriented programming. . . . . . . . . . . . 320 Example: Using interfaces . . . . . . . . . . . . the distinction between interface and object is only for compiletime error checking and language rule enforcement. . . .

Therefore. You can usually program successfully without using interfaces. which has methods chaseTail() and eatCatNip(). “About casting objects. So you could create a Playful interface that declares the chaseTail() and eatCatNip() methods. however. For example. You can use interfaces to implement a limited form of multiple inheritance. The ActionScript 2. see “Writing custom class files” on page 235. however. For a tutorial on creating an application with interfaces. Like Java. a class can inherit from a single parent class. scalable. and their return types. When used appropriately. This parent class can be either a core or Flash Player class or a user-defined (custom) class. One way to do this would be to create a class that defines all these methods and then have each class extend. ActionScript interfaces do exist at runtime to allow type casting (changing an existing data type to a different type). ActionScript interfaces exist at runtime to allow type casting. otherwise. this superclass. While designing the application. You create an interface that declares these methods. their parameters.” on page 111. by which a class inherits from more than one class. it doesn’t make sense to put them all into a common class hierarchy. see Chapter 4. see “Example: Using interfaces” on page 321. An interface is not an object or a class. But because the application consists of classes that are unrelated.0 does not allow a class to extend multiple classes directly but does allow a class to extend a single class and implement multiple interfaces. A better solution is to create an interface that declares the methods these classes use to communicate.An interface is not a class.0 object model does not support multiple inheritance. the Cat class could extend the Mammal class as well as a Playful class. 314 Interfaces . The interface is like a communication protocol to which all the classes must adhere. you agree on a set of methods that the different classes use to communicate. could then implement this interface and provide definitions for those methods. A Cat class. each of whom is working on a different class within the same application. in C++. but the workflow is similar to working with classes. ActionScript 2. For more information on the class workflow. suppose you are working with a team of programmers. and maintainable. this is not altogether true in ActionScript at runtime because an interface is abstract. and then have each class implement (provide its own definitions for) those methods. or inherit from. a compiler error results. For example. You can also think of an interface as a “programming contract” that you can use to enforce relationships between otherwise unrelated classes. Any class that implements this interface must provide definitions for those methods. interfaces can make the design of your applications more elegant. or any other class.

IEmployeeRecords. see Chapter 19. That is. with the following important differences: ■ Interfaces contain only declarations of methods. static and class members are not permitted.” on page 731. The following interface name. “Best Practices and Coding Conventions for ActionScript 2. see the following sections: ■ ■ ■ “About the interface keyword” on page 315 “About naming interfaces” on page 315 “Defining and implementing interfaces” on page 316 About the interface keyword The interface keyword defines an interface. uses an initial uppercase letter and concatenated words with mixed case: interface IEmployeeRecords {} Some developers start interface names with an uppercase “I” to distinguish them from classes. the same as class names. An interface is similar to a class. To use the interface keyword. not their implementation. Only public members are allowed in an interface definition. Interface names are usually adjectives.0 and Flash Player 6 or later in the Flash tab of your FLA file’s Publish Settings dialog box. not in scripts that you write in the Actions panel. such as Printable. every class that implements an interface must provide an implementation for each method declared in the interface. This is a good practice to adopt because it lets you quickly distinguish between interfaces and regular classes.0. About naming interfaces Interface names have an uppercase first letter. The get and set statements are not allowed in interface definitions. you must specify ActionScript 2. ■ ■ ■ The interface keyword is supported only when used in external script files. NO T E For more information on naming conventions. About interfaces 315 .For more information on using interfaces.

method1(). Create a new ActionScript file and save it as IMyInterface. or subinterfaces based on the original interface Creating a class that implements the interface in an external script file ■ ■ You declare an interface using the interface keyword. For a tutorial on creating an application that uses an interface. method1() and method2(). Type the following ActionScript code into the Script window: interface IMyInterface { public function method1():Void. The first method.Defining and implementing interfaces The process for creating an interface is the same as for creating a class. For example. you can define interfaces only in external ActionScript files. “Best Practices and Coding Conventions for ActionScript 2. as shown in the following example: interface IEmployeeRecords { // interface method declarations } An interface can contain only method (function) declarations. method2(). 2. the workflow for creating an interface involves the following steps: ■ ■ Defining a interface in an external ActionScript file Saving the interface file to a designated classpath directory (a location where Flash looks for classes) or in the same directory as the application’s FLA file Creating an instance of the class in another script.as. the following code declares an interface named IMyInterface that contains two methods. including parameters. and then left and right curly braces ({}). see “Example: Using interfaces” on page 321. has no parameters and specifies a return type of Void (meaning that it does not return a value). see Chapter 19. followed by the interface name. public function method2(param:String):Boolean.” on page 731. and function return types. } 3. which define the body of the interface. and specifies a return type of Boolean. parameter types. The second method. you first need to create a class that implements your new interface. Like classes. Save your changes to the ActionScript file. In order to use the interface within an application. To create a simple interface: 1. either in a Flash (FLA) document or an external script file. For more information on conventions for structuring classes and interfaces. 316 Interfaces .0. has a single parameter of type String. At a minimum.

Classes that implement a particular interface almost always include additional methods. 8.. } } 9. In the MyClass class file. You see this error message because any class that extends an interface must define each method that’s listed in the interface document. Click the Check Syntax button. The Output panel no longer displays any error messages or warnings because you have now defined the two methods. type the following ActionScript code into the Script window: class MyClass { } In order to instruct the custom class (MyClass) to use your interface (IMyInterface). as shown in the following snippet: class MyClass implements IMyInterface { public function method1():Void { // . which specifies that a class must define all the methods declared in the interface (or interfaces) that you implement. public function method2(param:String):Boolean { // . variables.as (add the boldface code) so it matches the following snippet: class MyClass implements IMyInterface { } You place the implements keyword after the class name... as well as those methods’ properties and return types. }.as document and click Check Syntax. 5. return true. Modify the ActionScript code in MyClass. Create a new ActionScript file and save it as MyClass.as. 7. and write ActionScript code for the method1() and method2() methods. The interface file only outlines the minimum methods that you must implement.as in the same directory as the IMyInterface. you need to use the implements keyword. Modify the MyClass document again (add the boldface code). Flash displays an error in the Output panel stating that MyClass must implement method X from interface IMyInterface. The class file that you create is not limited to the public methods that you define in the interface file. Save the MyClass. and getter and setter methods.4. 6.. About interfaces 317 .

as. Creating interfaces as data types Like a class. Save your changes to the ActionScript file. You can consider any class that implements an interface to be of the type that is defined by the interface. private function illegalPrivateMethod():Void. 2. In this document.as in the same directory as IMovable. public var illegalVar:String. see “About naming class files” on page 265. // Compiler error. This is useful for determining whether a given object implements a given interface. Functions that you declare in an interface cannot contain curly braces. 4. To create an interface as a data type: 1.Interface files cannot contain any variable declarations or assignments. Create a new ActionScript document and save it to your hard disk as IMovable. consider the interface IMovable. you create a Box class that implements the IMovable interface that you created in an earlier step. In IMovable. For example.as. Private methods are not allowed in interfaces.as. which you create in the following example. Function bodies not allowed in interfaces. For example. public function get illegalGetter():String. } For a tutorial demonstrating how to create a complex interface. Variable declarations not allowed in interfaces. public function illegalMethod():Void { } // Compiler error. the following interface does not compile: interface IBadInterface { // Compiler error. an interface defines a new data type. Getters/setters are not allowed in interfaces. type the following ActionScript code into the Script window: interface IMovable { public function moveUp():Void. 318 Interfaces . see “Example: Using interfaces” on page 321. public function moveDown():Void. Create a new ActionScript document and save it as Box. // Compiler error. The rules for naming interfaces and storing them in packages are the same as those for classes. } 3.

Select Frame 1 of the Timeline. public var yPos:Number. you can cast an expression to an interface type or other data type at runtime.” on page 111.5. and then select Control > Test Movie to test the SWF file. Unlike Java interfaces. } Creating interfaces as data types 319 .fla: if (IMovable(newBox) != null) { newBox. This is useful if you want to ensure that a particular object implements a certain interface. } else { trace("box instance is not movable"). If the expression is an object that implements the interface or has a superclass that implements the interface. For more information on type casting. public function Box() { } public function moveUp():Void { trace("moving up"). see Chapter 4. // method definition } } 6. This ActionScript code creates an instance of the Box class. Create a new Flash document named boxTest. 9. the object is returned. “About casting objects.as. In Box. which you declare as a variable of the Box type. ActionScript interfaces exist at runtime. Save your changes to the Flash document. 7. Otherwise. // method definition } public function moveDown():Void { trace("moving down"). null is returned. and then type the following ActionScript code into the Actions panel (or Script window): var newBox:Box = new Box(). and then save it in the same directory as the two previous ActionScript documents. type the following ActionScript code into the Script window: class Box implements IMovable { public var xPos:Number. Add the following code at the end of the ActionScript code in boxTest. In Flash Player 7 and later. which allows type casting.moveUp(). 10.fla. 8. Save your changes to the ActionScript document. open the ActionScript editor.

} 3.moveUp() method is called.This ActionScript code checks whether the newBox instance implements the IMovable interface before you call the moveUp() method on the object. Save your changes to the ActionScript file.as in the same directory as the two previous files. the Box. and the text “moving up” appears in the Output panel. To extend an interface: 1. type the following ActionScript code into the Script window: interface Ia { public function f1():Void.as in the same folder as the Ia. 4. and then select Control > Test Movie to test the SWF file. 11. Save your changes to the ActionScript file. In Ia. One consideration you need to make when extending interfaces is that you receive error messages in Flash if multiple interface files declare functions with the same names but have different parameters or return types.as. public function f2():Void. The following example demonstrates how you can subclass an interface file using the extends keyword. } 6. see Chapter 4.” on page 111.as. 320 Interfaces . 7. This can be very useful in larger projects for which you might want to extend (or subclass) an existing interface and add additional methods. 2.as file you created in step 1.as. These methods must be defined by any classes implementing that interface. 5. For more information about casting. Understanding inheritance and interfaces You can use the extends keyword to create subclasses of an interface. Create a new ActionScript file and save it as ClassA. Save the Flash document. “About casting objects. and then save it as Ia. public function f9():Void. In Ib. Because the Box instance implements the IMovable interface. Create a new ActionScript file and save it as Ib. Create a new ActionScript file. type the following ActionScript code into the Script window: interface Ib extends Ia { public function f8():Void.

Save the changes that you made to the ActionScript interface file.0. Create a new ActionScript file in the same directory as the IDocumentation. type the following ActionScript code into the Script window: interface IDocumentation { public function downloadUpdates():Void.. Id {. which extends Ia.8. Save your class file and click the Check Syntax button above the Script window. NO TE If you want your ClassA class to implement multiple interfaces in the previous example..as file. } 3. Example: Using interfaces 321 .as. Create a new ActionScript file and save it as IDocumentation.}. public function checkForUpdates():Boolean. and save this new file as FlashPaper. Classes are only able to extend one class in ActionScript 2. you would simply separate the interfaces with commas. Example: Using interfaces In this example you create a simple interface that you can reuse between many different classes.as. 2. public function f1():Void { } public function f2():Void { } // f8() and f9() are defined in interface Ib. public function searchHelp(keyword:String):Array. In IDocumentation. you would use code similar to the following: class ClassA extends ClassB implements Ib. To build an interface: 1. Or. Flash doesn’t generate any error messages as long as all four methods are defined and match the definitions from their respective interface files. Ic. public function f8():Void { } public function f9():Void { } } 9. although you can use classes to implement as many interfaces as you want.as. type the following ActionScript code into the Script window: class ClassA implements Ib { // f1() and f2() are defined in interface Ia. 4. In ClassA.as. if you had a class that extended a superclass and implemented multiple interfaces.

8. and add the following boldface line of code (below the searchHelp() method): interface IDocumentation { public function downloadUpdates():Void.as. } 322 Interfaces .3. In FlashPaper. Open the FlashPaper. 7. The interface file defines only a set of minimum methods that must appear within any class that implements that interface. } 9.as class file again and modify the existing ActionScript code so that it matches the following code: class FlashPaper implements IDocumentation { private static var __version:String = "1. and then click Check Syntax again. N OT E 10.2. class FlashPaper implements IDocumentation { Total ActionScript Errors: 1 Reported Errors: 1 This error appears because the current FlashPaper class doesn’t define any of the public methods that you defined in the IDocumentation interface.5. Save the changes that you made to the ActionScript file. public. or private variables or methods as you want to the FlashPaper class file. Click the Check Syntax button for your ActionScript class.4". public function checkForUpdates():Boolean. public function addComment(username:String. You see an error that’s similar to the following message: **Error** path\FlashPaper. public function searchHelp(keyword:String):Array.as: Line 1: The class must implement method 'checkForUpdates' from interface 'IDocumentation'. public function downloadUpdates():Void { }. You can add as many additional static. This time you don’t see any errors appear in the Output panel. public function searchHelp(keyword:String):Array { return [] }. type the following ActionScript code into the Script window: class FlashPaper implements IDocumentation { } 6. comment:String):Void. }. public function checkForUpdates():Boolean { return true. Save your changes to the ActionScript file. Open the IDocumentation interface document again.

you can easily identify the methods that are required within the new class. Example: Creating a complex interface 323 . and then reopen the FlashPaper. as well as how to have interfaces extend other interfaces to create more complex data structures. */ } 14.as and click the Check Syntax button and you should no longer receive any errors. you created a class-based on the IDocumentation interface file. You save all of the files you create for this tutorial in this directory. Click You see the previous error because the FlashPaper. Create a new folder called complexInterface and save InterfaceA. the Check Syntax button. In this section you create a new class that also implements the IDocumentation interface. which inserts comment into database. and you see a new error message in the Output panel: **Error** path\FlashPaper. To create a complex interface: 1. Create a new ActionScript document and save it as InterfaceA.as: Line 1: The class must implement method 'addComment' from interface 'IDocumentation'. Add the following method in the FlashPaper class: public function addComment(username:String. you must either add the addComment() method to the FlashPaper class or remove the method definition from the IDocumentation interface file.as. In the previous section. Save your changes to the interface file. comment:String):Void { /* Send parameters to server-side page. although it adds some additional methods and properties. 2. 13.11. This tutorial demonstrates the usefulness of using interfaces because if you want to create another class that extends the IDocumentation interface. To fix this error message.as class file no longer defines all the classes that you outlined in the interface file. In this tutorial you learn how to create a simple interface file and how to write a class that implements multiple interfaces. Example: Creating a complex interface The following example shows several ways to define and implement interfaces.as document.as to this directory. class FlashPaper implements IDocumentation { Total ActionScript Errors: 1 Reported Errors: 1 12. Save the changes to FlashPaper.

324 Interfaces . 8.fla in the complexInterface directory.as interface InterfaceA { public function k():Number.as class ClassB implements InterfaceA { public function k():Number { return 25. // 12 7.as in the complexInterface directory. public function n(z:Number):Number. This class file tests the ClassB class you created previously. var myB:ClassB = new ClassB(). type the following ActionScript code on Frame 1 of the Timeline: // filename: classbTest. ClassB. } } 5. Save the ActionScript document and then create a new ActionScript document named ClassB.k()). // 25 trace(myB. 6.fla import ClassB.as.fla. This class file implements the InterfaceA interface that you created in step 1. trace(myB. } 4.as document and then create a new Flash document and save it as classbTest.as and save it in the complexInterface directory. Save your changes to the ClassB. In ClassB. type the following ActionScript code into the Script window: // filename: InterfaceA. Create a new ActionScript file and save it as ClassC. 9. In classbTest. type the following ActionScript code into the Script window: // filename: ClassB.as. which are the results of the k() and n() methods in the ClassB class.3. 25 and 12. and then select Control >Test Movie to test the Flash document.as implements the InterfaceA interface you created previously. The Output panel displays two numbers. Save your changes to the Flash document. In Interface.n(7)). } public function n(z:Number):Number { return (z + 5).

and then create a new ActionScript document and save it in the complexInterface directory as ClassD. The ClassD class must include method implementations for each of the methods listed in each of the interface files. When you create classes that implement an interface.as.as. Flash displays an error message in the Output panel that says the current class must implement the n() method defined in the InterfaceA interface. In ClassC. This class implements both the InterfaceA interface and the InterfaceB interface you created in earlier steps. InterfaceB.as interface InterfaceB { public function o():Void. } 12. In ClassD.as file. } // **Error** The class must also implement method 'n' from interface 'InterfaceA'. type the following ActionScript code into the Script window: // filename: ClassC. This Flash document tests the ClassD class that you created previously.10. } If you click the Check Syntax button for the ClassC class file. Save your changes to the InterfaceB. Create a new ActionScript document and save it as InterfaceB. } } 15. type the following ActionScript code into the Script window: // filename: InterfaceB. } public function o():Void { trace("o").as class ClassC implements InterfaceA { public function k():Number { return 25. 11.as class ClassD implements InterfaceA.fla. it is important that you define methods for each entry in the interface. and then create a new Flash document and save it as classdTest.as. Example: Creating a complex interface 325 . type the following ActionScript code into the Script window: // filename: ClassD.as document. } public function n(z:Number):Number { return (z * z). In 13. InterfaceB { public function k():Number { return 15. Save your changes to the ClassD. 14.as in the complexInterface directory.as.

as in the complexInterface directory. // 15 trace(myD. trace(myD. // 49 myD. In InterfaceC.k() method. In ClassE. The values 15 and 49 and the letter o should be displayed in the Output panel. Save your changes to the classdTest. 21. InterfaceC { public function k():Number { return 15. ClassD.o(). type the following ActionScript code into the Script window: // filename: InterfaceC. } public function o():Void { trace("o").as.16. and then create a new Flash document and save it as classeTest. } 20.o() methods. type the following ActionScript code into the Script window: // filename: ClassE. } public function p():Void { trace("p"). and ClassD. These values are the results of the ClassD. add the following ActionScript code on Frame 1 of the Timeline: // filename: classdTest.fla import ClassD. } } 22. var myD:ClassD = new ClassD(). 326 Interfaces . } public function n(z:Number):Number { return (z + 5).k()).n(). This class implements two interfaces. // o 17.Save your changes to the ActionScript file and then create a new ActionScript file and save it as ClassE. and it adds a new method definition.as.n(7)). 19.Save your changes to the ActionScript document.as.as interface InterfaceC extends InterfaceA { public function p():Void. This interface extends the InterfaceA interface you created earlier. InterfaceB and InterfaceC.fla.fla in the complexInterface directory. respectively. In classdTest.fla file and then select Control > Test Movie to test the file. Create a new ActionScript document and save it as InterfaceC.as class ClassE implements InterfaceB. 18.

and ClassE.k()). InterfaceC extends InterfaceA. ClassE. This means that all of its defined methods. Although the InterfaceB and InterfaceC interfaces only define the o() and p() methods. // o myE. type the following ActionScript code on Frame 1 of the Timeline: // filename: classeTest. must also be implemented.In classeTest.p() methods.o(). and then select Control > Test Movie to test the SWF file.Save the Flash document. o. Since the ClassE class implemented both the InterfaceB and InterfaceC interfaces.n(7)).n(). k() and n(). trace(myE.23. var myE:ClassE = new ClassE(). and p display in the Output panel.k(). 12. // 12 myE.p(). These values are the values that return from the ClassE. The values 15. // p 24. ClassE. // 15 trace(myE.fla import ClassE.fla. Example: Creating a complex interface 327 .o(). each method from the two interface files must be defined.

328 Interfaces .

You can handle events in ActionScript in several ways: ■ ■ ■ 10 “Using event handler methods” on page 330 “Using event listeners” on page 332 “Using button and movie clip event handlers” on page 337. Or when an XML file finishes loading over the network. However. the event handler is not available after the new content is loaded. An event such as a mouse click or a keypress is called a user event because it occurs as a result of direct user interaction. you must use event handlers—ActionScript code associated with a particular object and event. “Broadcasting events from component instances” on page 342 ■ Using event handlers with loadMovie (MovieClip. such as the initial appearance of a movie clip on the Stage. or if you create a dynamic handler using an event handler method such as onPress (MovieClip. you might advance the playhead to the next frame.onPress handler). In order for your application to react to events. 329 . the contents of that file might appear in a text field. For example. and then you call loadMovie(). on handler and onClipEvent handler. when a user clicks a button on the Stage. An event that Flash Player generates automatically. the event handler is still available after the new content is loaded. if you use onClipEvent handler or on handler to attach an event handler to a movie clip.CHAPTER 10 Handling Events Events are actions that occur while a SWF file is playing. is called a system event because it isn’t generated directly by the user.loadMovie method) can be unpredictable. If you attach an event handler to a button using on(). and then call loadMovie() on that movie clip. specifically.

. . . . . .343 Scope of the this keyword . . . . . . . . . ContextMenu. . . . . . . . . . . . . . . . . SharedObject. . . . . . . . . . . . . . . . . . . . . . For more information about the event handlers they provide. . and the function you assign to the event handler. . . To have your application respond to the event. . .342 Creating movie clips with button states . .eventMethod = function () { // Your code here. . . . . 347 Using the Delegate class . . . . . . . . . . . . . An event handler consists of three parts: the object to which the event applies. . . . . . . . . . . . . . The following ActionScript classes are examples of classes that define event handlers: Button. . . . . . . Sound. . . . 330 Using event listeners . . .342 Event handler scope . . . . . . . . . . . . . . . . . . Stage. . . . . . . . . . . . . . . . responding to event. . . . . 337 Broadcasting events from component instances . . . . .0 Language Reference. . . . . LoadVars. . . . . . . . . . . . event handler methods are undefined: when a particular event occurs. Unlike other methods of a class. . . . . . see the following sections: Using event handler methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . but your application doesn’t respond further to the event. Mouse. The following example shows the basic structure of an event handler: object. . . . . . . . 347 Using event handler methods An event handler method is a method of a class that is invoked when an event occurs on an instance of that class. Key. . . . . . . . . . . . . . . The word handler is added in the title of each event handler. . . . . . For example. . . . . . . . . . . . . . . . however. . . . . . . .332 Using event listeners with components . . . . . . . you define a function with the function statement and then assign that function to the appropriate event handler. . . its corresponding event handler is invoked. . . . . . . . MovieClipLoader. . . . Selection. . . . . . . . . . . . . . . . . . . . . . . . . . . the name of the object’s event handler method. . . . . the MovieClip class defines an onPress event handler that is invoked whenever the mouse is pressed on a movie clip object. . . . . . . . . . . . . . . . . . The function you assign to the event handler is then automatically invoked whenever the event occurs. . LocalConnection. . . . MovieClip. . . . . . you don’t invoke an event handler directly. . TextField. . . . . . . . . . . . . . . . . . . . . . . . . . see the entries for each class in ActionScript 2. . . . . . . . By default. . . XML and XMLSocket. } 330 Handling Events .For more information on handling events. . . . . . . . . . . . . . . . . . Flash Player invokes it automatically when the appropriate event occurs. . . ContextMenuItem. . .335 Using button and movie clip event handlers . . .

function goNextFrame() { nextFrame().type = "input". // Correct.onPress = goNextFrame. For example.onPress = goNextFrame(). For example.onPress = function () { nextFrame(). the nextFrame() function is assigned to an event handler for onPress.type = "input". 20). 200. to the onPress event handler: // Incorrect! next_btn. my_txt. 200.text = "I just lost keyboard focus". myOther_txt. 100. } Assigning a function reference In the previous code. my_txt. next_btn. myOther_txt. myOther_txt. as shown in the following example: // Assign a function reference to button's onPress event handler. Some event handlers receive passed parameters that provide information about the event that occurred. 10. the following code inserts some text into a text field that no longer has keyboard focus: this. this. 10. 50.border = true. 20). You can also assign a function reference (name) to an event handler method and later define the function. The following code assigns a function to the button’s onPress event handler. this function advances the playhead to the next frame in the current timeline: next_btn.border = true.onSetFocus event handler is invoked when a text field instance gains keyboard focus. // Define goNextFrame() function.For example. suppose you have a button named next_btn on the Stage. the TextField. } Notice in the following example that you assign the function reference. not the function’s return value.onPress = goNextFrame. 10.onSetFocus = function(my_txt:TextField) { my_txt.createTextField("myOther_txt". Receiving passed parameters Using event handler methods 331 .createTextField("my_txt". 99. next_btn. }. This event handler receives a reference to the text field object that previously had keyboard focus.

sets transparency when you click the movie clip. You can define an event handler in a new subclass that you can then reuse for various objects by linking any symbol in the library of the extended class to the new subclass. you can register a movie clip object to receive onResize notifications from the Stage._alpha -= 10. the following code creates a new movie clip instance (newclip_mc) and then assigns a function to the clip’s onPress event handler: this. class FadeAlpha extends MovieClip { function onPress() { this. "newclip_mc".Event handlers for runtime objects You can also assign functions to event handlers for objects you create at runtime. You can register multiple listener objects to receive events from a single broadcaster. For example. called a listener object. newclip_mc.” Using event listeners Event listeners let an object. “Classes. The following code overrides the MovieClip class’s onPress event handler with a function that decreases the transparency of the movie clip: // FadeAlpha class -. For example. } For more information.attachMovie("symbolID".onPress = function () { trace("You pressed me"). and you can register a single listener object to receive events from multiple broadcasters. receive events broadcast by another object. called a broadcaster object. } } For specific instructions on extending an ActionScript class and linking to a symbol in the library. For information on writing and working with custom classes. The broadcaster object registers the listener object to receive events generated by the broadcaster. or a button instance could receive onChanged notifications from a text field object. see Chapter 7. 332 Handling Events . Overriding event handler methods By creating a class that extends an ActionScript class. see “Creating movie clips at runtime” on page 360. you can override event handler methods with the functions that you write. 10). see the examples in “Assigning a class to symbols in Flash” on page 279.

Using event listeners 333 . listenerObject. On the Macintosh. ■ In Windows. addListener(). in the Samples folder on your hard disk.eventName = function(eventObj:Object) { // Your code here }. ■ Event listener model The event model for event listeners is similar to the model for event handlers (see “Using event handler methods” on page 330).addListener(listenerObject). ■ The following code outlines the event listener model: var listenerObject:Object = new Object(). stagesize. unlike event handler methods. see each class entry in the ActionScript 2. the different pieces of code have conflicts over control of that single XML. For more information on event listeners. To see which listeners are available for a class. You can find a sample source file. Mouse. can be problematic when various pieces of code are listening to the same event. This sample demonstrates how the Stage. and TextField. see the following topics: ■ ■ “Event listener model” on page 333 “Event listener example” on page 334 The Stage class can broadcast events. Stage.onLoad(). not the object that broadcasts the event. broadcasterObject. lets you have multiple pieces of code listen to the same event without conflict.0 Language Reference. You call a special method of the broadcaster object. browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\StageSize. with two main differences: ■ You assign the event handler to the listener object.scaleMode property affects the values of Stage.The listener-broadcaster model for events. Event models that do not use the listener/broadcaster model. such as XML.onLoad callback function reference. which registers the listener object to receive its events.height when the browser window is resized. The following ActionScript classes can broadcast events: Key.fla. With the listener/broadcaster model. Selection.width and Stage. MovieClipLoader. you can easily add listeners to the same event without worrying about code bottlenecks. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/StageSize.

334 Handling Events . Select Frame 1 in the Timeline and open the Actions panel (Window > Actions). Make sure the Show Border Around Text option is not selected for this text field. or button instance on the Stage. broadcasterObject. You assign a function to the event listener that responds to the event in some way. and the listener object. and the border of the text field that does not have focus is disabled. 2. Last. passing the listener object to the addListener() method. the border of the text field that receives keyboard focus is enabled (appears). 4. Create another input text field below the first one. listenerObject. Select the text field. with a property eventName. To unregister a listener object from receiving events. movie clip. you call the addListener() method on the broadcaster object. You can register multiple listeners to one event broadcaster. passing it the name of the event to remove. Event listener example The following example shows how to use the onSetFocus event listener in the Selection class to create a simple focus manager for a group of input text fields. and then in the Property inspector.removeListener(listenerObject). or it can be an instance of any ActionScript class. In this case. select Input from the Text Type pop-up menu and select the Show Border Around Text option. Using the Text tool. such as an existing object.The code starts with an object. you call the removeEventListener() method of the broadcaster object. To create a simple focus manager with event listeners: 1. The eventName property is an event that occurs on broadcasterObject. a custom movie clip could implement the listener methods for Stage listeners. You can continue to create input text fields. You could even have one object that listens to several types of listeners. create a text field on the Stage. which then broadcasts the event to listenerObject. 3. For example. Your listener object can be any object.

and type my_ldr in the Instance Name text box in the Property inspector. var focusListener:Object = new Object(). To register the focusListener object to receive events from the Selection object.onSetFocus = function(oldFocus_txt:TextField. enter the following code in the Actions panel: // Creates listener object. you have a slightly different event-listener syntax. focusListener. click in the first text field. // Defines function for listener object. Using event listeners with components When you work with components. To listen for Loader component events: 1. and press the Tab key to switch focus between fields. The following example shows how you can use event listeners to monitor the download progress of a dynamically loaded image.5. Selection. Components generate events. Select the loader.border = false.border = true. Using event listeners with components 335 . and you must specifically listen for these events by using either a listener object or a custom function. To create an object that listens for focus notification from the Selection class. add the following code to the Actions panel: // Registers focusListener with broadcaster. The function sets the border property of the text field that does not have focus to false. newFocus_txt:TextField) { oldFocus_txt. 2. 7.addListener(focusListener). focusListener. and sets the border property of the text field that has focus to true. Drag an instance of the Loader component onto the Stage from the Components panel. Test the application (Control > Test Movie). } This code creates an object named focusListener that defines an onSetFocus property and assigns a function to the property. newFocus_txt. The function takes two parameters: a reference to the text field that does not have focus and one to the text field that has focus. 6.

their code is executed. loaderListener). Secondly. Select Control > Test Movie to test the SWF file. and debugging text is displayed in the Output panel if you test the SWF file in the authoring tool. System. var loaderListener:Object = new Object(). This ActionScript code defines a listener object named loaderListener. the progress event might be dispatched numerous times.bytesTotal + " bytes loaded"). you must specify the specific event you want to listen for as well as the event listener object or function. my_ldr. // progress trace("\t" + evt_obj.target. which listens for two events: progress and complete. you must use the addEventListener() method instead of calling addListener(). The image downloads into the Loader instance on the Stage. Most notably.security. Next you tell the my_ldr instance to listen for each of the two specified events (progress and complete) and specify the listener object or function to execute when the event is dispatched.helpexamples. loaderListener).com/flash/images/image1. Depending on the size of the image you download. 336 Handling Events .helpexamples.jpg").complete = function(evt_obj:Object):Void { trace(evt_obj.type).addEventListener("complete". which triggers the image to begin downloading. When you work with components and dispatch events.target.type).progress = function(evt_obj:Object):Void { trace(evt_obj. loaderListener.com").addEventListener("progress".allowDomain("http://www. and then several messages are displayed in the Output panel. Finally. Add the following code to Frame 1 of the main Timeline. 4. the Loader.bytesLoaded + " of " + evt_obj.load() method is called. When each of these events are dispatched. // complete } my_ldr.3. the syntax is slightly different from the event listeners in previous examples. whereas the complete event is only dispatched after the image is completely downloaded.load("http://www. } loaderListener. and if the image was cached on the user’s local system. my_ldr.

my_ldr.bytesTotal + " bytes loaded").com"). you can use a custom function. as in the first procedure under “Using event listeners with components” on page 335.allowDomain("http://www.click. which must be attached to component instances and are discussed in Using Components.hide.Movie Clip. my_ldr.helpexamples. N OT E NO T E Using button and movie clip event handlers You can attach event handlers directly to a button or movie clip instance on the Stage by using the onClipEvent() and on() event handlers. see “Attaching code to objects” on page 746. progressListener).type). and then enter code in the Actions panel.png"). For guidelines about using code that’s attached to button or movie clip instances. such as SimpleButton.load() method is called.Instead of using a listener object. Do not confuse button and movie clip event handlers with component events. completeListener). The onClipEvent() event handler broadcasts movie clip events. This means that the content might display and the complete event might not be caught.addEventListener("progress".target.load() method before you specify the event listeners.Button or Actions Panel .target. function progressListener(evt_obj:Object):Void { trace(evt_obj. // progress trace("\t" + evt_obj. UIObject.load("http://www. and UIObject.helpexamples.reveal.bytesLoaded + " of " + evt_obj. the event listeners are always added before the Loader. the load might complete before the event listeners are fully defined. click the button or movie clip instance on the Stage to bring it in focus.addEventListener("complete". and the on() event handler handles button events. To attach an event handler to a button or movie clip instance. // complete } In the previous examples. The title of the Actions panel reflects that code will be attached to the button or movie clip: Actions Panel .type).security.com/flash/images/image1. } function completeListener(evt_obj:Object):Void { trace(evt_obj. Using button and movie clip event handlers 337 . The code in the previous example could be rewritten as follows: System. If you call the Loader. my_ldr.

For more information. see “Using event handler methods” on page 330 and “Attaching code to objects” on page 746. in some cases. the SWF file plays and the object rotates. use event handler methods or event listeners. Depending on when and what kinds of events you want to invoke. NO TE ■ ■ ■ For more information on button and movie clip event handlers. or both techniques of event handling. the button can have an on(press) handler that tells the SWF file to play. Instead. see “Creating movie clips with button states” on page 342. for which you define a function that tells an object on the Stage to rotate. For information on specifying events for on() and onClipEvent(). for example). You cannot attach onClipEvent() or on() to movie clip instances that are created at runtime (using the attachMovie() method. You can also use on() with movie clips to create movie clips that receive button events. the scope of variables and objects in on() and onClipEvent() handlers is different than in event handler and event listeners. event handler methods. Using the on() and onClipEvent() methods doesn’t conflict with using event handler methods that you define. 338 Handling Events . use different techniques to handle events without conflict. see “Specifying events for on or onClipEvent methods” on page 340. and the same button can have an onPress() method.) Attaching onClipEvent() and on() handlers is not a recommended practice. For more information. For example. However. suppose you have a button in a SWF file. When you click the button. you should put your code in frame scripts or in a class file. as demonstrated throughout this manual. you can use the on() and onClipEvent() methods. See “Event handler scope” on page 343.You can attach onClipEvent() and on() only to movie clip instances that have been placed on the Stage during authoring. (See “Using event handler methods” on page 330 and “Using event listeners” on page 332. To attach event handlers to objects created at runtime. see the following topics: “Using on and onClipEvent with event handler methods” on page 338 “Specifying events for on or onClipEvent methods” on page 340 “Attaching or assigning multiple handlers to one object” on page 341 Using on and onClipEvent with event handler methods You can.

} 7. Select the Selection Tool. 2."). you should put your code in frame scripts or in a class file..onPress = function() {.. Instead. Attaching onClipEvent() and on() handlers is not a recommended practice. Create a new Flash document and save it as handlers. Select the Rectangle Tool and draw a large square on the Stage.. }. Enter a symbol name for the box.}")..onPress = function() { trace("box_mc. 3. NO T E Using button and movie clip event handlers 339 ...} box_mc. 6. When you click the movie clip symbol on the Stage.}.}. 5. Add the following ActionScript directly on the movie clip symbol on the Stage: on (press) { trace("on (press) {. Add the following ActionScript to Frame 1 of the main Timeline: box_mc. the following output is sent to the Output panel: on (press) {. as demonstrated throughout this manual.fla. Select Control > Test Movie to test the Flash document. see “Using event handler methods” on page 330 and “Attaching code to objects” on page 746. set the type to Movie clip and click OK. For more information.onPress = function() {. double-click the square on the Stage. 4. and press F8 to launch the Convert to Symbol dialog box. Give the movie clip on the Stage an instance name of box_mc.. 8..To use an on handler and onPress event handler: 1.

For more information on adding keypress interactivity to your applications. see “Using event handler methods” on page 330 and “Attaching code to objects” on page 746.0 Language Reference. For example. Instead. For example. you could use the following code format. and add the following code to the Actions panel: on (keyPress "<Enter>") { trace("Enter Pressed").Specifying events for on or onClipEvent methods To use an on() or onClipEvent() handler. rollOut) { trace("You rolled over. and add the following code to the Actions panel: on (keyPress "3") { trace("You pressed 3") } Or. the following code traces a string when you press the number 3 on the keyboard. For a complete list of events supported by the on() and onClipEvent() event handlers. or rolled out"). the following on() event handler executes whenever the user clicks the button to which the handler is attached: on (press) { trace("Thanks for pressing me. For more information. NO T E 340 Handling Events . see Key. Select a button or movie clip instance. if you want to trace when the Enter key is pressed by a user. } You can also add key press events using on() handlers. as demonstrated throughout this manual. Select a button or movie clip instance. separated by commas. and press the Enter key to see the string trace to the Output panel. 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. } You can specify two or more events for each on() handler. Attaching onClipEvent() and on() handlers is not a recommended practice. the following on() handler attached to a button executes whenever the mouse rolls over and then off the button: on (rollOver. see on handler and onClipEvent handler in the ActionScript 2. you should put your code in frame scripts or in a class file. select Control > Disable Keyboard Shortcuts and try again. If nothing traces. For example."). } Select Control > Test Movie. The ActionScript in a handler executes when either of the events specified by the handler occurs.

To assign multiple handlers to an object: 1. For more information. see “Using event handler methods” on page 330 and “Attaching code to objects” on page 746.onPress = function() { target_mc.jpg". }.unloadMovie() } onClipEvent (load) { trace("I've loaded"). Instead.fla. } onClipEvent (unload) { trace("I've unloaded").onLoadError = function(target_mc:MovieClip) { trace("error downloading image"). the second executes when the movie clip is unloaded from the Stage. target_mc. For example. as demonstrated throughout this manual.addListener(mclListener). The code attaches the onPress and onRelease handlers to a movie clip instance. The first executes when the movie clip first loads (or appears on the Stage).stopDrag(). img_mcl. Create a new Flash document. mclListener.createEmptyMovieClip("img_mc". } var img_mcl:MovieClipLoader = new MovieClipLoader().startDrag(). img_mcl.onRelease = function() { target_mc.com/flash/images/image1. and add the following code in the Actions panel: this.onLoadInit = function(target_mc:MovieClip) { target_mc. you could attach the following onClipEvent() handlers to the same movie clip instance. and name it assignMulti. 10).Attaching or assigning multiple handlers to one object You can also attach more than one handler to an object if you want different scripts to run when different events occur. Select Frame 1 of the Timeline. you should put your code in frame scripts or in a class file. see the following example. var mclListener:Object = new Object(). NO TE To attach multiple handlers to one object using code that’s placed on the timeline. } Attaching onClipEvent() and on() handlers is not a recommended practice. 2. }.helpexamples. on (press) { this. } mclListener. Using button and movie clip event handlers 341 .loadClip("http://www. img_mc).

4. Enter a symbol name of mcbutton. Select Control > Test Movie to test the document. 5.hitArea property) property. Over. and Down) in a movie clip by adding the frame labels _up. Creating movie clips with button states When you attach an on() handler to a movie clip. Broadcasting events from component instances For any component instance. the movie clip responds to mouse events in the same way as a button. The image loads into the img_mc instance. Create a new layer above the default layer and labels layer. 8. draw a small rectangle (approximately 100 pixels wide by 20 pixels high) on the Stage. Double-click the movie clip symbol on the Stage to enter symbol-editing mode. or assign a function to one of the MovieClip mouse event handlers for a movie clip instance. To designate the hit area that a movie clip uses. you can specify how an event is handled. 3.fla. 342 Handling Events . you use the hitArea (MovieClip.3. _over. Create a new Flash document and save it as mcbutton. For more information. and _down to the movie clip’s timeline. To create button states in a movie clip: 1. Double-click the shape with the Selection tool and press F8 to launch the Convert to Symbol dialog box. see “Handling Component Events” in Using Components. Component events are handled differently than events broadcast from native ActionScript objects. 6. the playhead is sent to the frame with the appropriate frame label. Enter a frame label of _up in the Property inspector. and click OK. You can also create automatic button states (Up. When the user moves the mouse over the movie clip or clicks it. 2. set the symbol type to movie clip. and the onPress() and onRelease() event handlers let you drag the image around the Stage. Using the Rectangle Tool. 7. Create a new layer in the movie clip’s timeline and rename the new layer labels.

do one of the following: ■ 12. To make the movie clip respond to mouse events. Rename the new layer actions and add the following ActionScript to Frame 1 of the movie clip’s timeline: stop(). Add a stop() action on Frame 10 of the actions layer. ActionScript 1.0 and ActionScript 2. Click the movie clip instance and the playhead automatically goes to the movie clip’s _down state. all three layers. Event handler scope The scope. Select 11. 10. the rectangle on Frame 10 and use the Property inspector to select a different fill color. as discussed in “Using button and movie clip event handlers” on page 337). and add a frame label of _down in the Property inspector. Frame 10.0 examples. but on() and onClipEvent() handlers do not. Move your mouse pointer over the movie clip instance on the Stage and the movie clip automatically goes to the movie clip’s _over state. Assign a function to one of the movie clip object’s mouse event handlers (onPress. This section contains both ActionScript 1. or on() and onClipEvent() handlers. ■ 17. as discussed in “Using event handler methods” on page 330. Event handler scope 343 . or context. Select Control > Test Movie to test the Flash document. 16. Create new keyframes on frame 20 of each of the three layers. and so forth). and select Insert > Timeline > Keyframe. the color of the rectangle in Frame 20 so each of the three button states have a different color. the scope also depends on how you define the event handler. Select 13. If you’re defining an event handler in a new ActionScript class. of variables and commands that you declare and execute within an event handler depends on the type of event handler you use: event handlers or event listeners. Attach an on() event handler to the movie clip instance. and add a frame label of _over in frame 10 of the labels layer.9. 14. onRelease. Modify 15.0 examples Functions assigned to event handler methods and event listeners (as with all ActionScript functions that you write) define a local variable scope. Return to the main timeline.

the following on() event handler produces different results that depend on whether it’s attached to a button or movie clip object. the play() function call starts the timeline of the movie clip to which the handler is attached. For instance. variables (as well as function and method calls) are invoked in the scope of the timeline that contains the button instance.For example. // local function variable shoeColor = "blue". If you attach the following code to a movie clip. } // on() handler attached to clip_mc: on (press) { var shoeColor. // Attached to button. on (press) { play().onPress = function () { var shoeColor. The first is an onPress event handler associated with a movie clip named clip_mc. // no local variable scope shoeColor = "blue". in the second case. it plays the parent timeline: // Attached to movie clip. // Attached to clip_mc's parent clip timeline: clip_mc. consider the following two event handlers. the play() function applies to the timeline that contains the button—that is. they have different results. } When attached to a button object. the play() function call applies to the movie clip that bears the handler. } // Attached to movie clip. the variable is defined in the scope of the timeline of the clip_mc movie clip. rather than to movie clips. on (press) { _parent. // Plays parent timeline. // Plays parent timeline. } Although both event handlers contain the same code. the color variable is local to the function defined for onPress.play(). the play() function call starts the playhead of the timeline that contains the button. // Plays movie clip's timeline. The second is an on() handler attached to the same movie clip instance. In the first case. the button’s parent timeline. For on() event handlers attached to buttons. } 344 Handling Events . on (press) { play(). because the on() handler doesn’t define a local variable scope. But when the on(press) handler is attached to a movie clip object. In the second case. In the first case.

// plays root timeline }.onPress event handler method on the timeline that contains the my_mc movie clip instance: // Function defined on a timeline my_mc.monthNames.com/flash/params.onLoad = onLoadVarsDone.load("http://www.my_txt. _level0. However. // TextLoader.helpexamples.onPress = function () { play().my_txt. ActionScript 2. see “Scope of the this keyword” on page 347. params_lv.onPress = function () { this. }. _level0. params_lv.autoSize = "left". 100.text = params_lv.0 example The following TextLoader class is used to load a text file and display some text after it successfully loads the file.createTextField("my_txt". 20). 0. public function TextLoader() { params_lv = new LoadVars().play(). For more information about the scope of the this keyword in event handlers. }.txt"). refer explicitly to that clip using the this keyword.onPress = function () { this.play(). as follows: // Function defined on root timeline my_mc. 999.Within an event handler or event listener definition. To play the movie clip that defines the onPress event handler. } private function onLoadVarsDone(success:Boolean):Void { _level0. the same code placed on the root timeline for a button instance would instead play the root timeline: my_btn. 0. suppose you declare the following my_mc. the same play() function applies to the timeline that contains the function definition. For example.as class TextLoader { private var params_lv:LoadVars. // plays timeline that it is defined on. // undefined } } Event handler scope 345 . // plays timeline of my_mc clip.

// January.load("http://www. public function TextLoader() { params_lv = new LoadVars().This code cannot work correctly because there is a problem involving scope with the event handlers. and the onLoadVarsDone() function is invoked with this set to LoadVars.onLoadVarsDone(success). The owner object is still visible in the scope of the anonymous function. not TextLoader. even though the onLoadVarsDone() function relies on the params_lv object by reference.. } private function onLoadVarsDone(success:Boolean):Void { _level0.autoSize = "left". The params_lv object resides in the this scope when it is invoked. The behavior that you might expect in this example is that the onLoadVarsDone() method will be invoked in the scope of the TextLoader object.monthNames. To correctly invoke the onLoadVarsDone() method in the scope of the TextLoader object. var owner:TextLoader = this. but it is invoked in the scope of the LoadVars object because the method was extracted from the TextLoader object and grafted onto the LoadVars object. so it can be used to find the calling TextLoader object. 0.txt").createTextField("my_txt". _level0. you can use the following strategy: use a function literal to create an anonymous function that calls the desired function. } } 346 Handling Events . The LoadVars object then invokes the this. 100. 999.text = params_lv.onLoad = function (success:Boolean):Void { owner. 0..helpexamples. the onLoadVarsDone() function is expecting a params_lv.com/flash/params. params_lv.params_lv instance that does not exist. Therefore.my_txt.March. // TextLoader.my_txt. 20).February.. _level0.onLoad event handler when the text file is successfully loaded. and what this refers to is confused between the onLoad event handler and the class. } params_lv.as class TextLoader { private var params_lv:LoadVars.

this refers to the timeline that contains the button. this can refer to different objects. You can use Delegate.addEventListener().Scope of the this keyword The this keyword refers to the object in the currently executing scope. // _level0.my_mc } Within an on() handler attached to a button. For example. and so that you can call functions within the scope of the containing class. // _level0.create() to call the function within the scope of the declaring object. in the following code. as shown in the following code: // Attached to movie clip named my_mc on main timeline on (press) { trace(this). // _level0 } Using the Delegate class The Delegate class lets you run a function in a specific scope. Within an event handler or event listener function. this refers to the movie clip to which the on() handler is attached. this refers to the object that defines the event handler or event listener method. as shown in the following code: // Attached to button on main timeline on (press) { trace(this).onPress = function () { trace(this). Using the Delegate class 347 . The following example shows three methods of listening for events for a Button component instance. this refers to my_mc: // onPress() event handler attached to main timeline: my_mc.my_mc } Within an on() handler attached to a movie clip. the function is invoked in the scope of the broadcaster component instance. Depending on what type of event handler technique you use. This class is provided so that you can dispatch the same event to two different functions (see “Delegating events to functions” in Using Components). Each way that you add event listeners to a Button component instance results in the event being dispatched in a different scope. When you pass a function as a parameter to EventDispatcher. not the object in which it is declared (see “Delegating the scope of a function” in Using Components).

10). this.create(this. The third section of code creates an object that you use as an event listener. "two_button"."). 10). } var buttonListener:Object = new Object(). import mx. You add and position the button instance on the Stage using ActionScript in a later step.Delegate. function clickHandler(eventObj:Object):Void { trace("[" + eventObj. 3. one_button. {label:"Two"}).move(120. clickHandler). The second section of code defines a function that you call when the user clicks some of the buttons. {label:"One"}).createClassObject(Button. buttonListener).type + "] event on " + eventObj.addEventListener("click". trace("\t this -> " + this). 2. two_button. }.move(230.utils. "three_button". Add the following ActionScript to Frame 1 of the main Timeline: import mx. 10). trace("\t this -> " + this). "one_button". and the object listens for a single event. buttonListener. one_button. three_button. The first section imports the Button class (for the Button component) as well as the Delegate class. 348 Handling Events . three_button. 10.createClassObject(Button.type + "] event on " + eventObj.target + " instance.").click = function(eventObj:Object):Void { trace("[" + eventObj. 20. Create a new Flash document and save it as delegate.fla. 30. Delegate.move(10.createClassObject(Button. this. clickHandler)).target + " instance. this.addEventListener("click".controls. click.Button.addEventListener("click".To use the Delegate class to listen for events: 1. {label:"Three"}). The preceding code is separated into six sections (each section is separated by a blank line). two_button. Drag a Button component from the User Interface folder of the Components panel to the library.

and add an event listener for the click event. Click the third button on the Stage to trace the following text in the Output panel: [click] event on _level0. b. The second button adds an event listener for the click event and passes a reference to a listener object. uses the Delegate class to dispatch the click event in the this scope (where this equals _level0) and passes a reference to the click handler function. which contains a handler for the click event. this -> _level0. 4.one_button instance.create() method call. Select Control > Test Movie to test the Flash document. the this scope refers to the buttonListener object. The first button adds an event listener for the click event and passes a reference to a click handler function directly.two_button instance. 5. Click each button instance on the Stage to see which scope in which the event is handled.one_button When you click one_button instance. Using the Delegate class 349 . reposition the instance. _level0. c. this -> [object Object] When you click the two_button instance. the this scope refers to the button instance itself. this -> _level0 When you click the three_button instance.The remaining three sections of code each create a new Button component instance on the Stage. Click the first button on the Stage to trace the following text in the Output panel: [click] event on _level0. Finally. the this scope refers to the scope that you specify in the Delegate. Click the second button on the Stage to trace the following text in the Output panel: [click] event on _level0. or in this case.three_button instance. the third function adds an event listener for the click event. a.

350 Handling Events .

filters. if the main timeline has only one frame and a movie clip in that frame has ten frames. scripted animation and more. blends. and Drawings. or nested clips. each frame in the movie clip plays when you play the main SWF file. movie clips provide the foundation of component-based architecture in Macromedia Flash Basic 8 and Macromedia Flash Professional 8. You can name movie clip instances to uniquely identify them as objects that can be controlled with ActionScript. You can think of movie clips as autonomous objects that can respond to events. In fact. A movie clip can. where the parent clip contains one or more child clips. Movie clips nested in this way have a hierarchical relationship. contain other movie clips. “Animation.CHAPTER 11 Working with Movie Clips Movie clips are like self-contained SWF files that run independently of each other and the timeline that contains them.” 11 351 . send messages to other movie clip objects. the instance name identifies it as an object of the MovieClip class type. You use the properties and methods of the MovieClip class to control the appearance and behavior of movie clips at runtime. For information on using the Drawing API (drawing methods of the MovieClip class). the components available in the Components panel (Window > Components) are sophisticated movie clips that are designed and programmed to look and behave in certain ways. see Chapter 13. in turn. and manage their child clips. For example. In this way. When you give a movie clip instance an instance name. Filters. maintain their state.

. . . . . . . . . . . . . . . . . . .369 Using movie clips as masks . . . . . . . . . . . the target timeline must be loaded in Flash Player when the function or method is called. .379 About controlling movie clips with ActionScript You can use global ActionScript functions or the methods of the MovieClip class to perform tasks on movie clips. . . . . . . . . . . 378 Assigning a class to a movie clip symbol. . . . . . . . . . . . . . . . . . . . . . . . . and places it at a depth of 5. . . . . . . . . . and then the method name and parameters. . . . . . . . . . . . . . . .For more information on movie clips. . . . . other MovieClip methods. . . . . . . . . . . . . . . . . . 359 Creating movie clips at runtime .366 About caching and scrolling movie clips with ActionScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . names the new clip new_mc. . . . . . . . . . . . . . . . . . . . . . . Whether you use a function or a method. . . 5). . . . . . . . . . . . . . . don’t have corresponding function names. . . . . . . The following example shows the difference between using a method and using a function. . . 376 Handling movie clip events. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .355 Changing movie clip position and appearance . "new_mc". . . Some methods of the MovieClip class perform the same tasks as functions of the same name.duplicateMovieClip("new_mc". . . . . . . . . When a function and a method offer similar behaviors. . . you can select to control movie clips by using either one. duplicateMovieClip(my_mc. . . . . . . . . . . . . . . . . . . . . . . . . such as hitTest() and swapDepths(). . . . . . . . 357 Dragging movie clips . . . . . . . . . . . . . . . .). . . . . . . . 5). . . . . . . . . . . . . . To use a method. . . . . . . . . . see the following topics: About controlling movie clips with ActionScript . . . . . . . . . . . . . . . . . activate it by using the target path of the instance name. . . . . . . . . . . . . parentClip. . . . . . . . . . .354 Loading and unloading SWF files . . . . . . . . . . . . . . . . .childClip. . The choice depends on your preference and your familiarity with writing scripts in ActionScript.play(). . . . . . . . . Each statement duplicates the instance my_mc. . . . .gotoAndPlay(3). . . . . . . . . 378 Initializing class properties . . . . . . . . . . . . . .352 Calling multiple methods on a single movie clip . . . . . .364 Managing movie clip depths . . . . . . . . . . . . . . . as shown in the following statements: myMovieClip. . . . . . . . . . . . . . . . . . . . . . a dot (. . . . my_mc. . . . . . . . . . . . . 360 Adding parameters to dynamically created movie clips. . . 352 Working with Movie Clips . . . . . . . . . .

getBounds(). MovieClip. ■ About controlling movie clips with ActionScript 353 .onRelease = function() { stopDrag(). MovieClip. in the Samples folder on your hard disk. gotoAndPlay() sends the playhead in childClip (which is a child of the instance parentClip) to Frame 3 and continues to move the playhead. MovieClip. In the second statement. animation. To use these functions. unloadMovie(). MovieClip. }.getBytesLoaded(). MovieClip. ■ In Windows. setProperty(). For example. loadVariables().swapDepths(). play() moves the playhead in the myMovieClip instance. MovieClip.localToGlobal(). MovieClip. MovieClip.onPress = function() { startDrag(this). you can find a sample source file.attachMovie(). and removeMovieClip(). Global functions that control a timeline have a target parameter that let you specify the target path to the instance that you want to control. On the Macintosh.globalToLocal(). MovieClip.getDepth(). MovieClip. in the following script startDrag() targets the instance the code is placed on and makes it draggable: my_mc. MovieClip.fla. MovieClip. The following functions target movie clips: loadMovie().getBytesTotal(). browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Animation. For more information about these functions and methods. you must enter a target path for the function’s target parameter to indicate the target of the function. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Animation. For an example of scripted animation in Flash. my_mc. }.createTextField(). see their entries in the ActionScript 2.In the first statement. duplicateMovieClip(). startDrag().getNextHighestDepth().createEmptyMovieClip(). MovieClip.0 Language Reference.hitTest().setMask(). The following MovieClip methods can control movie clips or loaded levels and do not have equivalent functions: MovieClip.getInstanceAtDepth().

hole.You can find samples of photo gallery applications on your hard disk. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Galleries. The object you specify is added to the end of the current target path. which includes scripted animation. Array.fla. ■ Calling multiple methods on a single movie clip You can use the with statement to address a movie clip once and then execute a series of methods on that clip. } 354 Working with Movie Clips ._yscale = 150. browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Galleries. _yscale = 150.hole. On the Macintosh. All actions nested inside a with statement are carried out inside the new target path. donut. hole. in the Samples folder on your hard disk. ■ In Windows._alpha = 20. in the following script.hole object passes to the with statement to change the properties of hole: with (donut. The preceding code is also equivalent to the following example: with (donut) { hole.These files provide examples of how to use ActionScript to control movie clips dynamically while loading image files into a SWF file. gallery_tree._alpha = 20. For example. The preceding code is equivalent to the following example: donut._xscale = 150. and Sound)—not only movie clips. the donut. Color. } The script behaves as if the statements inside the with statement were called from the timeline of the hole instance.hole) { _alpha = 20. The with statement works on all ActionScript objects (for example. You can find the sample source files. The with statement takes a movie clip as a parameter._yscale = 150.hole. or scope. hole. _xscale = 150._xscale = 150. donut.fla and gallery_tween.

If you might reuse the clip at a later time. You can also use the loadMovie() method to send variables to a CGI script. Develop a branching interface with links that lets the user select among several SWF files that are used to display a site’s content. Explicitly unloading SWF files with unloadMovie() ensures a smooth transition between SWF files and can decrease the memory that Flash Player requires. For more information on the MovieClipLoader class.Loading and unloading SWF files To play additional SWF files without closing Flash Player. It can be more efficient in some situations to set the movie clip’s _visible property to false instead of unloading the clip. see “Loading external SWF and image files” on page 593. Build a navigation interface with navigation controls in level 0 that loads content into other levels. If you load a SWF file into a target. you might use this procedure to load dynamic SWF or image files based on specified variables within a movie clip. ■ ■ For more information on loading SWF files. see MovieClipLoader in the ActionScript 2. you can specify a level or movie clip target into which the SWF file loads. or to switch SWF files without loading another HTML page. which generates a SWF file as its CGI output. The loadClip() method of the MovieClipLoader class. set the _visible property to false and then set to true when necessary. After the Flash movie is loaded.0 Language Reference. you can use one of the following options: ■ ■ The global loadMovie() function or loadMovie() method of the MovieClip class. see the following topics: ■ ■ “Specifying a root timeline for loaded SWF files” on page 356 “Loading image files into movie clips” on page 357 Loading and unloading SWF files 355 . Loading content into levels helps produce smoother transitions between pages of content than loading new HTML pages in a browser. For more information. Use loadMovie() to do any of the following: ■ Play a sequence of banner ads that are SWF files by placing a loadMovie() function in a container SWF file that sequentially loads and unloads SWF banner files. you can change those properties. the loaded SWF file inherits the properties of the targeted movie clip. The unloadMovie() method removes a SWF file previously loaded by the loadMovie() method. When you load a SWF file. For example.

For example. However. if a script in level 1 evaluates _root. consider a file named container. In the following example. To force _root to always evaluate to the timeline of the loaded SWF file.swf that has a movie clip instance named target_mc on its main timeline. can set _lockroot to true. rather than the actual root timeline. target_mc.swf: target_mc.swf into the target_mc movie clip: // In container.swf. 356 Working with Movie Clips .userName = "Mary".loadMovie("contents.swf"). my_btn.swf ) would be set to "Mary" instead of "Tim". the loaded SWF file. In the following example.swf loads into the movie clip in container. You can set this property either by the loading the SWF file or by the SWF file being loaded. }. the value of userName that’s attached to the root timeline of the hosting SWF file (container. the root timeline is on the level that contains the currently executing script. If a SWF file has multiple levels. the same script then loads another file called contents. _level1 is returned.swf could put the following code on Frame 1 of the main Timeline: // Added to Frame 1 in container. contents. that movie clip acts as _root for any SWF file loaded into it._lockroot = true.userName = "Tim".onRelease = function():Void { trace(_root. This could cause code in container. After contents. By default. the author of container. When _lockroot is set to true within a SWF file.swf file declares a variable named userName on its main timeline. use the _lockroot property.swf: _root. For example. Any movie clip. and any number of movie clips.swf: _root.Specifying a root timeline for loaded SWF files The _root ActionScript property specifies or contains a reference to the root timeline of a SWF file. this property is false. depending on whether a SWF file is running independently (in its own level) or was loaded into a movie clip instance by a loadMovie() call. When _lockroot is set to true on a movie clip instance. also declares a variable named userName on its root timeline: // In contents.userName). The container.swf (as well as contents.swf ) to malfunction. the timeline that _root specifies can change. no matter what other SWF file loads it. that SWF file acts as its own root.swf.

but the original content of the movie clip is removed. Changing movie clip position and appearance 357 . Alternatively. see _lockroot (MovieClip. Because this registration point is often the center of the movie clip. when you load an image to a root timeline.swf: this. the author of contents. not to the actual root timeline of container.This step ensures that any references to _root in contents. see loadMovie function. Loading image files into movie clips You can use the loadMovie() function. _rotation._lockroot = true.loadMovie method). the upper-left corner of the image is placed at the registration point of the movie clip._lockroot property). and loadMovieNum function in the ActionScript 2. the upper-left corner of the image is placed on the upper-left corner of the Stage. write a statement that assigns a value to a property or use the setProperty() function.swf could add the following code to its main timeline: // Added to Frame 1 in contents. For example. the following code sets the rotation of instance mc to 45: my_mc. any reference it makes to _root refers to its own main timeline.0 Language Reference and “Loading external SWF and image files” on page 593. not to that of the hosting SWF file. which uses the setProperty() function: setProperty("my_mc". The loaded image inherits rotation and scaling from the movie clip. When you load an image into a movie clip. You can also use the loadMovieNum() function to load an image file into a level. Also. loadMovie (MovieClip. "Tim" appears.swf. This would ensure that no matter where contents. to load image files into a movie clip instance. For more information. For more information.swf—or any SWF file loaded into target_mc—refers to its own timeline. Now when you click the button. This is equivalent to the following code. 45). or the MovieClip method of the same name. the loaded image might not appear centered.swf is loaded. Changing movie clip position and appearance To change the properties of a movie clip as it plays._rotation = 45.

_droptarget. _xscale. which includes scripted animation. For an example of scripted animation in Flash. You can find the sample source files. which is a child of the car_mc instance: car_mc. and _ymouse. All other properties belong to each movie clip or loaded level. (These properties are specified as read-only in their ActionScript 2. }._x = _root. On the Macintosh. _xmouse). _rotation. 358 Working with Movie Clips . _parent.0 Language Reference entries.fla. _alpha. animation. ■ In Windows. ■ In Windows. The _focusrect._x = getProperty(_root.fla and gallery_tween. in the Samples folder on your hard disk.fla. you can find a sample source file. they belong only to the level 0 main timeline.These files provide examples of how to use ActionScript to control movie clips dynamically while loading image files into a SWF file. _xmouse. For example.onEnterFrame = function() { my_mc. and transform the movie clip and any of the clip’s children.onEnterFrame = function() { my_mc. the following statement gets the value of the _xmouse property on the current level’s timeline and sets the _x property of the my_mc instance to that value: this. _totalframes. in the Samples folder on your hard disk. see the property summary for the MovieClip class in the ActionScript 2. _y. You can write statements to set any property that is not read-only. In addition.Some properties. _yscale. gallery_tree. browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Galleries. }.) The following are read-only properties: _currentframe. and _visible properties are affected by transformations on the movie clip’s parent. _target. you can write statements that get the value of a movie clip property. and _soundbuftime properties are global. have values that you can read but cannot set. The _x. The following statement sets the _alpha property of the wheel_mc movie clip instance. _height. _width._alpha = 50. called read-only properties.0 Language Reference. For a list of movie clip properties. _framesloaded. which uses the getProperty() function: this.wheel_mc. browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Animation. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Animation. ■ You can find samples of photo gallery applications on your hard disk. This is equivalent to the following code._xmouse. _highquality. _quality. _url.

0 Language Reference. A movie clip remains draggable until explicitly stopped by stopDrag() or until another movie clip is targeted with startDrag(). scroll bars. ■ Dragging movie clips 359 . For example.startDrag(false). as shown in the following example: // Drag a piece of garbage. browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Galleries.startDrag method) in the ActionScript 2. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Galleries. You can find the sample source file. Dragging movie clips You can use the global startDrag() function or the MovieClip.startDrag() method to make a movie clip draggable. To create more complicated drag-and-drop behavior. }. and sliders.fla. you might examine the _droptarget property to see if the movie clip was dragged onto a specific movie clip (such as a “trash can” movie clip) and then trigger another action. gallery_tween. garbage_mc. in the Samples folder on your hard disk. you can make a draggable movie clip for games. drag-and-drop functions. // When the garbage is dragged over the trashcan. make it invisible. garbage_mc. if (eval(this. which includes making each movie clip draggable. // Convert the slash notation to dot notation using eval.■ On the Macintosh.stopDrag().onPress = function() { this. ■ In Windows. } }.onRelease = function() { this. you can evaluate the _droptarget property of the movie clip being dragged._droptarget) == trashcan_mc) { garbage_mc. customizable interfaces. For more information._visible = false. On the Macintosh.This file provides an example of how to use ActionScript to control movie clips dynamically while loading image files into a SWF file. see startDrag function or startDrag (MovieClip. For example. You can a sample photo gallery application on your hard disk. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Galleries. Only one movie clip at a time can be dragged in a SWF file.

which includes creating movie clips at runtime.This file provides an example of how to use ActionScript to control movie clips dynamically while loading image files into a SWF file. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Galleries. you can also create movie clip instances at runtime in the following ways: ■ ■ ■ “Creating an empty movie clip” on page 360 “Duplicating or removing a movie clip” on page 362 “Attaching a movie clip symbol to the Stage” on page 362 Each movie clip instance you create at runtime must have an instance name and a depth (stacking. You can find the sample source file. On the Macintosh. The depth you specify determines how the new clip overlaps with other clips on the same timeline. “Creating an empty movie clip” on page 360 “Duplicating or removing a movie clip” on page 362 “Attaching a movie clip symbol to the Stage” on page 362 ■ For more information. in the Samples folder on your hard disk. browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Galleries. (See “Managing movie clip depths” on page 366. ■ For an example source file that creates and removes numerous movie clips at runtime. use the createEmptyMovieClip() method of the MovieClip class. gallery_tween. or z-order) value. empty movie clip instance on the Stage. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Animation. browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Animation. It also lets you overwrite movie clips that reside at the same depth. This method creates a movie clip as a child of the clip that calls the method. you can find a sample source file. see the following topics: ■ ■ ■ Creating an empty movie clip To create a new.fla. The registration point for a newly created empty movie clip is the upper-left corner.fla. 360 Working with Movie Clips .Creating movie clips at runtime In addition to creating movie clip instances in the Flash authoring environment. ■ In Windows. in the Samples folder on your hard disk ■ In Windows.) You can a sample photo gallery application on your hard disk. On the Macintosh. animation.

99). 10). the following code creates a new child movie clip named new_mc at a depth of 10 in the movie clip named parent_mc: parent_mc. var my_mcl:MovieClipLoader = new MovieClipLoader().loadMovie("http://www.0 Language Reference. 0). in the Samples folder on your hard disk ■ In Windows. my_mcl. and then activates loadMovie() to load an external JPEG file into itself: this. For more information. To get access to movie clip methods. // Creates a parent movie clip to hold the container. you can find a sample source file. ■ Creating movie clips at runtime 361 . you must create an empty parent movie clip and a container child movie clip.onPress = function():Void { trace("It works").jpg". my_mc.loadClip("http://www.helpexamples. this. my_mc. // Put event handler on the my_mc parent movie clip. }. Load the image into the container and place the event handler on the parent movie clip.fla.createEmptyMovieClip("my_mc".createEmptyMovieClip("canvas_mc". As shown in the following example. // Use MovieClipLoader to load the image.createEmptyMovieClip("container_mc".onPress() method to make the image act like a button. For an example source file that creates and removes numerous movie clips at runtime. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Animation. On the Macintosh.jpg image into a movie clip and use the MovieClip. // This is the movie clip the image will replace. my_mc.helpexamples. // Creates a child movie clip inside of "my_mc". Loading an image using loadMovie() replaces the movie clip with the image but doesn’t give you access to movie clip methods.createEmptyMovieClip method) in the ActionScript 2. you can load the image2. canvas_mc.For example.jpg"). browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Animation.com/flash/images/image1.container_mc). 10). animation.com/flash/images/image2. see createEmptyMovieClip (MovieClip.createEmptyMovieClip("new_mc". The following code creates a new movie clip named canvas_mc on the root timeline of the SWF file in which the script is run.

To assign a linkage identifier to a movie clip: 1. or the MovieClip class methods of the same name. see duplicateMovieClip function and removeMovieClip in the ActionScript 2. the element is not exported to the SWF file. The attachMovie() method attaches to the Stage an instance of a movie clip symbol in the SWF file’s library. assigns it a new instance name. This can create a delay before the first frame plays. To use ActionScript to attach a movie clip symbol from the library. or z-order. 362 Working with Movie Clips .0 Language Reference. The new clip becomes a child clip of the clip that attached it. animation. 2. function For more information. you can find a sample source file.Duplicating or removing a movie clip To duplicate or remove movie clip instances. in the Samples folder on your hard disk ■ In Windows. all movie clips that are exported for use with ActionScript load before the first frame of the SWF file that contains them. By default. and gives it a depth. If it isn’t added in the first frame. you use the Linkage Properties dialog box. you can also specify whether this content should be added before the first frame. use the duplicateMovieClip() or removeMovieClip() global functions. Select a movie clip in the Library panel. A duplicated movie clip always starts at Frame 1. On the Macintosh. To do this. Duplicated movie clips are also removed if the parent movie clip is deleted. use removeMovieClip(). browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Animation. For an example source file that creates and removes numerous movie clips at runtime. To delete a movie clip you created with duplicateMovieClip(). you must export the symbol for ActionScript and assign it a unique linkage identifier.fla. Select Window > Library to open the Library panel. When you assign a linkage identifier to an element. even if the original movie clip was on another frame when duplicated and is always in front of all previously defined movie clips placed on the timeline. browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Animation. if you don’t. ■ Attaching a movie clip symbol to the Stage The last way to create movie clip instances at runtime is to use the attachMovie() method. The duplicateMovieClip() method creates a new instance of an existing movie clip instance. you must include an instance of it in some other frame of the SWF file.

10).attachMovie("calif_id". as described in the previous example. to attach the movie clip to the root timeline. select Linkage from the Library panel pop-up menu. select ActionScript 2. You can optionally assign an ActionScript class to the movie clip symbol. In the Actions toolbox (at the left of the Actions panel). For idName. "california_mc". enter values for the following parameters: ■ ■ ■ 4. 7. select Export for ActionScript. 5. enter an instance name for the attached clip so that you can target it. To attach a movie clip to another movie clip: 1. With the Actions panel open (Window > Actions). deselect the Export in First Frame option. By default. place an instance of the movie clip on the frame of the timeline where you want it to be available. specify the identifier you entered in the Linkage Properties dialog box. If you deselect this option. Each attached movie clip has its own stacking order. enter an ID for the movie clip. Using the code hints that appear as a guide. If you don’t want the movie clip to load before the first frame. type the name of the movie clip or level to which you want to attach the new movie clip. 3. the identifier is the same as the symbol name. enter the level at which the duplicate movie clip will be attached to the movie clip. For example. and select attachMovie(). select a frame in the Timeline. if the script you’re writing doesn’t reference the movie clip until Frame 10. as shown in the following example: this. For newName. 6. 5. For Identifier.0 Classes > Movie > MovieClip > Methods. This lets the movie clip inherit the methods and properties of a specified class. 2. type this. place an instance of the symbol at or before Frame 10 on the Timeline. Click OK. Assign a linkage identifier to a movie clip library symbol. with level 0 as the level of the originating movie clip. (See “Assigning a class to a movie clip symbol” on page 378. you can attach an instance of the symbol to the Stage at runtime by using attachMovie(). Attached movie clips are always on top of the original movie clip. For depth.) 4. The Linkage Properties dialog box appears. After you’ve assigned a linkage identifier to a movie clip. For example. For Linkage. Creating movie clips at runtime 363 . In the Actions panel’s Script pane.3. In the Library panel.

■ Use the following syntax with duplicateMovie(): myMovieClip.0 Language Reference.text = name_str. To populate a dynamically created movie clip with parameters from a specified object: Do one of the following: ■ Use the following syntax with attachMovie(): myMovieClip. initObject]). name_txt. The initObject parameter of attachMovie() and duplicateMovie() allows dynamically created movie clips to receive clip parameters. For more information.duplicateMovie(idName. create a movie clip symbol by selecting Insert > New Symbol. and open the Actions panel (Window > Actions). and select the Movie Clip behavior. The initObject parameter specifies the name of the object whose parameters you want to use to populate the dynamically created movie clip. 5. 2. you can populate the movie clip with parameters from another object. see attachMovie (MovieClip.attachMovie method) and duplicateMovieClip (MovieClip. depth [. 4.attachMovie() and MovieClip. 3. and assign its value to the text property of name_txt. In a new Flash document.attachMovie method) in the ActionScript 2.duplicateMovieClip method) in the ActionScript 2.For more information. Make sure this text field is below and to the right of the registration point. newName. depth [. Create a new variable called name_str. newName. To populate a movie clip with parameters by using attachMovie(): 1. Adding parameters to dynamically created movie clips When you use MovieClip.duplicateMovie() to create or duplicate a movie clip dynamically. Select Frame 1 of the movie clip’s Timeline. Inside the symbol. see attachMovie (MovieClip. as shown in the following example: var name_str:String.0 Language Reference. 364 Working with Movie Clips . Type dynamic_mc in the Symbol Name text box.attachMovie(idName. create a dynamic text field on the Stage with an instance name of name_txt. initObject]).

fla. browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Galleries. and add the following code to the Actions panel’s Script pane: /* Attaches a new movie clip and moves it to an x and y coordinate of 50 */ this.6. and click OK. On the Macintosh. the first frame of the main Timeline. ■ In Windows. 10. 7. "newClip_mc". 99. ■ Adding parameters to dynamically created movie clips 365 . Select the Export for ActionScript option. The Linkage Properties dialog box appears.fla. in the Samples folder on your hard disk. and Export in first frame. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Animation. and select Linkage from the Library pop-up menu. You can find a sample photo gallery application on your hard disk. On the Macintosh.attachMovie("dynamic_id". _x:50. in the Samples folder on your hard disk ■ In Windows. Select the movie clip symbol in the library. _y:50}).This file provides an example of how to use ActionScript to control movie clips dynamically while loading image files into a SWF file. ■ For an example source file that creates and removes numerous movie clips at runtime. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Galleries. browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Animation. You can find the sample source file. Type dynamic_id into the Indentifier text box. Select 11. you can find a sample source file. The name you specified in the attachMovie() call appears inside the new movie clip’s text field. which includes creating movie clips at runtime. animation. Select Edit > Edit Document to return to the main Timeline. {name_str:"Erick". 9. Test the Flash document(Control > Test Movie). gallery_tween. 8.

10). getInstanceAtDepth (MovieClip. named clip1_mc. or createEmptyMovieClip (MovieClip. however. duplicateMovieClip (MovieClip.attachMovie("symbolID". Instead. the following code attaches a new movie clip to the timeline of a movie clip named container_mc with a depth value of 10. "clip1_mc". The following code attaches two new movie clips to container_mc. container_mc. To avoid this problem. the new or attached clip overwrites the existing content. and swapDepths (MovieClip. This example creates a new movie clip with a depth of 10 within the z-order space of container_mc. When you create a movie clip at runtime by using attachMovie (MovieClip.getNextHighestDepth() method. container_mc. you always specify a depth for the new clip as a method parameter. is rendered behind clip2_mc because it was assigned a lower depth value. For more information on movie clip depths.Managing movie clip depths Every movie clip has its own z-order space that determines how objects overlap within its parent SWF file or movie clip.swapDepths method) in the ActionScript 2.getInstanceAtDepth method). The MovieClip class provides several methods for managing movie clip depths.createEmptyMovieClip method).getDepth method).0 Language Reference. "clip1_mc". do not use this method with components that use a different depthmanagement system. use the MovieClip. For example. getDepth (MovieClip.attachMovie("symbolID". 10). use “DepthManager class” with component instances. "clip2_mc". which determines if it renders in front of or behind other movie clips in the same movie clip timeline. see getNextHighestDepth (MovieClip. 15). see the following topics: ■ ■ ■ ■ “Determining the next highest available depth” on page 367 “Determining the instance at a particular depth” on page 367 “Determining the depth of an instance” on page 368 “Swapping movie clip depths” on page 368 366 Working with Movie Clips . for more information.attachMovie("symbolID".duplicateMovieClip method).attachMovie method). Depth values for movie clips can range from -16384 to 1048575. container_mc. Every movie clip has an associated depth value.getNextHighestDepth method). If you create or attach a new movie clip on a depth that already has a movie clip. The first clip.

_y:0}).attachMovie("menuClip". see “DepthManager class” in the Component Language Reference. "edit_mc". subtract 1 from the value that getNextHighestDepth() returns. instead."file_mc".getInstanceAtDepth().getNextHighestDepth().Determining the next highest available depth To determine the next highest available depth within a movie clip.0 Language Reference. _y:0}). on the root timeline named file_mc. 10. The integer value returned by this method indicates the next available depth that will render in front of all other objects in the movie clip. Do not use MovieClip. {_x:200. with a depth value of 10. Determining the instance at a particular depth To determine the instance at a particular depth. as shown in the next section. var highestOccupiedDepth:Number = this.getNextHighestDepth() .getNextHighestDepth() with components. use MovieClip. this. use the depth manager. method) For more information.1.getInstanceAtDepth in the ActionScript 2. var instanceAtHighestDepth:MovieClip = this. // 10 var nextDepth:Number = this. the variable named nextDepth contains the value 11 because that’s the next highest available depth for the edit_mc movie clip. see getInstanceAtDepth (MovieClip. This method returns a reference to the MovieClip instance at the specified depth. The following code attaches a new movie clip.getDepth()). this. For more information.getNextHighestDepth method).getNextHighestDepth(). use MovieClip. To obtain the current highest occupied depth.getDepth()). nextDepth. see getNextHighestDepth (MovieClip. // 11 In this case.getNextHighestDepth(). trace(edit_mc.getInstanceAtDepth(highestOccupiedDepth). trace(file_mc. The following code combines getNextHighestDepth() and getInstanceAtDepth() to determine the movie clip at the (current) highest occupied depth on the root timeline. It then determines the next highest available depth in that same movie clip and creates a new movie clip called edit_mc at that depth. Managing movie clip depths 367 . {_x:0. For more information on MovieClip.attachMovie("menuClip".

and then type first_mc into the Instance Name text box in the Property inspector. Select the blue circle. see getDepth (MovieClip. and then type second_mc into the Instance Name text box in the Property inspector. 10.swapDepths(second_mc). Select 368 Working with Movie Clips . if (obj instanceof MovieClip) { var objDepth:Number = obj. The following examples show how two movie clip instances can swap depths at runtime. 8. 7. Create a new Flash document called swap. and then type the following code into the Actions panel: first_mc. Draw a blue circle on the Stage. second_mc.fla. 5. Drag the two instances so that they overlap slightly on the Stage. Draw a red circle on the Stage.onRelease = function() { this. Select the instance on the Stage. and then click OK. Select the Movie clip option._name + ":" + objDepth) } } For more information. }.0 Language Reference. 4.getDepth(). and then click OK. To swap movie clip depths: 1. use MovieClip. 9.getDepth method) in the ActionScript 2. }. Select the instance on the Stage.swapDepths(). 6. trace(obj. 2.onRelease = function() { this.swapDepths(first_mc). Swapping movie clip depths To swap the depths of two movie clips on the same timeline. and then select Modify > Convert to Symbol. The following code iterates over all the movie clips on a SWF file’s main timeline and shows each clip’s instance name and depth value in the Output panel: for (var item:String in _root) { var obj:Object = _root[item]. 3.Determining the depth of an instance To determine the depth of a movie clip instance. Select the Movie clip option. Frame 1 of the Timeline. and then select Modify > Convert to Symbol. use MovieClip.getDepth().

instances with caching turned on are not continually redrawn as the SWF file plays. Flash does not optimize the content. About caching and scrolling movie clips with ActionScript As your designs in Flash grow in size.0 Language Reference. which lets the SWF file render quickly. Therefore. Therefore. You can update the vector data. the vector data cached in the surface does not need to remain the same for the entire SWF file. You’ll see the two instances change which clip is on top of the other clip. see swapDepths (MovieClip. The movie clip or button is a surface. they swap depths.11. you can cache specified movie clips and buttons to improve the performance of your SWF file. when you change the position of the rectangle movie clip. essentially a bitmap version of the instance’s vector data. Therefore. which is data that you do not intend to change much over the course of your SWF file. you can select the Use runtime bitmap caching option in the Property inspector instead. About caching and scrolling movie clips with ActionScript 369 . N OT E You can use ActionScript to enable caching or scrolling and to control backgrounds. Flash redraws the entire rectangle in Flash Player 7 and earlier. When you click the instances on the Stage. For more information.swapDepths method) in the ActionScript 2. You can use the Property inspector to enable caching for a movie clip instance. In Flash Player 8. you need to consider performance and optimization. Select Control > Test Movie to test the document. at which time the surface is recreated. To cache movie clips or buttons without using ActionScript. whether you are creating an application or complex scripted animations. When you have content that remains static (such as a rectangle movie clip).

If you set this property to a numeric value. Flash creates a surface object for the instance.scrollRect property). The movie clip’s contents are cropped. and renders faster. Text fields and complex content that you display in the instance can scroll faster because Flash does not regenerate the entire movie clip vector data. For an example. If you change the bounds of the movie clip. The surface copies the bitmap onto its parent surface. the surface is recreated instead of resized. For more information and an example. To create a surface that’s also scrollable. which is a cached bitmap instead of vector data. see the sample file in Flash install directory\Samples and Tutorials\Samples\ActionScript\FlashType. N OT E ■ You can find a sample source file that shows you how bitmap caching can be applied to an instance. the opaqueBackground and scrollRect properties work best when an object is cached as a bitmap. see “Setting the background of a movie clip” on page 375. height. An opaque bitmap does not have an alpha channel (transparency). Surfaces can nest within other surfaces. 370 Working with Movie Clips . see scrollRect (MovieClip. For information on alpha channel masking. These three properties are independent of each other. You only see performance benefits for the opaqueBackground and scrollRect properties when you set cacheAsBitmap to true. which requires you to set the cacheAsBitmap property to true. the movie clip instance has an opaque (nontransparent) surface. however. see “Caching a movie clip” on page 373. see “About alpha channel masking” on page 377. For more information and an example. and the instance scrolls with a specified width. In Windows.fla. For more information and an example. You cannot apply caching directly to text fields. This lets the user quickly scroll movie clip content and have a window that displays larger content than the Stage area. scrollRect Lets you quickly scroll movie clip content and have a window for viewing larger content. Find the file called cacheBitmap. in the Samples folder on your hard disk. You need to place text within a movie clip to take advantage of this feature. opaqueBackground Lets you specify a background color for the opaque movie clip instance.The following table contains brief descriptions of the new properties for movie clip instances: Property cacheAsBitmap Description Makes the movie clip instance cache a bitmap representation of itself. and scroll offsets. browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\CacheBitmap. you must set the cacheAsBitmap and scrollRect properties for the movie clip instance.

how much of the data you change. and whether or not you set the opaqueBackground property. Complex background image An application that contains a detailed and complex background image of vector data (perhaps an image where you applied the trace bitmap command. About caching and scrolling movie clips with ActionScript 371 . The background is rendered as a bitmap and can be redrawn quickly. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/CacheBitmap. which has several advantages. see “About alpha channel masking” on page 377. Find the sample source file. and when to use regular movie clips. such as helping complex vector animations to render fast. flashtype. ■ In Windows. It might seem as though you will always want to enable caching to improve the performance of your SWF files. You might want to test both scenarios with your work before you deploy the application. ■ When to enable caching Enabling caching for a movie clip creates a surface. which slows the animation because the background needs to continuously regenerate the vector data. When to use bitmap caching The following are typical scenarios in which you might see significant benefits when you enable bitmap caching. store it in a movie clip. browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\FlashType. you can select the content. There are several scenarios in which you will want to enable caching. This section describes scenarios in which caching should be used. or even decrease it. however.■ On the Macintosh. You might animate characters over the background. in the Samples folder on your hard disk. which requires you to set the cacheAsBitmap property to true. You can also find a sample source file that shows you how to apply bitmap caching to scrolling text.fla. or artwork that you created in Adobe Illustrator). browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/FlashType. For information on alpha channel masking. and set the opaqueBackground property to true. there are situations in which enabling caching does not improve performance. If you are changing small regions. On the Macintosh. To improve performance. the difference between using a surface and using vector data could be negligible. Overall performance of cached data depends on how complex the vector data of your instances are. so that your animation plays much faster.

When a user scrolls the movie clip instance. web browser windows). Users can drag the windows so that they overlap each other. if the movie clip on Stage is 250 pixels by 250 pixels in size. You can place the text field in a movie clip that you set as scrollable with scrolling bounds (the scrollRect property).Scrolling text field An application that displays a large amount of text in a scrolling text field. Find the sample source file. Each window can be open or closed (for example. when cached it might use 250 KB instead of 1 KB when it’s a regular (uncached) movie clip instance. ■ In Windows. This enables fast pixel scrolling for the specified instance. each window is isolated and cached. Windowing system An application with a complex system of overlapping windows. A cached bitmap can use significantly more memory than a regular movie clip instance. Flash shifts the scrolled pixels up and generates the newly exposed region instead of regenerating the entire text field. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/FlashType. which means that you should only enable surfaces when you need to improve rendering performance. remember the following guidelines: ■ Do not overuse surfaces (movie clips with caching enabled). Find the file called cacheBitmap. If you mark each window as a surface (set the cacheAsBitmap property to true). Each surface uses more memory than a regular movie clip. On the Macintosh.fla. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/CacheBitmap. On the Macintosh. When you develop a FLA file that uses surfaces. All of these scenarios improve the responsiveness and interactivity of the application by optimizing the vector graphics. flashtype. in the Samples folder on your hard disk. ■ In Windows.fla. If you overuse bitmap caching. especially if you zoom in on the content. ■ You can also find a sample source file that shows you how to apply bitmap caching to scrolling text. in the Samples folder on your hard disk. 372 Working with Movie Clips . You can find a sample source file that shows you how bitmap caching can be applied to an instance. browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\FlashType. For example. ■ Avoid zooming into cached surfaces. and each window doesn’t need to regenerate the vector content. a large amount of memory is consumed (see previous bullet). ■ When to avoid using bitmap caching Misusing this feature could negatively affect your SWF file. browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\CacheBitmap.

which is difficult to process and negatively affects your SWF file.fla. and name the file cachebitmap. Select Export for ActionScript (which also selects Export in first frame). About caching and scrolling movie clips with ActionScript 373 . ■ Caching a movie clip To cache a movie clip instance. You can drag or move the instance. with the linkage identifier of Star. and then click Advanced (if the dialog box is not already expanded). you might notice that the movie clip instance automatically pixel-snaps to whole coordinates. if one or more of the following occurs: ■ ■ The bitmap is greater than 2880 pixels in height or width. 2. Group surfaces together as much as possible. when you create windowing applications. browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\CacheBitmap. For example. it increases the amount of processing that Flash Player (and sometimes the computer) needs to do. you need to set the cacheAsBitmap property to true. To cache a movie clip: 1. Create or import a complex vector graphic into the FLA file. Type star into the Name text box. ■ 4. you should notice that any complex vector animation renders much faster. On the Macintosh. A surface (cached bitmap) is not created. Click OK to create the movie clip symbol. even if cacheAsBitmap is set to true. 5. Type star_id into the Identifier text box. After you set the cacheAsBitmap property to true. for example. 7. the instance changes between the surface and vector data. 8. Select the vector graphic. 6. browse to Macintosh HD/Applications/Macromedia Flash 8/ Samples and Tutorials/Samples/ActionScript/CacheBitmap. Type 24 into the fps text box in the Property inspector (Window > Properties > Properties). and select Modify > Convert to Symbol. Create a new Flash document. When you test the SWF file.■ Use surfaces for movie clip instances that are largely static (nonanimating). if you rotate or transform an instance. If you mix surfaces with vector data. 3. The bitmap fails to allocate (out of memory error). You can find a complex vector graphic in the finished source file for this example in the following directory: ■ In Windows. but the contents of the instance should not animate or change a lot.

When you click the Stage._rotation += 5. i++) { makeStar(). i < 20. null.onEnterFrame = function() { star_mc. var star_array:Array = new Array(). (Math.height . Control > Test Movie to test the document. star_mc. 10. i < star_array. it toggles the cacheAsBitmap setting between true and false. to a smooth animation where the instances animate back and forth across the Stage. var star_tween:Tween = new Tween(star_mc. Stage._height / 2).cacheAsBitmap.onMouseDown = function():Void { var star_mc:MovieClip.cacheAsBitmap property) in the ActionScript 2. as demonstrated in the previous example. mouseListener.9.Tween. Click anywhere on the Stage to enable bitmap caching.yoyo().getNextHighestDepth().attachMovie("star_id".transitions. 0. star_tween.width. You can also apply this code for a Button instance.length. 374 Working with Movie Clips . and then add the following ActionScript to the Actions panel: import mx. } } Mouse. for (var i:Number = 0.onMotionFinished = function():Void { star_tween.random() * 5) + 5.random() * Stage. i++) { star_mc = star_array[i].round(Math. Select Frame 1 of the Timeline.addListener(mouseListener). var star_mc:MovieClip = this. If you toggle caching on and off. } star_mc. }. "_x". } var mouseListener:Object = new Object().cacheAsBitmap = !star_mc._y = Math. } function makeStar():Void { var depth:Number = this.0 Language Reference.star_mc. star_array. You’ll notice that the animation changes from appearing to animate at 1 frame per second.push(star_mc). See cacheAsBitmap (Button. true). Select 11. for (var i:Number = 0. it frees the data that is cached. depth). star_mc. "star" + depth.

which helps optimize performance. browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\FlashType. Draw a blue circle on the Stage. Select the blue circle. Select the Movie clip option. 2. which requires you to set the cacheAsBitmap property to true. in the Samples folder on your hard disk. When you set cacheAsBitmap to true. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/FlashType. when you have a background that contains complex vector art.scrollRect property) in the ActionScript 2. If you do not set cacheAsBitmap to true. You can find a sample source file that shows you how bitmap caching can be applied to an instance. ■ In Windows. Create a new Flash document called background. and also set the opaqueBackground property to a specified color. Find the file called cacheBitmap. About caching and scrolling movie clips with ActionScript 375 . see scrollRect (MovieClip. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/CacheBitmap. ■ Setting the background of a movie clip You can set an opaque background for a movie clip. On the Macintosh. in the Samples folder on your hard disk. Find the sample source file. 3. ■ You can also find a sample source file that shows you how to apply bitmap caching to scrolling text.fla. browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\CacheBitmap. To set the background of a movie clip: 1. flashtype. On the Macintosh. and then select Modify > Convert to Symbol. you can set the opaqueBackground property to a specified color (typically the same color as the Stage).fla. 4. The background is then treated as a bitmap.For examples of scrolling movie clips. see “About alpha channel masking” on page 377. The following example shows how to set the background of a movie clip to optimize performance. the opaqueBackground property adds an opaque vector-square shape to the background of the movie clip instance. For information on alpha channel masking. and then click OK. ■ In Windows.0 Language Reference.fla. For example. It does not create a bitmap automatically. the opaqueBackground property allows the internal bitmap to be opaque and rendered faster.

Select Control > Test Movie to test the document. the internal bitmap is opaque and renders faster. Select Frame 1 of the Timeline. (MovieClip.opaqueBackground = 0xFF0000. The mask movie clip plays all the frames in its timeline. or resize a mask dynamically. and then type the following code into the Actions panel: /* When you set cacheAsBitmap. Using movie clips as masks You can use a movie clip as a mask to create a hole through which the contents of another movie clip are visible. and then type my_mc into the Instance Name text box in the Property inspector.cacheAsBitmap = true. You cannot use a mask to mask another mask.opaqueBackground property) For more information on this property. You can make the mask movie clip draggable. Select the square and press F8 to convert it into a movie clip. animate it along a motion guide. 376 Working with Movie Clips . Only fills are used in a movie clip that is used as a mask. 2. The movie clip appears on the Stage with the background color that you specified.5. the same as a regular movie clip. see opaqueBackground in the ActionScript 2. Select Frame 1 in the Timeline. Create a square on the Stage with the Rectangle tool. 4. You can also use ActionScript to turn a mask on and off. use separate shapes within a single mask. 3. This instance is your mask. my_mc. strokes are ignored. In the Property inspector. type mask_mc in the Instance Name text box. The masked movie clip is revealed under all opaque (nontransparent) areas of the movie clip acting as the mask. Open the Actions panel (Window > Actions) if it isn’t already open. */ my_mc. 7. 5. To create a mask: 1.0 Language Reference. You cannot set the _alpha property of a mask movie clip. 6. Select the instance on the Stage.

not the shape of the mask itself. An external JPEG image loads into the SWF file at runtime. the mask is an oval (oval_mask) that has alpha of 50% and a blur filter applied to it.6. var mclListener:Object = new Object().helpexamples. the user must have Flash Player 6 (6. That is.allowDomain("http://www. and is masked by the shape you drew previously on the Stage. For detailed information.createEmptyMovieClip("img_mc".0) or later.security. In the Actions panel. download the alpha masking sample file from www. the mask that appears in the SWF file is the shape of the rectangular bounding box of the mask. Select Control > Test Movie to test the document.loadClip("http://www. } var my_mcl:MovieClipLoader = new MovieClipLoader().com").setMask method) in the ActionScript 2. You can mask device fonts only by using a movie clip as a mask.com/flash/images/image1. This support also lets you use a filter on the mask independently of the filter that is applied to the maskee itself. my_mcl. 7. In this sample file.macromedia. this.0.helpexamples. In order for a movie clip mask on a device font to work properly. About masking device fonts You can use a movie clip to mask text that is set in a device font. Both movie clips have runtime bitmap caching applied in the Property inspector.addListener(mclListener).com/go/flash_samples. see setMask (MovieClip.setMask(mask_mc). enter the following code: System. Using movie clips as masks 377 . my_mcl. the rectangular bounding box of the mask is used as the masking shape. To see an example of alpha masking. if you create a nonrectangular movie clip mask for device font text in the Flash authoring environment. 10). The maskee (flower_maskee) has alpha of 100% and no filter applied on it. About alpha channel masking Alpha channel masking is supported if both the mask and the maskee movie clips use bitmap caching. You cannot mask device fonts by using a mask layer on the Stage.0 Language Reference. mclListener.jpg".onLoadInit = function(target_mc:MovieClip):Void { target_mc.40. img_mc). When you use a movie clip to mask text set in a device font.

and use runtime bitmap caching.0. you can provide method definitions for the built-in MovieClip methods and event handlers. it assumes the properties and behaviors defined by the class assigned to it. such as mouse clicks and keypresses. You must use ActionScript code to apply a mask. such as the initial loading of a movie clip on the Stage. you’ll create a movie clip symbol in a new Flash (FLA) document and assign the MoveRight class to that symbol.”. Mask layers do not support alpha channel masking. ActionScript provides two ways to handle movie clip events: through event handler methods and onClipEvent() and on() event handlers. see “Example: Writing custom classes” on page 263. the following code is placed on Frame 1 of the Timeline: flower_maskee. When you test the document (Control > Test Movie). 378 Working with Movie Clips . NO TE Handling movie clip events Movie clips can respond to user events. MoveRight defines an onPress handler that moves the clip 20 pixels to the right whenever the user clicks the movie clip. For more information on handling movie clip events. To create a movie clip subclass: 1. you’ll create a class called MoveRight that extends the MovieClip class. you can create a class that extends the behavior of the built-in MovieClip class and then use the Linkage Properties dialog box to assign that class to a movie clip library symbol. the maskee is alpha blended by using the mask. Assigning a class to a movie clip symbol Using ActionScript 2.) In a subclass of the MovieClip class. Select File > New.In the Actions panel. see Chapter 10. In the second procedure.0.setMask(oval_mask). as well as systemlevel events. such as onEnterFrame and onRelease. “Handling Events. In the following procedure. 2. (For more information about ActionScript 2. and select ActionScript file from the list of document types to create a new ActionScript file. Create a new directory called BallTest. Whenever you create an instance of the movie clip to which the class is assigned.

2. To assign the class to a movie clip symbol: 1. select Component Definition from the Library pop-up menu and enter the new class name in the Class box. Initializing class properties 379 . In the Convert to Symbol dialog box. 7. draw a circle on the Stage.as in the BallTest directory. you can assign parameters to clips you create at runtime by using the initObject parameter of attachMovie() and duplicateMovie(). Test the Flash document(Control > Test Movie)._x += 20. and type MoveRight in the Class text box. Save the document as MoveRight. select Movie Clip as the symbol’s behavior. You can use this feature to initialize properties of the class you’re assigning to a movie clip.as file). Select the Export for ActionScript option. it moves 20 pixels to the right.moves clip to the right 20 pixels when clicked class MoveRight extends MovieClip { public function onPress() { this. Save the file as ball. 3. if they aren’t already showing. you need to take an additional step: with the movie clip symbol selected in the Library panel. 4. and enter ball_mc in the Name text box. If you create component properties for a class and want a movie clip to inherit those component properties. and select Modify > Convert to Symbol. and click OK. Select the circle. Using the Oval tool.fla in the BallTest directory (the same directory that contains the MoveRight. Each time you click the ball movie clip. Click OK. } } 4.3. 8. 6. Initializing class properties In the example presented in the second procedure under “Assigning a class to a movie clip symbol”. you added the instance of the Ball symbol to the Stage while authoring. 5. Enter the following code in your script file: // MoveRight class -. select Flash Document from the list of file types. In Flash. Select Advanced to show the options for Linkage. select File > New. As discussed in “Adding parameters to dynamically created movie clips” on page 364.

2. Create a new ActionScript document and save it as MoveRightDistance.moves clip to the right 5 pixels every frame. 5. and then delete any content from the Stage. {distance:50}).attachMovie("Ball". To pass arguments to a custom class: 1. Create a new Flash document. The first instance. whose value determines how many pixels a movie clip moves each time it is clicked. 4. moves 125 pixels each time it is clicked. named ball50_mc.distance. var distance:Number. 380 Working with Movie Clips . and save it as MoveRightDistance.0 Class text box. 8. this. Assign the linkage identifier Ball to the symbol.For example. Add the following code to Frame 1 of the Timeline: this. "ball50_mc". such as an oval. function onPress() { this. the second. right-click (Windows) or Control-click (Macintosh) the symbol and select Linkage from the context menu. Type the following ActionScript into the Script window: // MoveRightDistance class -. 10._x += this. You only need a movie clip symbol in the library for this example. Create a movie clip symbol that contains a vector shape. 7. This code creates two new instances of the symbol on the root timeline of the SWF file. class MoveRightDistance extends MovieClip { // Distance property determines how many // pixels to move clip for each mouse press.as. The difference is a new property named distance. 10. } } 3. 6.fla in the same directory as the class file. the following class named MoveRightDistance is a variation of the MoveRight class (see “Assigning a class to a movie clip symbol” on page 378). 20. moves 50 pixels each time it is clicked. In the Library panel. {distance:125}). Select Control > Test Movie to test the SWF file. Type MoveRightDistance into the AS 2. 9. named ball125_mc. "ball125_mc". Save your progress.attachMovie("Ball".

You can use many different kinds of text. or use ActionScript. and punctuation that you combine to make up strings. 12 You use anti-aliasing to smooth text so the edges of characters that appear onscreen look less jagged. One way to display text is to use code to manipulate how strings appear before they are loaded and displayed on the Stage at runtime. unlike anti-aliased text (see following definition). such as sending them to a server and retrieving a response. focusing on using code to manipulate text. and graphics that you create with Macromedia Flash Professional 8 or Macromedia Flash Basic 8 include some kind of text. Or you might use input text to capture user input. You might use static text in your layouts. parsing strings in an array. or validating strings that the user types into a text field. 381 . This chapter describes several ways to use text and strings in your applications.CHAPTER 12 Working with Text and Strings Many of the applications. numerals. You can work with strings in an application in several ways. Characters Anti-alias Characters are letters. The following list describes terminology used in this chapter. The Anti-Alias option in Flash makes text more legible by aligning text outlines along pixel boundaries. but dynamic text for longer passages of text. and is particularly effective for clearly rendering smaller font sizes. Alias Aliased text does not use color variations to make its jagged edges appear smoother. presentations. You can create text fields with the Flash authoring tool. and text in an image for your background design.

. . . . . . . . . . . .392 Using fonts . . . . . . . . . . . . . . . . . . . font size. . . . . . . . . . . . . . . . . . . . . . and size. . . . . . . . allow HTML formatting. 421 Creating a style sheet object . . . . . . . . . . . . . . . . . . . . . . . . . . the text that you create with these fonts looks different than expected on computer systems that do not have a font installed that corresponds to the device font. . . . . Flash lets you set text fields as editable (read-only). . Instead. . . or certain characters within a text field. . . . . italics. . . . . . or apply a CSS stylesheet to your HTML formatted text. . . . margin widths. . . . . . . . . Fonts String Text Device fonts Sets of characters with a similar font face. . Similar to an input text field or text area form control in HTML. . . . . . see the following topics: About text fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Text formatting You can apply formatting to a text field. . . . . . . . . bold. . . . . . . . . . . . . . . . . . . . . . 406 About text layout and formatting. . . . . . . For more information on text. . . . . . . . . . . . . . and _typewriter (similar to Courier). . . . . . . 424 Using HTML-formatted text . . . . . . . . . . . . . . . password masking. . . . . . . . .436 Example: Creating scrolling text . . . . . . . indenting. 449 382 Working with Text and Strings . . . . . .384 About loading text and variables into text fields . . . . . . . . . . . . . . . . . . . . . . However. . . or within a user interface component. . . . . . . . . . . . 414 Formatting text with Cascading Style Sheet styles . . . . .383 Using the TextField class . . . . A sequence of characters. . because device fonts are not embedded. . . . . . . Because font outlines are not embedded. .Device fonts are special fonts in Flash that are not embedded in a SWF file. . . . . . . . . . . . . color. . . . . . . . . . . . . . . . . . . . . . style. . . . . . . . a SWF file size is smaller than using embedded font outlines. . . . . . . . . . . . . . . . . . enable multiline support. Text fields A visual element on the Stage that lets you display text to a user. . . . Flash Player uses whatever font on the local computer that most closely resembles the device font. . . . . . . .398 About font rendering and anti-alias text . . . . . . . . . Some examples of text formatting options that can be applied to text are: alignment. . . . . . . Flash includes three device fonts: _sans (similar to Helvetica and Arial). and letter spacing. . . . . . . . . . . . _serif (similar to Times Roman). . . . . . . . . . . . . . . . . . . . . A series of one or more strings that can be displayed in a text field. .

see “About displaying text field properties for debugging” on page 728. see “About strings and the String class” on page 450 N OT E Text components The methods of the TextField class let you set. Also. The TextInput component is similar to an input text field. which lets you embed not just external images but also external SWF files as well as movie clips that reside in the library (see “Image tag” on page 439). they add more file size to your application. Static text You can use TextArea or TextInput components to display or capture text in your applications. you can assign it an instance name in the Property inspector. The TextArea component is similar to a dynamic text field with built-in scroll bars. Input text Use input text fields when you need to capture user input. Flash Player 7 and later supports the img HTML tag. change. and format the text field and its content by using the TextField and TextFormat classes. All text fields support Unicode. and manipulate text in a dynamic or input text field that you create during authoring or at runtime. You can use the instance name in ActionScript statements to set. For information on Unicode. ActionScript also provides several ways to format your text at runtime. When you create a text field in the authoring environment. select. Users can type in these text fields. For more information. Flash Player also supports a subset of HTML tags that you can use to format text (see “Using HTML-formatted text” on page 436). to display small amounts of text.About text fields A dynamic or input text field is a TextField object (an instance of the TextField class). or you can use ActionScript to create text fields. you can load text into dynamic text fields. see “Using the TextField class” on page 384. The TextFormat class lets you set character and paragraph formatting for TextField objects (see “Using the TextFormat class” on page 419). You can use the user interface to create several kinds of text fields. or to display special fonts that are not available on most computers. Both components have additional functionality over their text field equivalents. You can also display uncommon fonts by embedding characters for dynamic text fields. For information on debugging text fields at runtime. About text fields 383 . Dynamic text Use dynamic text fields when you need to display characters that are updated or that change at runtime. You can create the following kinds of text fields in Flash: Use static text to display characters that do not need to change. however.

In Flash Player 8. In Flash Player 7 and later. The source files are called textfieldsA. you must assign the text field an instance name in the Property inspector. see the following topics: ■ ■ “Assigning text to a text field at runtime” on page 385 “About text field instance and variable names” on page 386 You can find sample source files that demonstrate how to work with text fields using ActionScript. You can also create TextField objects at runtime. HTML text that you assign to a text field can contain embedded media (movie clips. You can get and set properties and invoke methods for text fields dynamically. using the method. which might optionally use CSS styles. _framesloaded. and JPEG files). SWF files. “Working with Text and Strings” on page 381. and assign them instance names. you can apply Cascading Style Sheet (CSS) styles to text fields using the TextField. see the introduction for this chapter. with the exception of the _currentframe.fla. and progressive JPEG images (Flash Player 7 does not support progressive JPEG images). directly to a text field. and more. You can also assign HTML formatted text. You can use CSS styles to style built-in HTML tags. and you can find them in the Samples folder on your hard disk: ■ In Windows. see “Formatting text with Cascading Style Sheet styles” on page 421.createTextField() For more information on using the TextField class. For information on the terminology that compares text. For more information on using CSS. or apply styles. strings. You use the methods and properties of this class to control text fields at runtime. see “Image tag” on page 439. GIF. see “Creating text fields at runtime” on page 387.StyleSheet class. For more information. The text wraps around the embedded media similar to how a web browser wraps text around media embedded in an HTML document. and _totalframes properties. define new formatting tags. You can then reference the text field with the instance name. and use the methods and properties of the TextField class to control the contents or basic appearance of the text field. browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\TextFields. For more information. TextField objects support the same properties as MovieClip objects.fla and textfieldsB.In Flash Player 7 and later. MovieClip. _droptarget. To use ActionScript to control a dynamic or input text field. 384 Working with Text and Strings . Using the TextField class The TextField class represents any dynamic or input (editable) text field you create using the Text tool in Flash. you can also dynamically load PNG.

text or the TextField. the text “New articles available on Developer Center” appears on the Stage. Assigning text to a text field at runtime When you build applications with Flash. you can use the TextField. Type the following code in the Actions panel: headline_txt.text = "New articles available on Developer Center". Or you can use ActionScript to define a stylesheet. When you test the SWF file (Control > Test Movie). an XML file. The text field is created at the next highest depth. To assign text to a text field. XML formatted text. About text fields 385 . underscores (_). you can assign a value to the text field by creating a variable with the specified name. This code creates a new text field with the instance name headline_txt. and dollar signs ($).■ On the Macintosh. The following exercise assigns text to a text field at runtime. and external style sheets. headline_txt. Or. 2. Using the Text tool. 300. this. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/TextFields. Select Frame 1 of the Timeline. Instance names must consist only of letters. 4. plain text.getNextHighestDepth(). with a text field width of 200 pixels and a height of 20 pixels. at the x and y coordinates of 100. 3.createTextField("headline_txt". Flash provides a great deal of control over how you create and display text on the Stage. you can also assign values by creating bindings between components. With the text field selected. To assign text to a text field at runtime: 1. such as supporting text that is HTML formatted. select Input Text from the Text Type pop-up menu. in the Property inspector (Window > Properties > Properties). such as a text file. if you entered a value in the variable text field in the Property inspector.text = "New articles available on Developer Center".htmlText property. Select Control > Test Movie to test the Flash document. 100. If you use version 2 of Macromedia Components Architecture in your Flash document. or even a remote web service. and then assign text to it. Type the following ActionScript on Frame 1 of the Timeline: this. and enter headline_txt in the Instance Name text box. create a text field on the Stage. and open the Actions panel (Window > Actions). 5. you may want to load text from an external source. 100. You can also create a text field with ActionScript. numbers. 100. 20).

headline_txt. The source files are called textfieldsA. Set the text field’s html property to true by using ActionScript (see the following code sample). type the following ActionScript on Frame 1 of the Timeline: this. 100. headline_txt. this. enables HTML formatting. On the Macintosh. 300. About text field instance and variable names In the Instance Name text box in the Property inspector. 20).fla. and you can find them in the Samples folder on your hard disk: In Windows. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/TextFields.getNextHighestDepth(). You can then assign values to the variable.fla and textfieldsB. and displays the text “New articles available on Developer Center” on the Stage. with the word “Developer Center” appearing in italics. When you target newer players. The preceding code dynamically creates a new text field. browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\TextFields. In the Var text box in the Property inspector. target the text of a text field by using its instance name and ActionScript.createTextField("headline_txt". CAUTION ■ ■ You can find sample source files that demonstrate how to work with text fields using ActionScript. 386 Working with Text and Strings . you must assign the text to the text field’s htmlText property instead of the text property.html = true.". To apply HTML formatting to a text field by using ActionScript.htmlText = "New articles available on <i>Developer Center</ i>. 100. you must assign an instance name to a text field to invoke methods and get and set properties on that text field.To create an HTML-formatted text field: Use one of the following two steps to enable HTML formatting for the text field: ■ ■ Select a text field and click Render Text as HTML in the Property inspector. you can assign a variable name to a dynamic or input text field. When you use HTML formatted text with a text field (not components) on the Stage. This is a deprecated functionality that you might use when you create applications for older versions of Flash Player (such as Flash Player 4).

To dynamically create a text field using ActionScript: 1. as shown in the following code: // This won't work. // For input text field with instance name "myField". this will work. However. This reduces the chances of a variable name conflict. 0) and a depth (z-order) of 10. you can’t use the variable name myTextVar to set the text field’s text property. Select File > New and then select Flash Document to create a new FLA file. Type the following ActionScript on Frame 1 of the Timeline: this. On the Macintosh. The new text field is attached to the timeline of the movie clip that calls the method. myTextVar. For example.text = "This sets the text property of the myField object". A text field’s variable name is a variable reference to the text contained by that text field. This code creates a 300 x 100-pixel text field named test_txt with a location of (0. however.text = "A text field variable is not an object reference". and you can find them in the Samples folder on your hard disk: ■ In Windows. ■ Creating text fields at runtime You can use the createTextField() method of the MovieClip class to create an empty text field on the Stage at runtime. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/TextFields. unless you’re targeting a version of Flash Player that doesn’t support the TextField class.text property to control the contents of a text field. 100). 300.Do not confuse a text field’s instance name with its variable name. You can find sample source files that demonstrate how to work with text fields using ActionScript. you can use the following code to set the contents of the text field: var myTextVar:String = "This is what will appear in the text field".fla and textfieldsB.createTextField("test_txt". You have to use the instance name. Use the TextField. browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\TextFields. The source files are called textfieldsA. it is not a reference to an object.fla. 0. 2. myField. which could result in unexpected behavior at runtime. 10. if you assigned a text field the variable name myTextVar. About text fields 387 . 0.

fla. such as _rotation.createTextField() method.wordWrap = true. Then it assigns some text using the text field’s text property: test_txt.createTextField method) and removeTextField (TextField. the following code creates a new text field named test_txt. The removeTextField() method does not work on a text field placed by the timeline during authoring. For more information. are not available when you create text fields at runtime. and modifies its properties to make it a multiline. The text is created at runtime and appears on the Stage.removeTextField() method to remove a text field created with createTextField().autoSize = "left". N OT E ■ ■ You can find sample source files that demonstrate how to work with text fields using ActionScript. You can rotate a text field only if it uses embedded fonts. word-wrapping text field that expands to fit inserted text.fla and textfieldsB. and you can find them in the Samples folder on your hard disk: In Windows. test_txt.0 Language Reference. browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\TextFields. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/TextFields. You can use the TextField. On the Macintosh. Some TextField properties. test_txt. The source files are called textfieldsA. Select Control > Test Movie to see the text field.". See “To embed a font symbol:” on page 400. 388 Working with Text and Strings .3.removeTextField method) in the ActionScript 2. 4. To access the methods and properties of the newly created text field. use the instance name specified in the first parameter of the createTextField() method. test_txt.text = "Create new text fields with the MovieClip. see createTextField (MovieClip.multiline = true. For example.

my_txt. ■ Changing a text field’s position You can change a text field’s position on the Stage at runtime.text = "Hello world".fla.height . You can manipulate a text field as long as you assign an instance name in the Property inspector._height) / 2. and you can find them in the Samples folder on your hard disk: ■ In Windows.fla.border = true.text = "I like seeds".my_txt. 100.width . see the following sections: ■ ■ “Changing a text field’s position” on page 389 “Changing a text field’s dimensions at runtime” on page 390 You can find sample source files that demonstrate how to work with text fields using ActionScript. For a complete list of properties in the TextField class. 200. 3._y = (Stage. 10. as shown in the following example. my_txt.About manipulating text fields You can manipulate text fields that you create in a FLA file in several ways. 200). The following simple example creates a text field. or you can assign one with code if you use code to create the field. 0. see the ActionScript 2. You need to set new values for the text field’s _x and _y properties. On the Macintosh. browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\TextFields._width) / 2.createTextField("my_txt". this. About text fields 389 . 2. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/TextFields. pigeon_txt. Create a new FLA file and save it as positionText. 100.fla and textfieldsB. and changes the border property of the field: this. For examples of how to manipulate text fields.getNextHighestDepth(). my_txt. assigns text to it. 0. pigeon_txt.my_txt.0 Language Reference. To reposition a text field by using ActionScript: 1. Save the Flash document and select Control > Test Movie to see the text field centered on the Stage. 300.createTextField("pigeon_txt".border = true. Add the following ActionScript to Frame 1 of the Timeline: this. 20)._x = (Stage. The source files are called textfieldsA. my_txt.

height . Save the Flash document and select Control > Test Movie to see the results in the authoring environment. 10. On the Macintosh. my_txt.width . To resize a text field using ActionScript: 1. 21). The next example creates a text field on a timeline and sets its initial dimensions to 100 pixels wide by 21 pixels high. 0. 100._width) / 2. Create a new Flash document and save it as resizeText. 390 Working with Text and Strings . Later.border = true. this technique may not be suitable for your needs. Add the following ActionScript to Frame 1 of the Timeline: this.multiline = true. 3.my_txt. 2._x = (Stage.fla. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/TextFields. my_txt. The previous example resized a dynamically created text field to 300 pixels by 200 pixels at runtime.wordWrap = true.my_txt._width = 300. my_txt. rather than in the authoring environment.autoSize property. my_txt. Fortunately.fla and textfieldsB. my_txt. which you can use to automatically resize a text field to fit its contents._height) / 2.You can find sample source files that demonstrate how to work with text fields using ActionScript._y = (Stage. and you can find them in the Samples folder on your hard disk: ■ In Windows.createTextField("my_txt". but when you load content from an external website and are not sure how much content will be returned. The source files are called textfieldsA. my_txt._height = 200.fla.autoSize property to resize the text field after text is added to the text field.text = "Hello world". 0. ■ Changing a text field’s dimensions at runtime You may need to get or set a text field’s dimensions dynamically at runtime. and it is repositioned to the center of the Stage. The following example demonstrates how you can use the TextField. browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\TextFields. Flash includes a TextField. the text field is resized to 300 pixels wide by 200 pixels high. my_txt. my_txt.

you may encounter line breaks in the long text string. my_txt.". NO T E 3. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.multiline = true. use the following code.createTextField("my_txt". 120).fla. if (my_txt.border = true.fla. Flash resizes the text field vertically so that all the content can be displayed without being cropped by the text field boundaries. 10. my_txt.wordWrap property to false. the code won’t compile. consectetur adipisicing elit. my_txt. 2. sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.wordWrap = true. Ut enim ad minim veniam. and then remove the line break characters in the long text string. Excepteur sint occaecat cupidatat non proident. To enforce a maximum height on the auto-sized text field (so that the text field height doesn’t exceed the boundaries of the Stage).autoSize = "left". About text fields 391 . 10. this method is often adequate while testing this code. } You must add some scrolling functionality. Alternatively. If you set the my_txt. 10. and you can find them in the Samples folder on your hard disk: ■ In Windows. enable Hidden Characters on the popup menu of the Actions panel.To automatically resize text fields based on content: 1. The source files are called textfieldsA.text = "Lorem ipsum dolor sit amet._height = 160. sunt in culpa qui officia deserunt mollit anim id est laborum. 160. to allow users to view the remainder of the text. In this case.autoSize = "none". my_txt. the text field resizes horizontally to accommodate the text. You can find sample source files that demonstrate how to work with text fields using ActionScript. my_txt. If you encounter this situation._height > 160) { my_txt. Save the Flash document and select Control > Test Movie to view the Flash document in the authoring environment. such as a scroll bar. Add the following code to Frame 1 of the main Timeline: this. If you paste this code directly into the Actions panel from some versions of Flash Help. my_txt. browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\TextFields. Create a new Flash document and save it as resizeTextAuto. you can roll the mouse pointer over the text.fla and textfieldsB.

which passes short strings of text into a Flash document through the object and embed tags in the HTML code that you use to embed the SWF file in an HTML page.” The following sections show you different ways to load text and variables into your documents: ■ ■ ■ ■ “Using FlashVars to load and display text” on page 393 “Using LoadVars to load and display text” on page 394 “Loading variables by using LoadVars” on page 396 “Loading and displaying text from an XML document” on page 397 392 Working with Text and Strings .macromedia. About loading text and variables into text fields You can load text into a Flash document several ways. but they are also the most difficult to learn. LoadVars. XML. FlashVars and LoadVars are much simpler. including (but certainly not limited to) using FlashVars. see Chapter 17. Also. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/TextFields. some ways of loading text into a SWF file are easier than others. as demonstrated in “Using FlashVars to load and display text” on page 393 and “Using LoadVars to load and display text” on page 394. you must follow security restrictions when you send and load data. see www. XML. Another easy way to load text or variables into a Flash document is to use the LoadVars class. if you syndicate data from external sites.” For more information on loading external data. Perhaps the simplest method of passing text into a Flash document is to use the FlashVars property. and Flash Remoting are the most versatile for loading external data. For information on Flash Remoting. you might not have a choice for the format of the data that you need to load. “Understanding Security. “Working with External Data. Each way of loading and/or sending data to and from a SWF file has its pros and cons. However.com/support/flashremoting. web services. but they can be much more limited in the types and formats of data that you can load.■ On the Macintosh. or web services. For information on security. which can load large blocks of text or load a series of URL encoded variables from a text file. see Chapter 16. As you can see from the previous examples in this section.

3. About loading text and variables into text fields 393 . and you can find them in the Samples folder on your hard disk: ■ In Windows. On the Macintosh.You can find sample source files that demonstrate how to work with text fields using ActionScript. Open up the flashvars. The sample source file is called flashtype. 10. to the same directory as your FLA file.fla and formattedText. Make sure that you select HTML. 10.fla. 100.fla. ■ You can also find a source file that loads text and applies anti-alias formatting in addition to bitmap caching.fla in the Samples folder on your hard disk: ■ In Windows. You can then test the Flash document by viewing the modified HTML document in your web browser. browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\LoadText. select File > Publish Settings and then select the Formats tab. by default. Add the following ActionScript to Frame 1 of the Timeline: this. N OT E 4. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/FlashType. ■ Using FlashVars to load and display text Using FlashVars is simple. 21).createTextField("my_txt". On the Macintosh.username.html document in a text or HTML editor. Create a new Flash document and save it as flashvars. You modify the generated HTML code and include the FlashVars properties in both the object and embed tags. 2. but requires you to publish your SWF files along with HTML documents. The source files are called loadText. my_txt. browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\FlashType. To use FlashVars to pass variables from HTML to your Flash document: 1. 10.text = _level0. If an HTML document does not publish. Save the Flash document and select File > Publish to generate the HTML and SWF files. An HTML document publishes. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/LoadText.

” Using LoadVars to load and display text You can also use the LoadVars class to load content into a SWF file. For information on security.macromedia.com/pub/shockwave/cabs/flash/ swflash. In the HTML document.0" width="550" height="400" id="flashvars" align="middle"> <param name="allowScriptAccess" value="sameDomain" /> <param name="movie" value="flashvars.0. see Chapter 17.com/go/ getflashplayer" /> </object> 6. “Understanding Security. Open the modified HTML in a web browser. 394 Working with Text and Strings . 7.5. <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload. or even content from a different server.macromedia. which loads text or variables from an external file on the same server. The SWF file displays the name “Thomas” in the dynamically created text field on the Stage.0.swf" /> <param name="FlashVars" value="username=Thomas" /> <param name="quality" value="high" /> <param name="bgcolor" value="#ffffff" /> <embed src="flashvars.cab#version=8. Save your changes to the HTML document. modify the code inside the object tag to match the following. The code you need to add is in boldface.swf" FlashVars="username=Thomas" quality="high" bgcolor="#ffffff" width="550" height="400" name="flashvars" align="middle" allowScriptAccess="sameDomain" type="application/xshockwave-flash" pluginspage="http://www. The next example demonstrates how to dynamically create a text field and populate it with the contents of a remote text file.

Flash displays the contents of the remote file in the text field on the Stage. The first block of code in the previous snippet creates a new text field on the Stage and enables multiline and word wrapping. } else { my_txt.helpexamples.txt) from a remote web server and display its contents into the my_txt text field created earlier.onData = function (src:String):Void { if (src != undefined) { my_txt.To use LoadVars to populate a text field with external text: 1. Create a new Flash document and save it as loadvarsText.fla.load("http://www. Add the following ActionScript to Frame 1 of the Timeline: this.multiline = true. lorem_lv. For information on security. 320. 10. The second block of code defines a new LoadVars object that is used to load a text file (lorem. see Chapter 17. 10. 100).createTextField("my_txt".com/flash/lorem. 3. my_txt. 10.". After a slight delay.txt").wordWrap = true.text = src. } } lorem_lv. Save the Flash document and select Control > Test Movie to test the SWF file.text = "Unable to load external file.autoSize = "left". my_txt.border = true. 2. my_txt.” About loading text and variables into text fields 395 . my_txt. var lorem_lv:LoadVars = new LoadVars(). “Understanding Security.

monthNames and dayNames. lorem_lv. 2. my_txt. Create a new Flash document and save it as loadvarsVariables. Because you are using the LoadVars. my_txt.dayNames + "\n\n".monthNames. The external text file contains two variables. Add the following code to Frame 1 of the Timeline: this.com/flash/params. 100).Monday. Save the Flash document and select Control > Test Movie from the main menu. my_txt.multiline = true.onLoad() method instead of LoadVars.text = "dayNames: " + lorem_lv.autoSize = "left". 10.createTextField("my_txt".. The following example demonstrates how to load a remote text file into a SWF file and display its variables..helpexamples. Flash parses out the variables and creates variables within the LoadVars object instance. my_txt. 320. 10. } else { my_txt.onData(). } } /* contents of params.fla. which both contain strings. For information on security.text += "monthNames: " + lorem_lv.text = "Unable to load external file.. see Chapter 17.. 3. To load variables from a text file by using LoadVars: 1. var lorem_lv:LoadVars = new LoadVars(). similar to passing variables in the query string in a web browser.load("http://www. */ lorem_lv..onLoad = function (success:Boolean):Void { if (success) { my_txt. monthNames and dayNames.txt")."..” 396 Working with Text and Strings . my_txt.Loading variables by using LoadVars The LoadVars class also lets you load variables in a URL-encoded format.February.border = true.wordWrap = true. “Understanding Security.txt: &monthNames=January.&dayNames=Sunday. 10.

my_txt.com/flash/xml/reviews.load("http://www. my_txt.text += childItems[i]. } } reviews_xml. To load text into Flash from an external XML document: 1.childNodes.. Once the date is completely loaded and parsed by Flash.. Item 8 For information on security. 10. in part because it is a widely accepted standard for organizing and parsing data. Add the following code to Frame 1 of the Timeline: this. 320. XML is an excellent choice for sending and receiving data from Flash.multiline = true.fla.wordWrap = true.firstChild.” About loading text and variables into text fields 397 . As such. XML is slightly more difficult to learn than using LoadVars and FlashVars to load data and display text. 100). the XML. var reviews_xml:XML = new XML(). 10. “Understanding Security. however.onLoad = function (success:Boolean):Void { if (success) { var childItems:Array = reviews_xml. for (var i:Number = 0. 10. This text field is used to display various parts of the XML document that is loaded later.Loading and displaying text from an XML document XML data is a popular way to distribute content on the Internet.border = true. 2. i++) { my_txt. The first block of code in the preceding snippet creates a new text field on the Stage.createTextField("my_txt".firstChild.nodeValue + "\n". Create a new Flash document and save it as xmlReviews. 3. reviews_xml. my_txt.length. Flash displays the following output in the text field on the Stage: Item 1 Item 2 . The second block of code handles creating an XML object that will be used to load the XML content.text = "Unable to load external file.".xml"). i < childItems.firstChild.onLoad() event handler is invoked and displays the contents of the XML packet in the text field.autoSize = "left". Save the Flash document and select Control > Test Movie to test the SWF file. reviews_xml. } } else { my_txt.ignoreWhite = true.helpexamples. my_txt. see Chapter 17.

Using fonts Fonts are sets of characters with a similar font face. 4. click Don’t Embed. and size. drag your mouse over multiple character sets. and other techniques for working with fonts in Flash 8. shared fonts. You can also quickly select multiple character sets by selecting a character set with your mouse. For more information on fonts. The following sections show you how to embed characters. To select a block of character sets. Create a dynamic text field on the Stage by using the Text tool. press and hold the Control key and deselect the character set by clicking it with your mouse pointer. press and hold the Control key while you select character sets. 5. style. and click a new character set. see the following sections: ■ ■ ■ ■ ■ “Embedding characters” on page 399 “Embedding fonts” on page 400 “Creating custom character sets” on page 402 “Using TextField methods with embedded fonts” on page 404 “About sharing fonts” on page 406 The following example shows you how to add and remove embedded characters and character sets in a Flash document. and you are not sure if your end users will have a specific font installed on their systems. 398 Working with Text and Strings . If you build animations. To select multiple non-sequential character sets. Create a new Flash document and save it as embedding. you need to understand the basics about embedding fonts. No matter what you create using Flash Basic 8 or Flash Professional 8. To remove a specific character set that you added earlier.fla. and with the mouse button still held down. 3. To remove every selected character set and any specified characters in the Include these characters text input field. 6. you will probably use text with at least one or two fonts in your Flash applications. Using Shift selects every character set between the two selected character sets. 2. Click Embed to launch the Character Embedding dialog box. you can use the Shift or Control key while selecting items with your mouse pointer. press and hold Shift. select a character set with your mouse pointer. To add and remove embedded characters and character sets: 1. To select multiple character sets. Select a specific character set to embed by clicking it with your mouse pointer. entire fonts.

specify specific characters to embed. With the text field still selected on the Stage. Flash only embeds unique glyphs. Using the Text tool.fla. you can reduce file size by embedding only the characters that you need instead of including additional. 8. Type the string hello world into the Include these characters text box. Even though the string “hello world” contains 11 characters. 4. so the letters l and o are embedded once instead of multiple times. To embed certain characters within a text field and not embed a whole character set. unused font outlines. 5. Auto Fill to automatically populate the Include These Characters text box. To embed specific characters for use in a text field: 1. Click Embed in the Property inspector to open the Character Embedding dialog box again. 10. 7. 3. and tells you the total number of glyphs being embedded for this text field. Using the Text tool. Click OK to apply the changes and return to your document. 9. The dialog box tells you that a total of 8 glyphs will be embedded for this text field. Clicking Don’t Embed in the Character Embedding dialog box removes any specified embedded characters and character sets that were previously chosen without asking you to confirm. create a new text field on the Stage. Type the string hello world into the text field on the Stage. click Embed in the Property inspector to open the Character Embedding dialog box. 2. 6. use the Character Embedding dialog box to specify which specific characters you want to embed. The Character Embedding dialog box lets you set which character sets will embed in the Flash document (as well as how many glyphs per character set).Don’t Embed clears any previously specified individual characters or character sets. Create a new Flash document and save it as charembed. Click Using fonts 399 . create a text field on the Stage and set the text field’s text type to either dynamic or input. Set the text field’s text type to dynamic in the Property inspector. C A U TI O N Embedding characters If you’re working with embedded fonts and know exactly what characters you need.

3. After you’ve embedded a font in your library. Type a name for the font symbol in the Name text box of the Font Symbol Properties dialog box. Instead of having to tell Flash which characters you want to include. T IP 11. Flash can determine characters to embed automatically only if the text field contains text on the Stage. 400 Working with Text and Strings . Select Bold. 2. or Alias text if you want to apply a style to the font. To use an embedded font symbol in your Flash document: 1. Use the Text tool to create a text field on the Stage. 6. Click OK. Italic. If the text field is populated by using ActionScript. Embedding fonts When you embed fonts. Follow the steps in the procedure under “Embedding fonts” on page 400 to embed a font in your library. Enter the font size to embed. and then click OK to apply the changes and return to your document. 4. Flash stores all of the font information in the SWF file so the font is displayed properly even if it’s not installed on the user’s computer. Flash Player automatically selects a substitute font to use instead. 2. Open the library that you want to add the font symbol to. N OT E To embed a font symbol: 1. Your font now appears in the current document’s library. If you use a font in your FLA file that isn’t installed on a user’s system. Type some text in the text field. Select New Font from the library’s pop-up menu (upper-right corner of the Library panel). Select a font from the Font menu or type the name of a font in the Font text box. you can use it with a text field on the Stage. If you use a static text field. 3. you must specify which characters you want to embed for the text field. You need to embed a font only if you’re using dynamic or input text fields. you don’t need to embed the font.You will see the string “helo wrd”. Select Window > Library to open the current FLA file’s library. and you don’t embed the font in the SWF file. 5. Flash can determine all unique characters in the specified text field for you.

To properly test that the font is embedded._rotation = 45. Set the text field’s Text type to Dynamic Text. 8... Select the text field. either type the characters into the text box in the dialog box. font_txt. If you aren’t sure which characters you will need (for example. b. 9. Add 11. The Character Embedding dialog box lets you select the individual characters or character sets that you want to embed for the selected text field. Or you can set the TextField. Punctuation [!@#%. you can select entire sets of characters to embed. and then click OK to apply the changes and return to your document. b. To specify what characters to embed. the following code to Frame 1 of the Timeline: 10. Select the individual characters or character sets you want to embed.4._alpha or TextField. you might need to test on a separate computer without the embedded font installed.. Type font_txt into the Instance Name text box. Each character set you select increases the final size of the SWF file because Flash has to store all of the font information for each character set that you use. Close the SWF file and return to the authoring tool. Lowercase [a.Z]. 7. and open the Property inspector. NO TE 6. Using fonts 401 . Select the text field on the Stage. Select the name of the embedded font by using the Font drop-down menu. Numerals [0. Set the text field to single-line. such as Uppercase [A. Embedded fonts have an asterisk (*) after the font name. because your text loads from an external file or a web service). because these properties work only on embedded fonts (see the following steps). Select Control > Test Movie again to view the changes in the authoring environment. and open the Property inspector._rotation properties for the text field with embedded fonts. a.9]. Click Embed in the Property inspector to launch the Character Embedding dialog box.z]. 5..]. or click Auto Fill to automatically populate the text field with the unique characters currently in the text field. and character sets for several different languages. Select Control > Test Movie to test the Flash document in the authoring environment.. a. The embedded font is displayed in the text field on the Stage.

The following XML nodes define the Uppercase [A. or perhaps you only need uppercase characters..Z] character set: <glyphRange name="Uppercase [A. such as the second range child node. such as 0x0020 (the space character). Rather than embedding entire character sets. and id. because you don’t store any extra font information for the characters that you don’t need. A range can be a single character. seen in the previous snippet. if you’re using an embedded font called Times. To create a custom character set. Working with Text and Strings .xml file. Before you create a custom character set. Creating custom character sets In addition to using the Flash default character sets. you should understand the necessary XML structure. you must edit the UnicodeTable. and then want a word to be italic. set the min value and the max value to the same unicode character value. you must embed the style that you want to use. not the name of the substituted font. However. A glyphRange node can have as many range child nodes as you need..The embedded font rotates 45º clockwise.. To embed only a single character.Z]. located in the C:\Program Files\Macromedia\Flash 8\<language>\First Run\FontEmbedding\ directory. Otherwise. you might need to allow some fields to include Extended Latin. the text won’t appear in the text field. For example. to support various accented characters. perhaps you don’t need the numerals and punctuation. you can create a custom character set that contains only the characters that you need. you must make sure to embed both the normal and italic character outlines. or a range of characters. the TextField. you can also create your own character sets and add them to the Character Embedding dialog box. This file defines the default character sets and the character ranges and characters that they contain. This way you can keep the size of your SWF file as small as possible.Z] " id="1" > <range min="0x0020" max ="0x0020" /> <range min="0x0041" max ="0x005A" /> </glyphRange> Notice that the glyphRange node includes name. If you don’t embed a font within your Flash document and Flash Player automatically chooses a font substitute on the user’s computer. For example. Uppercase [A.font property returns the original font used within the FLA. and you can still see the text because it’s embedded in the SWF file. C A UT I ON NO TE 402 If you use embedded fonts with a variety of styles in your text fields.

Before you create a custom character set. 4.). The best place to find Unicode values is the Unicode Standards web site. Before you edit this file. To create and use a custom character set: 1.9] " id="100" > <range min="0x0020" max ="0x0020" /> <range min="0x002E" max ="0x002E" /> <range min="0x0030" max ="0x0039" /> <range min="0x0041" max ="0x005A" /> </glyphRange> Save your changes to UnicodeTable. located in the <Flash install directory>\<language>\First Run\FontEmbedding\ directory. which contains the Unicode Character Code chart for dozens of languages. C A U TI O N Open the UnicodeTable. Open or restart Flash and then create a new Flash document. you need to know the characters and their corresponding Unicode values.. N OT E Scroll to the bottom of the XML document and add the following XML code directly before the closing </fontEmbeddingTable> node: <glyphRange name="Uppercase and Numerals [A. you must restart the application before you can use the new character set.Another example of an XML glyphRange node is the Numerals [0. 2. using an XML or text editor such as Notepad or TextEdit.. Using fonts 403 . as well as 0x002E (..xml. in case you want to revert to the original file that is installed with Flash. C A UT I ON Macromedia recommends that you do not modify the existing character sets that are installed with Flash.9] node: <glyphRange name="Numerals [0. you need to edit an XML file in the Flash installation folder. www. you should make a backup copy in case you want to revert to the original Unicode table. To add custom character sets.unicode.Z. Remember to save a backup of this document.0. and that you instead make your own custom character sets that include the characters and punctuation that you require..9] " id="3" > <range min="0x0030" max ="0x0039" /> <range min="0x002E" max ="0x002E" /> </glyphRange> This range of characters includes the Unicode values 0x0030 (zero) through 0x0039 (9).xml document.org. If you have Flash open. 3.

Make sure that you deselect the Bold and Italic options.5. are already included in your custom character set. and then click Embed Character Options to open the Character Embedding dialog box.. Add a new TextField instance on the Stage by using the Text tool. Enter a font name of Times (embedded) 404 Working with Text and Strings ... by moving <glyphRange> packets in the XML file.9] (38 glyphs). Uppercase and Numerals [A. you can control the thickness of a text field by using ActionScript as demonstrated in the following example. 8.. 6. as well as the default Uppercase [A. Scroll to the bottom of the Character Embedding dialog box and select your new custom character set. Create a new Flash document and save it as textfieldThickness. TIP Using TextField methods with embedded fonts Methods of the TextField class provide useful functionality for your applications. Uppercase and Numerals [A. This happens because two overlapping characters. and select New Font from the pop-up menu (in the upper-right corner of the Library panel). This dialog box lets you select a font to embed in the SWF file (including a font style and font size). Open the Library panel. a. including your custom character sets.Z] or Numerals [0. Set the Text type of the TextField to Dynamic in the Property inspector.Z. Set the size to 30 pixels. which keeps the file size as small as possible. You can also assign a font name that appears in the document’s library and the font drop-down menu in the Property inspector (if you have a text field selected on the Stage).fla. Select any other character sets and click OK.Z. This is because all of the uppercase characters are included in your custom character set. You can reorder the character sets. To set a text field’s thickness using ActionScript: 1. as well as your custom character set. d. and Flash doesn’t include duplicate characters. The position of a character set in the Character Embedding dialog box is determined by its location in the XML document.9] character set. The Font Symbol Properties dialog box opens. If you select the Punctuation character set. For example. which includes 38 glyphs. notice that the number of glyphs that are embedded doesn’t change.9]. Flash stores information for only 88 glyphs instead of 90. Select the Times New Roman font from the Font drop-down menu. which includes 52 glyphs.. c. b.. 7. the space and the period. 2.0. If you select your custom character set.0.

lorem_txt. 10.setTextFormat(style_fmt).size = 30. 4. 20. quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.width) . Select the Export for ActionScript and Export in first frame options and click OK.round(_xmouse * (400 / Stage. Add the following ActionScript to Frame 1 of the Timeline: // 1 this. sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.thickness = " + lorem_txt. Flash opens the Linkage Properties dialog box. Stage. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 20. 5. Click OK. 0.thickness property changes between -200 and +200. 3. onMouseMove Using fonts 405 . lorem_txt. and positions them on the Stage. sets the font size to 30 pixels. thickness_txt and lorem_txt. lorem_txt. }. and final.createTextField("lorem_txt". sunt in culpa qui officia deserunt mollit anim id est laborum. // 2 var style_fmt:TextFormat = new TextFormat().createTextField("thickness_txt". consectetur adipisicing elit.autoSize = "left".e. lorem_txt. style_fmt.thickness. block of code defines and assigns a mouse listener for the event. mouseListener.thickness can range from -200 to +200. The lorem_txt text field sets its embedFonts property to true and populates the text field with a block of text. When the mouse pointer moves horizontally across the Stage. style_fmt. Excepteur sint occaecat cupidatat non proident. 0). the TextField. In the library.text = "TextField.antiAliasType = "advanced". The first block of code creates two text fields.".font = "Times (embedded)". // 3 var mouseListener:Object = new Object(). right-click the font symbol. 0.200). lorem_txt. and then select Linkage from the context menu. lorem_txt. 22).width. Stage. Ut enim ad minim veniam.embedFonts = true.addListener(mouseListener). Mouse.wordWrap = true. lorem_txt. 0.width. this.onMouseMove = function():Void { // Values for TextField.text = "Lorem ipsum dolor sit amet. The second block of code defines a text format with the font face Times New Roman. depending on the current value of _xmouse. The third. and applies the text format to the lorem_txt text field.thickness = Math. thickness_txt.

called FlashType. About font rendering and anti-alias text Font rendering in Flash controls the way that your text appears in a SWF file. Select Control > Test Movie to test your Flash document. FlashType uses advanced rendering technology to help make text appear legible and clear at small to regular font sizes. called FlashType. rather than for individual characters. If you are publishing files for use with Flash Player 7 or earlier versions. and input text if the user has Flash Player 7 or later. This technology is discussed in more detail later in this section. that is. The Anti-Alias option for text makes characters more legible by aligning text outlines along pixel boundaries. and then assign the following attributes to the font symbol: ■ ■ An identifier string A URL where the document containing the font symbol will be posted In this way. When you move the mouse pointer to the right half of the Stage. you can link to the font and use it in a Flash application without the font being stored in the FLA file. The advanced font rendering technology used in Flash Player 8. 406 Working with Text and Strings . which can be particularly helpful when you want to display text using small text sizes. Anti-aliasing is supported for static. for working with anti-aliased fonts. the font thickness increases. Flash 8 includes five font rendering methods. Flash Basic 8 and Flash Professional 8 include a significantly improved font rasterization and rendering technology. the font thickness decreases. It is supported only for static text if the user has an earlier version of Flash Player. you can create a font symbol in the Library panel. About sharing fonts To use a font as a shared library item. When you move the mouse pointer to the left half of the Stage.You can apply anti-aliasing for each text field in your application. Advanced anti-aliasing options are available for Flash Player 8. Save your changes to the FLA file. only the Anti-Alias for Animation option is available for use with your text fields.6. such as when you apply advanced anti-aliasing to your text fields. how it is rendered (or drawn) at runtime. which are available only when you publish SWF files for Flash Player 8. Anti-aliasing lets you smooth text so that the edges of characters displayed onscreen look less jagged. 7. dynamic. and is particularly effective for more clearly rendering small font sizes.

About font rendering and anti-alias text 407 . You can find the sample source file. You use the FlashType rendering technology to create small text that’s highly legible. The FlashType technology lets you render font faces with high-quality output at small sizes. Bitmap Text (no anti-alias). in the Samples folder on your hard disk. you must select individual text fields and manually change the anti-aliasing settings to take advantage of the FlashType rendering technology. The improved capabilities mean that embedded text appears at the same level of quality as device text.FlashType is a high-quality font rendering technology that you can enable by using either the Flash 8 authoring tool or ActionScript. anti-alias is turned back on. The font rendering methods available for Flash Player 8 are Device Fonts. which lets you define a custom value for thickness and sharpness. flashtype. For more information on these options. This sample also demonstrates how text fields can scroll quickly and smoothly when you use the cacheAsBitmap property. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/FlashType. Anti-Alias for Animation. and fonts appear the same on different platforms. dynamic.fla. On the Macintosh. N OT E Advanced and custom anti-alias features do not support the following: A sample file on your hard disk shows how to apply and manipulate anti-aliased text in an application. and input text fields. You can apply FlashType to embedded font rendering for static. In Windows. your text is not automatically updated to the Anti-Alias for Readability option. and Custom Anti-Alias. with more control. or italic) up to 255 pt size File exporting to most formats (such as JPEG or GIF files) Flash Player 7 or earlier Skewed or flipped text Printing File exporting to the PNG file format When text is animated. After the animation is complete. see “Font rendering options in Flash” on page 408. browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\FlashType. Anti-Alias for Readability. bold. the player turns off advanced anti-alias to improve the appearance of your text while it’s moving. When you open existing FLA files in Flash 8. N OT E ■ ■ ■ ■ ■ ■ ■ Advanced and custom anti-alias features support the following: Scaled and rotated text All fonts (plain.

but you can visually manipulate the anti-aliasing parameters to produce a specific appearance. such as 255. The text also animates faster in some situations. Anti-Alias for Animation Produces anti-alias text that animates smoothly. CSM uses two rendering parameters to control the mapping of adaptively sampled distance field (ADF) distances to glyph density values. The function that maps ADF distances to density values has an outside cutoff. Anti-Alias for Readability The advanced anti-aliasing engine is used for this option. typeface. The option renders using fonts that are currently installed on the end user’s computer. or scaled fonts. above which values are set to a maximum density value. For an example of how to use anti-alias with ActionScript. Optimal values for these parameters are highly subjective. continuous modulation of both the stroke weight and the edge sharpness of the text. Device Fonts Produces a smaller SWF file size. they can depend on user preferences.Font rendering options in Flash Five different font rendering options are available in Flash 8. below which values are set to 0. Custom Anti-Alias About continuous stroke modulation The FlashType font rendering technology exploits the inherent properties of distance fields to provide continuos stroke modulation (CSM). select the text field and open the Property inspector. This option produces the largest SWF file size. This option is useful to produce the best possible appearance for new or uncommon fonts. for example. because font outlines are included in the SWF file. Bitmap Text (no anti-alias) Produces sharp text edges. because font outlines are included in the SWF file. display properties. Select an option from the Font rendering method pop-up menu. and an inside cutoff. This option produces a larger SWF file size. To select an option. see “Setting anti-alias with ActionScript” on page 409. lighting conditions. and point size. with the most legible text. The same as Anti-Alias for Readability. because alignment and anti-alias are not applied while the text animates. without anti-aliasing. You do not see a performance improvement when you use big fonts with lots of letters. This option offers the highest-quality text. This option produces a larger SWF file size. foreground and background colors. and also special anti-aliasing information. 408 Working with Text and Strings . because it includes font outlines.

Make sure that the Bold and Italic options are not selected. The Font Symbol Properties dialog box opens. Advanced anti-aliasing is available only in Flash Player 8 and later. see the following example. You will use these movie clips to toggle between the two types of anti-aliasing: normal and advanced. Select the Arial font from the Font drop-down menu. Open the Library panel and select New Font from the pop-up menu in the upper-right corner of the Library panel. the default setting for text fields created using ActionScript is normal. b. It is best used with applications that have a lot of small text. right-click the font symbol and select Linkage from the context menu. In the library. e. To use advanced anti-aliasing: 1. Create a new Flash document and save it as antialiastype. Applies advanced anti-aliasing for improved text readability.fla. Create two movie clips on the Stage and give them instances names of normal_mc and advanced_mc. For Flash Player 8. Advanced anti-aliasing allows font faces to be rendered at very high quality at small sizes. Enter the font name of Arial-10 (embedded). 4. Set the size to 10 pixels. This matches the type of anti-aliasing that Flash Player used in version 7 and earlier. You can also assign a font name that appears in the document’s library and in the Font drop-down menu in the Property inspector (if you have a text field selected on the Stage).antiAliasType property. in which you can select a font to embed in the SWF file (including a font style and font size). TIP advanced To use ActionScript to set anti-alias text. To set values for the TextField. c. The Linkage Properties dialog box appears. 2.Setting anti-alias with ActionScript Flash 8 offers two types of anti-aliasing: normal and advanced. which is available in Flash Player 8. and can be used only if you embed the font in the library and have the text field’s embedFonts property set to true. Macromedia does not recommend advanced anti-aliasing for fonts larger than 48 points. 3. use the following string values: normal Applies the regular text anti-aliasing. a. Click OK. d. About font rendering and anti-alias text 409 .

which specifies a font and font size to be used for a text field that will be created shortly. 240). Arial-10.setNewTextFormat(text_fmt).selectable = false.onData = function(src:String) { if (src != undefined) { my_txt. The code also sets the text formatting for the new text field to the TextFormat object that you created earlier. 410 Working with Text and Strings . Add the following ActionScript to Frame 1 of the main Timeline: var text_fmt:TextFormat = new TextFormat(). After the document is fully loaded (but not parsed). }. you must set embedFonts to true for the text field instance. The preceding code is separated into four key areas. text_fmt. 10. advanced_mc. text_fmt. so that they are displayed on the Stage. and click OK. var lorem_lv:LoadVars = new LoadVars(). The specified font. is the linkage identifier for the font symbol that you embedded in a previous step.size = 10. lorem_lv.onRelease = function() { my_txt. The third block of code defines a LoadVars instance that populates the text field on the Stage with the contents of an external text file. } }.com/flash/lorem. my_txt. The first block of code creates a new TextFormat object. the entire contents of the file are copied into the my_txt.wordWrap = true. my_txt. lorem_lv.antiAliasType = "advanced". this. 20. normal_mc.txt").embedFonts = true.". 20.text = "unable to load text file. The second block of code creates a new text field with the instance name my_txt.load("http://www.autoSize = "left". my_txt. Select the Export for ActionScript and Export in First Frame options. 320. my_txt.font = "Arial-10". 6.createTextField("my_txt". }.text property. In order for the font to be properly embedded.text = src. } else { my_txt.5.antiAliasType = "normal".multiline = true.helpexamples. my_txt. enter the linkage identifier Arial-10.onRelease = function() { my_txt. my_txt.

You can find the sample source file. When the user clicks and releases either one of these options. An inside cutoff value. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/FlashType. browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\FlashType. Advanced anti-aliasing uses adaptively sampled distance fields (ADFs) to represent the outlines that determine a glyph (a character). Click the advanced_mc movie clip on the Stage. the anti-alias type for the text field on the Stage changes. such as 255. When you are dealing with text fields with a smaller font size. Between these two cutoff values. the mapping function is a linear curve ranging from 0 at the outside cutoff to the maximum density at the inside cutoff. below which densities are set to 0. and final. above which densities are set to a maximum density value. Select Control > Test Movie to test your Flash document. setting the anti-aliasing to advanced can dramatically improve the readability of the text. In Windows. TIP For information on formatting anti-alias text. 7. This sample also demonstrates how text fields can scroll quickly and smoothly when you use the cacheAsBitmap property. A sample file on your hard disk shows how to apply and manipulate anti-aliased text in an application. see “Using a grid fit type” on page 417 and “About formatting anti-alias text” on page 414. flashtype. 8. On the Macintosh. Clicking the movie clip switches the anti-alias type from normal (the default) to advanced.The fourth. Advanced anti-aliasing allows font faces to be rendered at high quality at small sizes. Macromedia does not recommend advanced anti-aliasing for fonts larger than 48 points.fla. 9. About font rendering and anti-alias text 411 . block of code defines onRelease event handlers for both the normal_mc movie clip and the advanced_mc movie clip. You use the FlashType rendering technology to create small text that’s highly legible. Setting tables for fonts If you create fonts for use in SWF files or for distribution to Flash developers. It is best used with applications that have a lot of small text. in the Samples folder on your hard disk. Flash uses two values: ■ ■ An outside cutoff value. you may need to set tables for fonts to control how they render on the Stage. Save your changes to the FLA file.

high contrast edges at small point sizes and softer edges for animated text and larger point sizes. Select Arial from the Font pop-up menu. Select both the Bold and Italics options. the resulting density image is a bilevel bitmap. more filtered edge. b. 4. Adjusting these parameters to shift the midpoint toward negative infinity increases the stroke weight. Create a new Flash document and save it as advancedaatable. c. the resulting density image has a watercolor-like edge. When the spacing is 0. When the spacing is very wide. For more information on creating an anti-aliasing table. NO T E Flash Player includes advanced anti-aliasing settings for ten basic fonts. The outside cutoff typically has a negative value. shifting the midpoint toward positive infinity decreases the stroke weight. Select Export for ActionScript and Export in First Frame. Type Arial-embedded in the Identifier text box. a narrow spacing provides a sharper edge. The setAdvancedAntialiasingTable() method lets you set custom anti-aliasing data for other fonts and font sizes. Click OK. or to override the default settings for the provided fonts. Enter the font name Arial (embedded) in the Name text box and click OK. the inside cutoff has a positive value. The spacing between these two parameters is comparable to twice the filter radius of classic antialiasing methods. all sizes below 6 use the settings for 6. 3.fla. and then set the font size to 32 points. advanced anti-aliasing settings are provided only for the font sizes from 6 to 20. Typically. and for these fonts. 5. 2. and select Linkage. In the Linkage Properties dialog box: a. For these fonts. 7. users prefer sharp. Other fonts map to the supplied font data. see the following example: To create an advanced anti-aliasing table for an embedded font: 1.Adjusting the outside and inside cutoff values affects stroke weight and edge sharpness. 412 Working with Text and Strings . 6. and their midpoint lies near 0. Select New Font from the Library panel pop-up menu. while a wider spacing provides a softer. The outside cutoff should always be less than or equal to the inside cutoff. Right-click (Windows) or Control-click (Macintosh) the font symbol in the library. and all sizes above 20 use the settings for 20.

width-20. arialTable).createTextField("my_txt". The next section of code creates a new text field with a my_txt instance name.load("http://www. var lorem_lv:LoadVars = new LoadVars(). my_fmt.antiAliasType = "advanced".0.helpexamples. "dark". var my_fmt:TextFormat = new TextFormat(). 999. Stage.onData = function(src:String):Void { if (src != undefined) { my_txt. arialTable. The second section of code defines a new TextFormat object.align = "justify".sharpness = 0. arialTable. lorem_lv. my_txt.416}). insideCutoff:2.txt").push({fontSize:16.0.516. my_fmt. TextRenderer. my_txt. outsideCutoff:-2. The preceding code is separated into four sections.font = "Arial-embedded". and enables multiline text and word wrapping.multiline = true. Stage. insideCutoff:0. } }. my_txt.height-20). my_txt.wordWrap = true. outsideCutoff:0.8. my_txt. The final block of code defines a LoadVars object that you use to load text from an external text file. var arialTable:Array = new Array(). 10.text = src + "\n\n" + src. and populate the text field on the Stage.setAdvancedAntialiasingTable("Arial".TextRenderer. Select Control > Test movie to test the Flash document.text. my_txt. my_txt. 10. "bolditalic". my_fmt.push({fontSize:32. enables advanced anti-aliasing. and add the following ActionScript in the Actions panel: import flash.embedFonts = true.thickness = 0.8.com/flash/lorem. which you use to apply text formatting to the text field (that you create in the next section of code). this.size = 32.setNewTextFormat(my_fmt).8}). The first section of code imports the TextRenderer class and defines a new anti-aliasing table for two different sizes of the Arial font. } else { trace("error downloading text file"). applies the text format object (created earlier). About font rendering and anti-alias text 413 . 9. lorem_lv. Select Frame 1 of the main Timeline.

Setting a font’s thickness is similar to enabling bold formatting for a text field. For information on formatting text. For more information on text layout and text formatting using the TextFormat class. Setting sharpness to a lower value makes the font appear softer. The TextFormat class provides a great deal of control over how the text appears at runtime. see “Using a grid fit type” on page 417. About text layout and formatting You can control text layout and formatting by using ActionScript. Flash displays some text in the text field. Moving the mouse pointer along the y axis sets the thickness between -200 and 200. see “Using the TextFormat class” on page 419 and TextFormat in the ActionScript 2. For more information on the TextFormat class. This helps you to control the appearance of the characters at runtime. see “About formatting anti-alias text” on page 414. 414 Working with Text and Strings . The embedded font on the Stage should appear like it has a slight blur effect because of the current insideCutoff and outsideCutoff values. The following example dynamically loads a text file and displays text on the Stage. the bolder the font appears. The higher the thickness. and you can see the advanced anti-aliasing table properties applied to your text field. see “About text fields” on page 383. For general information on text fields.0 Language Reference. You can also control how characters fit on the grid by using ActionScript when you use antialias text in a SWF file. For an example of how to use a grid fit type in your applications. with more blurring. A high value for sharpness makes the embedded font edge appear jagged and sharp.After the text loads from the remote server. see the following sections: ■ ■ ■ ■ “About formatting anti-alias text” on page 414 “Using a grid fit type” on page 417 “Using the TextFormat class” on page 419 “Default properties of new text fields” on page 421 About formatting anti-alias text Flash 8 introduces two new properties that you can use when you format text fields with advanced anti-aliasing enabled: sharpness and thickness. Moving the mouse pointer along the x axis sets the sharpness between -400 and 400. Sharpness refers to the amount of aliasing that is applied to the text field instance. in addition to other forms of formatting such as style sheets (see “Formatting text with Cascading Style Sheet styles” on page 421) and HTML text (see “Using HTML-formatted text” on page 436).

sharpness = (_xmouse * (800 / Stage. 6. Right-click the font symbol in the library and select Linkage to open the Linkage Properties dialog box. lorem_txt. Stage. debug_txt.autoSize = "left".400. 4. this. 20.width. Select Arial from the Font drop-down menu and set the font size to 24 points. lorem_txt.autoSize = "left".background = 0xFFFFFF. }.width.thickness). Set the linkage identifier to Arial-24. debug_txt.20)). 5.antiAliasType = "advanced". 2.createTextField("lorem_txt". } lorem_lv. 7.fla. lorem_txt.thickness = (_ymouse * (400 / Stage. 100.height .setNewTextFormat(my_fmt). select the Export for ActionScript and Export in First Frame check boxes. my_fmt.com/flash/lorem.embedFonts = true.addListener(mouseListener).text = "loading.200. 0. Stage.onData = function(src:String) { lorem_txt. lorem_txt.. 20). 10. this. 3. lorem_lv.text = "sharpness=" + Math.height)) . (Stage.text = src.txt"). lorem_txt. 0.round(lorem_txt.". Enter the font name of Arial-24 (embedded) in the Name text box and click OK.size = 24. mouseListener. var lorem_lv:LoadVars = new LoadVars(). my_fmt. About text layout and formatting 415 . Add the following code to Frame 1 of the main Timeline: var my_fmt:TextFormat = new TextFormat(). Select New Font from the pop-up menu in the upper-right corner of the Library panel.helpexamples. lorem_txt.width)) . and click OK.sharpness) + ". lorem_txt.round(lorem_txt.load("http://www.wordWrap = true.font = "Arial-24". Create a new Flash document and save it as sharpness. thickness=" + Math.onMouseMove = function():Void { lorem_txt. debug_txt. 0.To modify a text field’s sharpness and thickness: 1. var mouseListener:Object = new Object()..createTextField("debug_txt". Mouse.

The first section of code defines a new TextFormat instance that will be applied to a dynamically created text field. flashtype. The fifth. and sets the antiAliasType property to true. lorem_txt. The sharpness and thickness properties are set for the lorem_txt text field. On the Macintosh. “Font rendering options in Flash” on page 408. This sample also demonstrates how text fields can scroll quickly and smoothly when you use the cacheAsBitmap property. and “Using a grid fit type” on page 417. 416 Working with Text and Strings . The second text field. debug_txt. and the current values are displayed in the debug_txt text field.displays the current sharpness and thickness values for the lorem_txt text field. For more information on using anti-alias text in a SWF file. Move the mouse pointer along the x axis to change the text field’s sharpness. applies the custom text formatting object created earlier. 8. browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\FlashType. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/FlashType. A sample file on your hard disk shows how to apply and manipulate anti-aliased text in an application. section of code defines a mouse listener that is called whenever the mouse pointer moves on the Stage. which is responsible for loading the external text file and populating the lorem_txt text field. The fourth section of code creates a LoadVars object. The next two sections create two new text fields on the Stage.fla. Move the mouse pointer along the y axis to cause the text field’s thickness to change. Select Control > Test Movie to test the document. In Windows. You use the FlashType rendering technology to create small text that’s highly legible. see “Setting anti-alias with ActionScript” on page 409. You can find the sample source file. The current values for sharpness and thickness are calculated based on the current position of the mouse pointer on the Stage. in the Samples folder on your hard disk. The first text field. Move the mouse pointer from left to right to cause the sharpness to increase and appear more jagged.This ActionScript code can be separated into five key sections. and final. enables embedded fonts.

4.fla. Click OK. Type the font name Arial-10 (embedded) in the Name text box and click OK. 6. pixel none Specifies that strong horizontal and vertical lines are fit to the pixel grid. Horizontal and vertical lines in the glyphs are not forced to the pixel grid. The subpixel setting is generally good for right-aligned and center-aligned dynamic text. This setting is usually good for animation and for large font sizes. 2. About text layout and formatting 417 . 7. and then select the Export for ActionScript and Export in First Frame check boxes. three types of grid fitting are available: Specifies no grid fitting. Right-click the font symbol in the library and select Linkage to open the Linkage Properties dialog box. subpixel To set a grid fit type on a text field: 1. Select Arial font from the Font drop-down menu and set the font size to 10 points. The following example shows how to set a grid fit type on a text field by using ActionScript. Set the linkage identifier to Arial-10. 5. 3. Select New Font from the pop-up menu in the upper-right corner of the Library panel. and it is sometimes a useful trade-off for animation versus text quality. Specifies that strong horizontal and vertical lines are fit to the subpixel grid on an LCD monitor. Create a new Flash document and save it as gridfittype. This setting generally provides the best legibility for left-aligned text.Using a grid fit type When you use advanced anti-aliasing on a text field. This setting works only for left-aligned text fields.

pixel_txt. lorem_lv. none_txt. subpixel_txt. none_txt.helpexamples. 0. h*2. 20.8.. } }.wordWrap = true. none_txt. Add the following code to Frame 1 of the main Timeline: var my_fmt:TextFormat = new TextFormat()..embedFonts = true. subpixel_txt. subpixel_txt.antiAliasType = "advanced".wordWrap = true.createTextField("pixel_txt". none_txt.wordWrap = true.text = "[antiAliasType=none]\n" + src.size = 10.". 418 Working with Text and Strings .multiline = true. my_fmt.. subpixel_txt.text = "loading.txt").createTextField("subpixel_txt".text = "loading..setNewTextFormat(my_fmt).width. this. Stage.multiline = true. pixel_txt.width. subpixel_txt. h).embedFonts = true. 0.antiAliasType = "advanced".height / 3). subpixel_txt. pixel_txt. Stage.selectable = false. var lorem_lv:LoadVars = new LoadVars().text = "[antiAliasType=subpixel]\n" + src.text = "loading.text = "[antiAliasType=pixel]\n" + src.gridFitType = "subpixel". pixel_txt.". none_txt. this. var h:Number = Math. pixel_txt.setNewTextFormat(my_fmt).antiAliasType = "advanced".. 0.onData = function(src:String):Void { if (src != undefined) { none_txt. subpixel_txt. lorem_lv.gridFitType = "pixel".createTextField("none_txt". subpixel_txt. 0. pixel_txt.embedFonts = true.com/flash/lorem. none_txt. none_txt.floor(Stage. pixel_txt. Stage. } else { trace("unable to load text file"). pixel_txt. h).gridFitType = "none".multiline = true. 30. h. this.font = "Arial-10".width. h).load("http://www. 10. pixel_txt. my_fmt."..setNewTextFormat(my_fmt).

section creates a LoadVars instance. each text field displays some formatted sample text using a different grid-fit type. and sets the grid fit type to normal. The second.”. or subpixel. Each text field should be initialized with the value “loading. Save the document and select Control > Test movie to test the SWF file.. see setTextFormat (TextField. or to the entire body of text in a text field. TI P Using the TextFormat class You can use the TextFormat class to set the formatting properties of a text field. pixel. and fourth sections of code each create a new dynamic text field on the Stage and set some common properties: antiAliasType (which must be set to advanced). multiline. About text layout and formatting 419 . Paragraph formatting information describes the appearance of a paragraph: left margin. color. to groups of characters. size and font. you first create a TextFormat object and set its character and paragraph formatting styles.setNewTextFormat() method. however—such as text entered by a user or inserted with ActionScript—does not assume the formatting specified by a setTextFormat() call.setTextFormat method) and setNewTextFormat (TextField. The fifth. The TextFormat class incorporates character and paragraph formatting information. The setTextFormat() method changes the text format that is applied to individual characters. and wordWrap. The font property refers to the linkage identifier of the font symbol currently in the document library. and an associated URL.setNewTextFormat method) in the ActionScript 2.The preceding ActionScript code can be separated into five sections. Each section also applies the text format object created in an earlier section. The first section defines a new text format object that specifies two properties. Character formatting information describes the appearance of individual characters: font name. After the external text file is successfully loaded. and final. right margin. or center alignment. 9.. use TextField. third. and left. To specify the default formatting for newly inserted text.setNewTextFormat(). indentation of the first line. To use the TextFormat class. right.0 Language Reference. point size. Newly inserted text. The FlashType rendering technology uses grid fitting only at 0º rotation. embedFonts (set to true).setTextFormat() or TextField. which loads the contents of an external text file into each of the text fields that you created with code. For more information. You then apply the TextFormat object to a text field using the TextField.

Select Control > Test Movie to test the application.setTextFormat(0. txt_fmt. 4. Apply the TextFormat object to the text field you created in step 1 by using TextField. and select Multiline from the Line Type pop-up menu. Enter the following code in the Actions panel to create a TextFormat object. In the Property inspector. type myText_txt in the Instance Name text box. Type some text in the text field on the Stage. Select Frame 1 on the Timeline and open the Actions panel (Window > Actions). txt_fmt). see setTextFormat (TextField.size = 24. and set the size property to 24: // Create a TextFormat object. txt_fmt.setTextFormat(): myText_txt. 5. such as Bold. txt_fmt. italic. 6.To format a text field with the TextFormat class: 1. 3.italic = true.0 Language Reference. For example. create a text field on the Stage using the Text tool. 24 point text.setTextFormat method) in the ActionScript 2. 24-point formatting to the first three characters you entered in the text field: myText_txt. In a new Flash document. italic. 2. For more information. set the bold and italic properties to true. var txt_fmt:TextFormat = new TextFormat().setTextFormat(txt_fmt). see the following topics: ■ ■ 420 Working with Text and Strings . This version of setTextFormat() applies the specified formatting to the entire text field. // Specify paragraph and character formatting. the following code applies bold.bold = true. Two other versions of this method let you apply formatting to individual characters or groups of characters. “Default properties of new text fields” on page 421 “Formatting text with Cascading Style Sheet styles” on page 421 For more information on using the TextFormat class. 3. select Dynamic from the Text Type pop-up menu.

Each rule associates a style name. see TextFormat in the ActionScript 2. the following style defines a selector named bodyText: . Formatting text with Cascading Style Sheet styles Cascading Style Sheet (CSS) styles are a way to work with text styles that can be applied to HTML or XML documents. N OT E For a complete list of TextFormat methods and their descriptions.Default properties of new text fields Text fields created at runtime with createTextField() receive a default TextFormat object with the following properties: align = "left" blockIndent = 0 bold = false bullet = false color = 0x000000 font = "Times New Roman" (default font is Times on Mac OS X) indent = 0 italic = false kerning = false leading = 0 leftMargin = 0 letterSpacing = 0 rightMargin = 0 size = 12 tabStops = [] (empty array) target = "" underline = false url = "" The default font property on the Mac OS X is Times. A style sheet is a collection of formatting rules that specify how to format HTML or XML elements.0 Language Reference. For example. with one or more style properties and their values. or selector.bodyText { text-align: left } Formatting text with Cascading Style Sheet styles 421 .

browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\LoadText. To apply a style sheet to a text field that contains HTML. formattedText. On the Macintosh. You use the TextField. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/LoadText. or define new tags.0 Language Reference).StyleSheet class to work with text style sheets. you use the TextField. The styles defined in the style sheet are mapped automatically to the tags defined in the HTML or XML document. either by loading them from an external CSS file or by creating new styles with ActionScript.or XML-formatted text.StyleSheet class (for more information see StyleSheet (TextField.styleSheet property. 422 Working with Text and Strings .or XML-formatted text. You can also create style classes that can be applied to specific HTML elements using the <p> or <span> tag’s class attribute.You can create styles that redefine built-in HTML formatting tags that Flash Player uses (such as <p> and <li>). You can load styles from an external CSS file or create them natively using ActionScript.fla. “Supported CSS properties” on page 423 “Creating a style sheet object” on page 424 “Loading external CSS files” on page 424 “Creating new styles with ActionScript” on page 426 “Applying styles to a TextField object” on page 427 “Applying a style sheet to a TextArea component” on page 427 “Combining styles” on page 429 “Using style classes” on page 429 “Styling built-in HTML tags” on page 430 “An example of using styles with HTML” on page 431 “Using styles to define new tags” on page 433 “An example of using styles with XML” on page 434 ■ ■ For more information. see the following topics: ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ You can find a sample source file. Assign the style sheet to a TextField object that contains HTML. Although the TextField class can be used with Flash Player 6.StyleSheet) in the ActionScript 2. Using styles sheets involves the following three basic steps: ■ Create a style sheet object from the TextField.StyleSheet class requires that SWF files target Flash Player 7 or later. in the Samples folder on your hard disk. the TextField. which shows you how to apply CSS formatting to text that you load into a SWF file at runtime. Add styles to the style sheet object. In Windows.

pt) are not parsed. Recognized values are true and false. pt) are not parsed. Only the numeric part of the value is used. Units (px. pt) are not parsed. Recognized values are normal and bold. text-decoration margin-left textDecoration marginLeft margin-right marginRight font-weight kerning font-style letterSpacing fontWeight kerning fontStyle letterSpacing text-indent textIndent Formatting text with Cascading Style Sheet styles 423 . Units (px. center. The following table shows the supported CSS properties and values as well as their corresponding ActionScript property names. and justify. Only the numeric part of the value is used. pt) are not parsed. Only the numeric part of the value is used. Units (px. pixels and points are equivalent. Recognized values are normal and italic.Supported CSS properties Flash Player supports a subset of properties in the original CSS1 specification (www. Units (px. (Each ActionScript property name is derived from the corresponding CSS property name. Only the numeric part of the value is used. pixels and points are equivalent.org/ TR/REC-CSS1).) CSS property ActionScript property text-align font-size textAlign fontSize Usage and supported values Recognized values are left.w3. Recognized values are none and underline. Only the numeric part of the value is used. pixels and points are equivalent. pt) are not parsed. pixels and points are equivalent. pixels and points are equivalent. right. the hyphen is omitted and the subsequent character is capitalized. Units (px.

color color Creating a style sheet object CSSs are represented in ActionScript by the TextField. which shows you how to apply CSS formatting to text that you load into a SWF file at runtime. you can either load an external CSS file into the object or define the styles in ActionScript. If you specify a generic font name. Named colors (such as blue) are not supported. and serif is converted to _serif. in descending order of desirability. Only hexadecimal color values are supported.StyleSheet class.StyleSheet(). use the style sheet object’s onLoad event handler.CSS property ActionScript property font-family fontFamily Usage and supported values A comma-separated list of fonts to use. On the Macintosh. To create a style sheet object. 424 Working with Text and Strings . To determine when the CSS file has finished loading. call the constructor function of the TextField. you use the load() method of the TextField. sans-serif is converted to _sans. The styles defined in the CSS file are added to the style sheet object. This class is available only for SWF files that target Flash Player 7 or later. it is converted to an appropriate device font. See “Loading external CSS files” on page 424 and “Creating new styles with ActionScript” on page 426.StyleSheet class: var newStyle:TextField. To load an external CSS file. in the Samples folder on your hard disk. Colors are written in the following format: #FF0000. formattedText.StyleSheet class. In Windows. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/LoadText. browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\LoadText. Loading external CSS files You can define styles in an external CSS file and then load that file into a style sheet object. Any font family name can be used.StyleSheet = new TextField.fla. The following font conversions are available: mono is converted to _typewriter. You can find a sample source file. To add styles to a style sheet object.

make sure the FLA file and the CSS file are in the same directory and that you typed the name of the CSS file correctly. Test the Flash document (Control > Test Movie).sans-serif. N O TE In the previous code snippet.load("styles. font-size: 24px..bodyText { font-family: Arial. create a new FLA file.StyleSheet. } 3. } else { trace("Error loading CSS file.” in the Output panel. 4.StyleSheet().getStyleNames() method to retrieve the names of the loaded styles.").headline If you see “Error loading CSS file. In Flash. create a new file.css. you create and load an external CSS file and use the TextField. Formatting text with Cascading Style Sheet styles 425 .In the following example.Helvetica. 7. select Layer 1. Open the Actions panel (Window > Actions). Add the following style definitions to the file: . Save the CSS file as styles. In the Timeline (Window > Timeline).onLoad = function(success:Boolean):Void { if (success) { // display style names.sans-serif. trace(this.headline { font-family: Arial. styles. You should see the names of the two styles in the Output panel: . styles. 2. Add the following code to the Actions panel: var styles:TextField. font-size: 12px.css"). 8.Helvetica. 6. } . 5.bodyText. Save the FLA file to the same directory that contains styles. In your preferred text or CSS editor.StyleSheet = new TextField.getStyleNames() refers to the styles object you constructed in the first line of ActionScript. 9.css. } }.getStyleNames()). To load an external style sheet: 1. this.

StyleSheet().StyleSheet) in the ActionScript 2.sans-serif'. {fontFamily: 'Arial. in the Samples folder on your hard disk. the CSS file must reside in the same domain as the SWF file that is loading the file.) For more information on using CSS with Flash. You can find a sample source file.setStyle("bodyText". For example.StyleSheet = new TextField. fontSize: '12px'} ). which shows you how to apply CSS formatting to text that you load into a SWF file at runtime. browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\LoadText. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/LoadText. This method takes two parameters: the name of the style and an object that defines that style’s properties.Helvetica. Creating new styles with ActionScript You can create new text styles with ActionScript by using the setStyle() method of the TextField. fontSize: '24px'} ). formattedText.Helvetica. {fontFamily: 'Arial. 426 Working with Text and Strings . In Windows. (See “Cross-domain and subdomain access between SWF files” on page 696.fla. styles.setStyle("headline". the following code creates a style sheet object named styles that defines two styles that are identical to the ones you already imported (see “Loading external CSS files” on page 424): var styles:TextField. styles.StyleSheet class.sans-serif'. see StyleSheet (TextField.As with all other ActionScript methods that load data over the network. On the Macintosh.0 Language Reference.

Create a new Flash document and save it as textareastyle.fla. Formatting text with Cascading Style Sheet styles 427 .StyleSheet class. or associated variable is stored verbatim. The following examples create a style sheet object. always contain the same value and behave identically.styleSheet = styles. The capitalization indicates the difference. htmlText property. The text field becomes read-only and cannot be edited by the user. and any variable associated with the text field. and assign it to the myTextArea component instance. you create a style sheet object and assign it HTML styles using the TextField. Do not confuse the TextField. The setTextFormat() and replaceSel() methods of the TextField class no longer function with the text field. Drag a TextArea component from the User Interface folder of the Components panel to the Stage and give it an instance name of myTextArea. Using a style sheet with a TextArea component: 1. You then assign the style sheet to the TextArea component’s styleSheet property.Applying styles to a TextField object To apply a style sheet object to a TextField object. styles. textObj_txt. you assign the style sheet object to the text field’s styleSheet property. Any text assigned to the text field’s text property. 2. Applying a style sheet to a TextArea component To apply a style sheet to a TextArea component. anything written to one of these properties can be retrieved in the text’s original form. The only way to change the field is by altering the text field’s text or htmlText property or by changing the text field’s associated variable. the following changes occur to the text field’s normal behavior: The text field’s text and htmlText properties.styleSheet property with the TextField. NO T E ■ ■ ■ ■ When you assign a style sheet object to a TextField object.StyleSheet class.

The preceding block of code creates a new TextField.setStyle("h1".Helvetica. set styleSheet property to the style sheet object.Helvetica. color:'#0000FF'}). Set html property to true.helpexamples. myVars.sans-serif'. myTextArea. /* Assign the style sheet object to myTextArea component.onData = function(myStr:String):Void { if (myStr != undefined) { myTextArea. var myVars:LoadVars = new LoadVars(). the style sheet object is applied to the TextArea component and HTML formatting is enabled. fontSize:'24px'. styles.html = true.com/flash/myText. styles. 428 Working with Text and Strings . The remaining ActionScript defines a LoadVars object that loads an external HTML file and populates the text area with the loaded text. color:'#006600'}).sans-serif'.setStyle("html". } else { trace("Unable to load text file.StyleSheet().3. // Define onData handler and load text to be displayed. {fontFamily:'Arial. var styles:TextField. and h1 HTML tags. Next.setStyle("body". fontSize:'12px'.StyleSheet = new TextField. body. myVars. 4. Add the following ActionScript to Frame 1 of the main Timeline: // Create a new style sheet object and set styles for it. Select Control > Test Movie to test the Flash document.text = myStr.htm")."). */ myTextArea. styles. } }.styleSheet = styles.StyleSheet instance that defines three styles: for the html. {color:'#00CCFF'. textDecoration:'underline'}).{fontFamily:'Arial.load("http://www.

sans-serif. When applied to a <p> tag. The mainBody style contributes color. Using style classes You can create style “classes” (not true ActionScript 2. font-size. The word emphatic will be formatted using a combination of the rules specified by mainBody and emphasized. with one <emphasized>emphatic</emphasized> word. the style affects the entire paragraph. the following style sheet defines two style classes: mainBody and emphasis: . and decoration rules. font-size: 24px.Combining styles CSS styles in Flash Player are additive. font-style: italic. as shown in the following snippet: <p class='mainBody'>This is <span class='emphasis'>really exciting!</ span></p> Formatting text with Cascading Style Sheet styles 429 .</mainBody> For the word emphatic in the above text. each level of nesting can contribute style information.mainBody { font-family: Arial. You can also style a span of text that uses a style class using the <span> tag.0 classes) that you can apply to a <p> or <span> tag using either tag’s class attribute. which is added together to result in the final formatting. you can apply these styles to <p> and <span> tags.emphasis { color: #666666. when styles are nested. The emphasized style adds a font-weight rule to these rules. the emphasized style is nested within the mainBody style. that is.Helvetica. } Within HTML text you assign to a text field. The following example shows some XML data assigned to a text field: <sectionHeading>This is a section</sectionHeading> <mainBody>This is some main body text. } . For example.

Affects all <a> anchor tags. After the mouse pointer moves off the link. For example. After the mouse button is released.) You can assign a CSS style to every instance of a built-in HTML tag that appears in a text field.sans-serif. display: inline. This style is applied after any a and a:link style. } The following table shows which built-in HTML tags can be styled and how each style is applied: Style name How the style is applied p body Affects all <p> tags. Affects all <li> bullet tags. the a:hover style is removed from the link. Affects all <body> tags. Applied to an <a> anchor tag when the mouse pointer is over the link. Applied to an <a> anchor tag when the user clicks the link. The p style. (For more information. p { font-family: Arial. Affects all <a> anchor tags. font-size: 12px. the a:active style is removed from the link. if specified. This style is applied after any a and a:link style. All instances of that tag are styled in the manner specified by the style rule. li a a:link a:hover a:active 430 Working with Text and Strings . takes precedence over the body style. This style is applied after any a style. the following code defines a style for the built-in <p> HTML tag. see “Using HTMLformatted text” on page 436.Styling built-in HTML tags Flash Player supports a subset of HTML tags.Helvetica.

display: block. } This style sheet defines styles for two built-in HTML tags (<p> and <a>) that will be applied to all instances of those tags.An example of using styles with HTML This section presents an example of using styles with HTML tags.Helvetica.Helvetica. font-size: 18px. display: inline.headline and .css. Formatting text with Cascading Style Sheet styles 431 . font-family: Arial.sans-serif. Create a new file in your preferred text or CSS editor.byline) that will be applied to specific paragraphs and text spans. font-family: Arial. Add the following style sheet definition to the file: p { color: #000000. font-size: 12px. you can apply that style sheet to a TextField object that contains HTML-formatted text. } . It also defines two style classes (.byline { color: #666600. To format HTML with a style sheet: 1. display: inline.headline { color: #000000. } a:link { color: #FF0000. Then. Save the file as html_styles. 3. font-weight: bold. font-weight: bold. You can create a style sheet that styles some built-in tags and defines some style classes. font-style: italic. } . 2.sans-serif. } a:hover{ text-decoration: underline.

// Define onLoad handler and Load CSS file. and add the following code to the Actions panel: this. 99. Create a new text file in a text or HTML editor. */ news_txt. 432 Working with Text and Strings . announced today a new version of Flash that features a brand new font rendering technology called FlashType. 300).html = true.4. // Location of CSS and text files to load.htm".StyleSheet = new TextField. then assign it to the text object. N OT E 5. Create a new Flash document in the Flash authoring tool. news_txt.styleSheet = styles. var styles:TextField.css". Select the first frame in Layer 1 in the Timeline (Window > Timeline). and assign the HTML text to the text field. var txt_url:String = "myText. // Create a new style sheet and LoadVars object.</a></p> If you copy and paste this text string. make sure that you remove any line breaks that might have been added to the text string. } else { trace("Unable to load HTML file").onLoad = function(success:Boolean):Void { if (success) { /* If the style sheet loaded without error. } }. and save the document as myText. news_txt. var css_url:String = "html_styles. Add the following text to the file: <p class='headline'>Flash adds FlashType rendering technology!</ p><p><span class='byline'>San Francisco. styles. For more information. // Define onData handler and load text to display.onData = function(src:String):Void { if (src != undefined) { news_txt.htmlText = src.StyleSheet().multiline = true. news_txt.com'>Macromedia Flash web site. 6. news_txt. 50. 450. visit the <a href='http:// www. CA</span>--Macromedia Inc.createTextField("news_txt".wordWrap = true.load(txt_url). var myVars_lv:LoadVars = new LoadVars(). Open the Actions panel (Window > Actions). myVars_lv. myVars_lv.text = storyText. 7. most excellent at rendering small text with incredible clarity and consistency across platforms. news_txt.border = true.htm. 50.macromedia.

} }. Helvetica. the following style sheet creates the new styles sectionHeading. This feature lets you assign arbitrary XML-formatted text directly to a text field. </mainBody> Formatting text with Cascading Style Sheet styles 433 . if a style sheet defines a CSS style named sectionHeading. you can use <sectionHeading> as an element in any text field associated with the style sheet. For example."). and emphasized: . font-size: 12px.mainBody { color: #000099.} else { trace("Unable to load CSS file. display: inline } You could then populate a text field associated with that style sheet with the following XMLformatted text: <sectionHeading>This is a section</sectionHeading> <mainBody>This is some main body text. see Chapter 15. Select Control > Test Movie to see the styles applied to the HTML text automatically.” N OT E 8. and Video. in the same way as you would use a built-in HTML tag. For example. mainBody. styles. display: block } . display: block } . with one <emphasized>emphatic</emphasized> word. that style can be used as a tag. you are loading the text from an external file.emphasized { font-weight: bold. so that the text is automatically formatted using the rules in the style sheet.fla in the same directory that contains the CSS file you created in step 3. font-size: 18px.sectionHeading { font-family: Verdana.load(css_url). 9. text-decoration: underline. In this ActionScript. Arial. “Working with Images. For information on loading external data. Using styles to define new tags If you define a new style in a style sheet. sans-serif. Sound. Save the file as news_html.

setStyle("byline". select Multiline from the Line Type menu. 434 Working with Text and Strings . and type news_txt in the Instance Name text box. select the Render Text as HTML option. 5.setStyle("a:hover".Helvetica. styles. display:'block' }).sans-serif'. styles. fontFamily:'Arial. display:'block'. 4. fontWeight:'bold' }). To create the style sheet object.setStyle("mainBody".Helvetica. fontFamily:'Arial. { color:'#000000'. you create a FLA file that has XML-formatted text. styles. open the Actions panel (Window > Actions). { color:'#FF0000' }). create a text field approximately 400 pixels wide and 300 pixels high. styles.setStyle("title". { color:'#666600'. 2. display:'inline' }). rather than importing styles from a CSS file as shown in “An example of using styles with HTML” on page 431 To format XML with a style sheet: 1. { color:'#000000'. and select the text field. { textDecoration:'underline' }). In Flash. create a FLA file. Open the Property inspector (Window > Properties > Properties).An example of using styles with XML In this section. fontWeight:'bold'. fontSize:'18'. and add the following code to the Actions panel: var styles:TextField. Using the Text tool. fontSize:'12'. select Dynamic Text from the Text Type menu. 6. On Layer 1 in the Timeline (Window > Timeline). In the Property inspector. You’ll create a style sheet using ActionScript.setStyle("a:link". 3.StyleSheet(). styles.StyleSheet = new TextField. fontStyle:'italic'.sans-serif'. select the first frame.

announced today a new version of Flash that features the new FlashType rendering technology. For more information.xml.” N OT E 10. my_xml.com">Macromedia Flash website</a></mainBody></story> If you copy and paste this text string.ignoreWhite = true. my_xml.text = my_xml. This code loads the story. In Flash. assigns the style sheet object to the text field’s styleSheet property. the file as news_xml.fla in the same folder as story.macromedia. “Working with Images. } else { trace("Error loading XML. and Video. add the following code in the Actions panel. The styles exactly match the ones you created in an external CSS file earlier in this chapter. news_txt. and assigns the XML text to the text field: var my_xml:XML = new XML().This code creates a new style sheet object named styles that defines styles by using the setStyle() method. } }. Formatting text with Cascading Style Sheet styles 435 . my_xml. make sure that you remove any line breaks that might have been added to the text string. Run the SWF file (Control > Test Movie) to see the styles automatically applied to the text in the text field.load("story. You are loading XML data from an external file in this ActionScript. visit the <a href="http:// www. Select Hidden Characters from the pop-up menu in the Actions panel to see and remove any extra line breaks. following the code in step 6. 7.xml document.styleSheet = styles. Save the text file as story."). Sound. open a text editor and enter the following text into a new document: <story><title>Flash now has FlashType</title><mainBody><byline>San Francisco.onLoad = function(success:Boolean):Void { if (success) { news_txt. Save 11. NO T E 8. CA</byline>--Macromedia Inc.xml").xml. To create the XML text to assign to the text field. 9. For information on loading external data. see Chapter 15.

set the value of TextField. Flash Player also supports the <textformat> tag.htmlText = "<font face='Times New Roman' size='25'>This is how you assign HTML text to a text field. In ActionScript. GIF. and movie clips in text fields” on page 445 Required properties and syntax for using HTMLformatted text To use HTML in a text field. Text fields in Flash Player 7 and later also support the <img> tag. headline_txt. the following code enables HTML formatting for a text field named headline_txt and then assigns some HTML to the text field: this. headline_txt. 1.multiline = true. 10. 436 Working with Text and Strings .Using HTML-formatted text Flash Player supports a subset of standard HTML tags such as <p> and <li> that you can use to style text in any dynamic or input text field. ■ ■ For example. Flash Player automatically wraps text around images embedded in text fields in much the same way that a web browser wraps text around embedded images in an HTML page. and movie clips in text fields” on page 445. 500.</br>". 10. and <img>. SWF files. SWF files. PNG). SWF files. 300).html = true. <br>. you must set several properties of the text field. see the following topics: ■ ■ ■ ■ “Required properties and syntax for using HTML-formatted text” on page 436 “About supported HTML tags” on page 437 “About supported HTML entities” on page 444 “About embedding images. headline_txt. headline_txt. which lets you embed image files (JPEG. you must make the text field a multiline text field by selecting the Multiline option in the Property inspector or by setting the text field’s multiline property to true.</font><br>It's very useful. either in the Property inspector or by using ActionScript: ■ Enable the text field’s HTML formatting by selecting the Render Text as HTML option in the Property inspector or by setting the text field’s html property to true. For more information. which lets you apply paragraph formatting styles of the TextFormat class to HTML-enabled text fields. For more information. and movie clips in a text field.createTextField("headline_txt". To use HTML tags such as <p>. see “Using the TextFormat class” on page 419.wordWrap = true. see “About embedding images. For more information on HTML-formatted text.htmlText to the HTML-formatted text string you want to display.

myField_txt. 200). myField_txt.htmlText myField_txt. 10. 10.createTextField("myField_txt". = "<p align=\"left\">This uses escaped double quotes</ = '<p align="left">This uses outer single quotes</p>'.htmlText = "<p align=left>This is left-aligned text</p>". = '<p align=\'left\'>This uses escaped single quotes</ It’s not necessary to escape double quotation marks if you’re loading text from an external file.htmlText myField_txt. it’s necessary only if you’re assigning a string of text in ActionScript. Either of the following ways of doing this is acceptable: myField_txt. For example.To render HTML correctly. Attributes of HTML tags must be enclosed in double (") or single (') quotation marks. see the following topics: ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ “Anchor tag” on page 438 “Bold tag” on page 438 “Break tag” on page 438 “Font tag” on page 439 “Image tag” on page 439 “Italic tag” on page 440 “List item tag” on page 440 “Paragraph tag” on page 441 “Span tag” on page 441 “Text format tag” on page 442 “Underline tag” on page 443 Using HTML-formatted text 437 . If you enclose attribute values in double quotation marks. = "<p align='left'>This uses single quotes</p>". 10. Attribute values without quotation marks can produce unexpected results. see “Formatting text with Cascading Style Sheet styles” on page 421.htmlText p>". you must escape the quotation marks (\"). For more information on supported HTML tags.htmlText p>'. 400. the following HTML snippet cannot be rendered properly by Flash Player because the value assigned to the align attribute (left) is not enclosed in quotation marks: this. About supported HTML tags This section lists the built-in HTML tags that Flash Player supports. you must use the correct syntax. such as improper rendering of text. myField_txt.html = true. You can also create new styles and tags by using CSS.

See “Styling built-in HTML tags” on page 430.com in a new browser window: urlText_txt. _blank. and _top specifies the top-level frame in the current window. href target Specifies the name of the target window where you load the page. as shown in the following example: text3_txt. Absolute URLs must be prefixed with http://. You can also define a:link.htmlText = "The boy put on his coat. a:hover. You must set the text field to be a multiline text field to use this tag.com' target='_blank'>Go home</a>". Break tag The <br> tag creates a line break in the text field. 200. Options include _self.macromedia.Anchor tag The <a> tag creates a hypertext link and supports the following attributes: ■ A string of up to 128 characters that specifies the URL of the page to load in the browser. the following HTML code creates the link “Go home. 10. otherwise. Flash treats them as relative URLs. the line breaks between sentences: this.com. An example of an absolute reference to a URL is http:// www. ■ For example. The _self option specifies the current frame in the current window. _parent. text1_txt.<br />His coat was <font color='#FF0033'>red</font> plaid. In the following example. and a:active styles for anchor tags by using style sheets. and _top. N OT E 438 Bold tag The <b> tag renders text as bold. Working with Text and Strings . You can use the special asfunction protocol to cause the link to execute an ActionScript function in a SWF file instead of opening a URL. see asfunction protocol in the ActionScript 2.multiline = true.htmlText = "He was <b>ready</b> to leave!". text1_txt. A bold typeface must be available for the font used to display the text. 1. an example of a relative reference is /index.” which opens www.html.".0 Language Reference. For more information on the asfunction protocol. _blank specifies a new window. text1_txt. 10.createTextField("text1_txt". _parent specifies the parent of the current frame.macromedia. 100). The URL can be either absolute or relative to the location of the SWF file that is loading the page.html = true.macromedia.htmlText = "<a href='http://www.

and movie clips inside text fields and TextArea component instances. select Multiline from the Text Type menu. GIF.createTextField method).embedFonts property) in the ActionScript 2. For example. For more information on embedding fonts in Flash applications. in the Property inspector. Using HTML-formatted text 439 . The font tag supports the following attributes: ■ color Only hexadecimal color (#FFFFFF) values are supported. you can specify a list of comma-delimited font names. Text automatically flows around images you embed in text fields or components. To use this tag.</font>".htmlText = "<font face='Times. do one of the following: ■ In the Flash authoring environment. as shown in the following example: myText_txt.htmlText = "<font color='#FF0000'>This is red text</font>". select a text field on the Stage and then. in pixels. set the new text field instance’s multiline (TextField.. SWF files. You can also use relative point sizes instead of a pixel size.Font tag The <font> tag specifies a font or list of fonts to display the text. 24point text</font>". Times New Roman'>Displays as either Times or Times New Roman.multiline property) properties to true. To create a multiline text field with word wrapping. ■ The <img> tag has one required attribute. All other attributes are optional. ■ size Specifies the size of the font.htmlText = "<font size='24' color='#0000FF'>This is blue. Flash Player selects a substitute font. If the specified font is not installed on the user’s computer system or isn’t embedded in the SWF file.0 Language Reference and “Setting dynamic and input text options” in Using Flash. ■ face Specifies the name of the font to use. For a text field created at runtime with createTextField (MovieClip. a SWF file. Image tag The <img> tag lets you embed external image files (JPEG.multiline property) and multiline (TextField. see embedFonts (TextField. As shown in the following example.. in which case Flash Player selects the first available font: myText_txt. which specifies the path to an image file. you must set your dynamic or input text field to be multiline and to wrap text. or the linkage identifier of a movie clip symbol in the library. src. such as +2 or -4. the following HTML code creates red text: myText_txt. PNG).

as shown in the following code: That is very <i>interesting</i>. SWF files. id ■ Specifies the name for the movie clip instance (created by Flash Player) that contains the embedded image file. see “About embedding images. or movie clip being inserted. SWF file. and SWF files) do not show until they are downloaded completely. and movie clips in text fields” on page 445. PNG. This is useful if you want to control the embedded content with ActionScript. in pixels. Italic tag The <i> tag displays the tagged text in italics. all other attributes are optional. or the linkage identifier for a movie clip symbol in the library. The default value is 8. External files (JPEG. An italic typeface must be available for the font used. ■ ■ ■ width height align Specifies the horizontal alignment of the embedded image within the text field. The height of the image. This attribute is required. or movie clip being inserted. SWF file. The default value is left. The default value is 8. as shown in the following code: Grocery list: <li>Apples</li> <li>Oranges</li> <li>Lemons</li> This code example would render as follows: Grocery list: 440 Working with Text and Strings . SWF file. Specifies the amount of horizontal space that surrounds the image where no text appears.The <img> tag supports the following attributes: ■ src Specifies the URL to an image or SWF file. This code example would render as follows: That is very interesting. vspace For more information and examples of using the <img> tag. hspace ■ ■ Specifies the amount of vertical space that surrounds the image where no text appears. GIF. Valid values are left and right. or movie clip. List item tag The <li> tag places a bullet in front of the text that it encloses. in pixels. The width of the image.

test_txt. see “Formatting text with Cascading Style Sheet styles” on page 421.createTextField("test_txt". ■ Specifies alignment of text within the paragraph.".) The following example uses the align attribute to align text on the right side of a text field. 100). 1. 300. NO TE Paragraph tag The <p> tag creates a new paragraph.</ p>.StyleSheet object. right. myText_txt.StyleSheet = new TextField. myStyleSheet. valid values are left. fontSize:18}). 400. The following example uses the class attribute to assign a text style class to a <p> tag: var myStyleSheet:TextField. class Specifies a CSS style class defined by a TextField. and center. 0. Using HTML-formatted text 441 .styleSheet = myStyleSheet. so they do not modify how your list is rendered. 10. For more information on creating text style classes. (For more information. 0. myText_txt. 100).createTextField("myText_txt". myText_txt. see “Using style classes” on page 429.■ ■ ■ Apples Oranges Lemons Ordered and unordered lists (<ol> and <ul> tags) are not recognized by Flash Player.blue".multiline = true. test_txt.html = true. 10. 10. {color:'#99CCFF'.StyleSheet object.html = true. All list items use bullets.StyleSheet(). see “Using style classes” on page 429. Span tag The <span> tag is available only for use with CSS text styles. (For more information. You must set the text field to be a multiline text field to use this tag. test_txt. this.) It supports the following attribute: ■ class Specifies a CSS style class defined by a TextField.htmlText = "<p align='right'>This text is aligned on the right side of the text field</p>". this.htmlText = "<p class='blue'>This is some body-styled text. The <p> tag supports the following attributes: ■ align justify.setStyle(".

rightMargin. (See leading (TextFormat. indent ■ Specifies the indentation from the left margin to the first character in the paragraph. in points.leading. in points. indentation. leftmargin ■ ■ Specifies the left margin of the paragraph. margins.) ■ Specifies the right margin of the paragraph.0 Language Reference.leftMargin property) in the ActionScript 2. corresponds to TextFormat. (See leftMargin (TextFormat.0 Language Reference. corresponds to TextFormat. corresponds to TextFormat.Text format tag The <textformat> tag lets you use a subset of paragraph formatting properties of the TextFormat class within HTML text fields.0 Language Reference. The <textformat> tag has the following attributes: ■ Specifies the block indentation in points.) Specifies the amount of leading (vertical space) between lines.) leading TextFormat.tabStops. tabstops ■ Specifies custom tab stops as an array of non-negative integers.) blockindent TextFormat. (See tabStops (TextFormat.0 Language Reference. You can combine <textformat> tags with the built-in HTML tags.0 Language Reference.tabStops property) in the ActionScript 2.indent.blockIndent.) The following table of data with boldfaced row headers is the result of the code example in the procedure that follows: Name Rick AJ Age 33 34 Occupation Detective Detective 442 Working with Text and Strings .rightMargin property) in the ActionScript 2. corresponds to (See rightMargin (TextFormat. corresponds to Lets you use negative integers. corresponds to (See blockIndent (TextFormat.leading property) in the ActionScript 2.indent property) in the ActionScript 2.) rightmargin TextFormat. and tab stops. including line leading. (See indent (TextFormat.leftMargin. Lets you use negative integers.blockIndent property) in the ActionScript 2.0 Language Reference.

The use of the tab character escape sequence (\t) adds tabs between each column in the table. 99. table_txt. and save it as tabstops.htmlText += row_2 .html = true. var row_2:String = "AJ\t34\tDetective". // Sets two tabstops. as shown in the following code: This is <u>underlined</u> text. 100). table_txt.htmlText += rowHeaders. Underline tag The <u> tag underlines the tagged text. select the first frame on Layer 1. formatted in bold. var rowHeaders:String = "<b>Name\tAge\tOccupation</b>". 50.100]'>".To create a formatted table of data using tab stops: 1. table_txt. table_txt. table_txt.multiline = true. In the Timeline. var row_1:String = "Rick\t33\tDetective".htmlText += row_1. // Creates rows with data.htmlText = "<textformat tabstops='[50.fla. // Creates column headers. You append text using the += operator. and enter the following code in the Actions panel: // Create a new text field. at 50 and 100 points. table_txt. Create a new Flash document. 4. Open the Actions panel (Window > Actions). Select Control > Test Movie to view the formatted table. 3. 50. this.htmlText += "</textformat>".createTextField("table_txt". table_txt. 450. 2. This code would render as follows: Using HTML-formatted text 443 . separated by tabs.

Unicode). &gt. In addition to the greater-than and less-than symbols. Description < (less than) > (greater than) & (ampersand) " (double quotes) ' (apostrophe. 100.autoSize = "left". my_txt. 100. my_txt. 19).htmlText += "&#x007E. Entity &lt. (ampersand . the previous code example in Flash displays the following text on the Stage: The <b> tag makes text appear bold. you need to substitute HTML entities for those characters. To display less-than or greaterthan characters in HTML-formatted text fields in Flash. my_txt.html = true.htmlText = "&#126. 100. tag makes text appear <b>bold</b>.autoSize = "left". 100. &quot. 10. (ampersand . &apos. For example.createTextField("my_txt". // tilde (Unicode) 444 Working with Text and Strings . The following ActionScript demonstrates how you can use ASCII or Unicode character codes to embed a tilde (~) character: this. 10. 100.htmlText += "\t" my_txt. Flash also recognizes other HTML entities that are listed in the following table.". // tilde (ASCII) my_txt. so that they are not interpreted as HTML. 19). &amp. my_txt.b&gt.html = true. The following ActionScript creates an HTML formatted text field on the Stage and uses HTML entities to display the string “<b>” without having the text appear in bold: this. 100. you use less-than (<) and greater-than (>) characters to enclose HTML tags. single quote) Flash also supports explicit character codes. At runtime.About supported HTML entities HTML entities help you display certain characters in HTML formatted text fields. my_txt.createTextField("my_txt".htmlText = "The &lt.ASCII) and &#x0026.". such as <img> and <span>. such as &#39.". my_txt.

createTextField("image1_txt".htmlText = "<p>Here's a picture from my vacation:<img src='beach.createTextField("image2_txt". The preceding code creates a new dynamic text field on the Stage.gif'>". 2. see “Image tag” on page 439.com/flash/images/image2. SWF files. an image embedded in a text field appears on the line following the <img> tag. 400. GIF.html = true.) Flash displays media embedded in a text field at full size.fla. enables HTML formatting.html = true. The preceding code inserts a JPEG file that’s located in a directory that’s on a server. Embedding an image in a text field: 1. and TextArea component instances. the following example inserts a GIF file that’s located in the same directory as the SWF file (a relative address. However. image1_txt. For example. the image appears on the first line of the text field. image1_txt. Using HTML-formatted text 445 . PNG). JPEG. 200. use the <img> tag’s height and width attributes. 150). when the <img> tag is the first character in the text field. 50.About embedding images. (See “About specifying height and width values” on page 447. and movie clips inside dynamic and input text fields. SWF files. (For a full list of attributes for the <img> tag. on or offline). 10. 3. Add the following ActionScript below the code added in the previous step: this. Create a new Flash document.htmlText = "<p>Here's a picture from my garden:<img src='http://www. you can use the <img> tag to embed image files (JPEG. and save it as embedding. image2_txt. The SWF file that contains this code might be on your hard disk or on a server. and adds some text and a local image to the text field. You can also insert an image by using an absolute address. To specify the dimensions of the media you are embedding. specify the absolute or relative path to the image (GIF. 50. and movie clips in text fields In Flash Player 7 and later. Embedding SWF and image files To embed an image or SWF file in a text field.jpg'>". 450. 20. 150).) In general. or PNG) or SWF file in the <img> tag’s src attribute. image2_txt. 50. Add the following ActionScript to Frame 1 of the main Timeline: this.helpexamples.

the following code inserts a movie clip symbol with the linkage identifier symbol_ID into a dynamic text field with the instance name textField_txt. 0. Copy a GIF image to the same directory as the FLA and rename the image to beach. Set the behavior to Movie Clip and enter a descriptive symbol name. Convert the shape or image imported in the previous step by selecting it on the Stage and pressing F8 to open the Convert to Symbol dialog box.createTextField("textField_txt".gif and select Control > Test Movie to retest the Flash document.html = true.0). 4. 8. 6. you must make sure that your URL is prefixed with http://.4. Select the Export of ActionScript and Export in First Frame check boxes. 5. Draw a new shape on the Stage. The upper text field should have a sentence of text and most likely an error message in the Output panel saying that Flash was unable to locate a file named beach.gif in the current directory. When using absolute URLs. For an embedded movie clip to be displayed properly and completely.fla. Add the following ActionScript to Frame 1 of the main Timeline: this. Enter the linkage identifier img_id in the Identifier text box and then click OK. 7. Save the document and select Control > Test Movie to test the document. 10. Create a new Flash document and save it as embeddedmc. NO T E Embedding movie clip symbols To embed a movie clip symbol in a text field. textField_txt.htmlText = "<p>Here's a movie clip symbol:<img src='img_id'>". The lower text field should have a sentence of text and an image of a flower that was loaded from the remote server. 0. see “Attaching a movie clip symbol to the Stage” on page 362.) For example. 300. 3. you specify the symbol’s linkage identifier for the <img> tag’s src attribute. 200). 2. and click Advanced to switch to advanced mode if you haven’t already done so. Select the upper-left square of the registration point grid. To embed a movie clip into a text field: 1. or select File > Import > Import to Stage and select an image that is roughly 100 pixels wide by 100 pixels high. 446 Working with Text and Strings . the registration point for its symbol should be at point (0. textField_txt. Save your changes to the Flash document. (For information on defining a linkage identifier.

For example. 3. If you don’t specify values for height and width. or movie clip. space is reserved in the text field for the image file. Using HTML-formatted text 447 . Create a new Flash document. The <img> tag’s id attribute lets you assign an instance name to the movie clip that is created. 5.9. and then move it to the center of the Stage. Resize the circle to 80 pixels by 80 pixels by using the Property inspector. 4. If you are dynamically loading your images into a text field containing text. SWF file. Flash inserts it into the text field at full size and rebreaks text around it. After an image or SWF file has downloaded completely. it is good practice to specify the width and height of the original image so the text properly wraps around the space you reserve for your image. Use the Rectangle tool to draw a red square on the Stage. 7. it appears in the reserved space. The movie clip that Flash creates is added as a child movie clip to the text field that contains the image. This lets you control that movie clip with ActionScript. Flash scales the media up or down. no space is reserved for the embedded media. You must enter values for both the height and width attributes to scale the image. Select Frame 20 on the Timeline and then press F7 (Windows or Macintosh) to insert a new blank keyframe. NO T E Controlling embedded media with ActionScript Flash creates a new movie clip for each <img> tag and embeds that movie clip within the TextField object. Resize the document’s Stage size to 100 pixels by 100 pixels. Select Control > Test Movie to test the Flash document. Use the Oval tool to draw a blue circle on the Stage on Frame 20. Resize the square to 80 pixels by 80 pixels by using the Property inspector. the following example embeds a SWF file in a text field. 2. and then move the shape to the center of the Stage. To embed a SWF file in a text field: 1. 6. After an image or SWF file is downloaded completely. About specifying height and width values If you specify width and height attributes for an <img> tag. according to the values you specify for height and width.

Create a button instance on the Stage and give it the instance name stop_btn in the Property inspector. Save your changes to the Flash document and then select Control > Test Movie to preview the animation within the text field. To control the SWF file as it plays in a text field. Control > Test Movie to preview the animation. 2. you need the SWF file to generate so that you can load it into a separate FLA file.animation_mc. 200). and set the tween type to Shape in the Property inspector. 0. see “About making hypertext links out of embedded media” on page 449. the following ActionScript code to Frame 1 of the main Timeline: 12. complete the next exercise.fla file you created previously. Add the following ActionScript code beneath the existing code in Frame 1 of the main Timeline: stop_btn. the timeline of the animation nested within the text field stops. The SWF file is created in the same directory as the FLA. Add this. Follow the steps in the first procedure under “Controlling embedded media with ActionScript” on page 447. textField_txt. Now. Select 11.8. Select Control > Test Movie to test the application. Save the file in the same folder as the animation. Create a new FLA file and save it as animationholder.fla.htmlText = "Here's an interesting animation: <img src='animation. To control a SWF file that plays in a text field: 1. In this case. For information on making your embedded media into a hyperlink.animation_mc. 13. 448 Working with Text and Strings .onRelease = function() { textField_txt. }. 10. the fully qualified path to the newly created movie clip is textField_txt. textField_txt. whenever you click the stop_btn button instance.createTextField("textField_txt". Click a blank frame between Frame 1 and 20. For this exercise to work correctly.swf' id='animation_mc'>". Save the current document as animation. 300. 10. 0. 9. 4.html = true. 3.fla.stop().

You can use the scroll and maxscroll properties of the TextField object to control vertical scrolling and the hscroll and maxhscroll properties to control horizontal scrolling in a text field. does not register in SWF files and movie clips that are enclosed by <a> tags. and select Text > Scrollable. you can read and write these properties. the mouse pointer turns into a “pointing hand” icon. The scroll and hscroll properties specify the current vertical and horizontal scrolling positions. see “About making hypertext links out of embedded media” on page 449. and select Text > Scrollable.jpg'></a>". Select the dynamic text field with the Selection tool. The TextArea component provides an easy way to create scrolling text fields with a minimum amount of scripting. respectively.htmlText = "Click the image to return home<a href='home. you can only read these properties. Example: Creating scrolling text 449 . Select the dynamic text field with the Selection tool. SWF file. SWF file. For more information. Interactivity. Example: Creating scrolling text You can use several methods to create scrolling text in Flash. You can make dynamic and input text fields scrollable by selecting the Scrollable option from the Text menu or the context menu. or by pressing Shift and double-clicking the text field handle. or movie clip. Right-click (Windows) or Controlclick (Macintosh) the dynamic text field. To create a scrollable dynamic text field: Do one of the following: ■ ■ ■ Shift-double-click the handle on the dynamic text field. or movie clip that is enclosed by <a> tags.htm'><img src='home. The maxscroll and maxhscroll properties specify the maximum vertical and horizontal scrolling positions. the same as it does with standard hypertext links. For information on embedding media. such as mouse clicks and keypresses.About making hypertext links out of embedded media To make a hypertext link out of an embedded image file. When the mouse pointer is over an image. see “TextArea component” in the Components Language Reference. respectively. enclose the <img> tag in an <a> tag: textField_txt.

Do one of the following: ■ Use the Text tool to drag a text field on the Stage. You use strings often in your Flash documents and class files to display text in applications. Assign the text field the instance name textField_txt in the Property inspector.scroll -= 1. or select Window > Common Libraries > Buttons.To use the scroll property to create scrolling text: 1. }. and. }. You can put strings directly in your ActionScript code by placing quotation marks around the characters of data. Also. Any text that loads into the textField_txt text field can be scrolled using the up and down buttons. About strings and the String class In programming. and drag buttons to the Stage. 450 Working with Text and Strings . 6. Select the Down button on the Stage and type down_btn into the Instance Name text box.createTextField() method. Assign the text field the instance name textField_txt as a parameter of the method. Use ActionScript to create a text field dynamically with the MovieClip. enter the following code to scroll the text up: up_btn. For more information on creating strings. Select Frame 1 on the Timeline. Select the Up button on the Stage and type up_btn into the Instance Name text box. Following the ActionScript in step 5. 4. in the Actions panel (Window > Actions).onPress = function() { textField_txt. you can store values as strings that you can use in an application for a variety of purposes. such as within text fields. 3. You will use these buttons to scroll the text up and down. see “Using the TextField class” on page 384. NO T E ■ 2. If you are not dynamically loading text into the SWF file.onPress = function() { textField_txt. Create an Up button and a Down button. For information on using text fields. a string is an ordered series of characters. select Text > Scrollable from the main menu. enter the following code to scroll the text down in the text field: down_btn. 5. see “Creating strings” on page 458.scroll += 1.

Then. Unicode is the standard for character sets that can represent any language set. The encoding method deciphers it in a computer program. or software used. you might watch for the terminating character to know the end of a string (such as in a chat program). if you’re working with socket connections. The numbers in UTF encoding represent the number of bits in a unit. Like ASCII. UTF is an 8-bit system. About strings and the String class 451 . and the way you encode characters. the number of characters that Unicode supports has expanded to add support for more (and larger) languages. ■ Strings can be of various lengths in your applications. Strings could be displayed on any computer system.org/charts. Also. ASCII is a character set consisting of 95 printable characters and numerous control characters. or platform. the character “A” is represented by the Unicode character code 0041. Character encoding refers to the code. such as numeric values. ■ UTF-8 is the standard encoding for exchanging text. Over the years. UTF-16. which include UTF-8.You can associate each character with a specified character code. it is up to the program involved (such as Flash or a web browser) to display the character glyph (its visual appearance). the Unicode Standard is a valuable standard to encode languages. or method. and UTF-32. The character encodings are called Unicode Transformation Format (UTF) and Universal Character Set (UCS). which you can also optionally use to display text. The character code designates what character it represents. ASCII encodes each letter. you might encounter a terminating character at the end of a string.unicode. each letter in the English language would have a representative numerical code in a character encoding. the way you represent strings in a Flash document depends a lot on the character set you choose. although this might vary. You can determine the length of your string. For example. depending on what language you’re using. For example. UTF-16 is commonly used for internal processing. For example. Unicode is another way to associate a code with each letter of the alphabet. where A equals 65). Because ASCII cannot support large character sets. see www. The character code (as mentioned in the previous paragraph) is the table of mapped values (such as the ASCII table. number. but you can use it to determine when a string ends. For more information on character codes and code charts. or 65 in ASCII (American Standard Code for Information Interchange). It is a standard that exists to help development in multiple languages. such as online mail systems. and some symbols to 7-bit binary versions of each integer. ASCII is used by computers to represent text. such as Chinese. and the standard attempts to provide a universal way to encode characters that are part of any language. and this null character doesn’t have a value. and the numbers in a UCS encoding represent bytes. This terminating character is not an actual character. for representing a set of characters in a language to representative codes. As you can see.

On the Macintosh. and have Flash automatically determine the content that should appear in a certain language based on the language of the computer that is running Flash Player. strings. For more information. see the following topics: ■ ■ ■ ■ ■ ■ ■ ■ ■ About the Strings panel The Strings panel lets you create and update multilingual content. This file shows you how to build a simple word processor that compares and retrieves string and substring selections. “About the Strings panel” on page 452 “Using the Locale class” on page 453 “Using an input method editor” on page 455 “About the String class” on page 457 “Creating strings” on page 458 “About the escape character” on page 460 “Analyzing and comparing characters in strings” on page 460 “Converting and concatenating strings” on page 464 “Returning substrings” on page 467 ■ For more information on Strings and the String Class.fla. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Strings. see the following topics in Using Flash: ■ ■ ■ ■ “Authoring multilanguage text with the Strings panel” on page 370 “About editing strings in the Strings panel” on page 374 “Translating text in the Strings panel or an XML file” on page 379 “Importing an XML file into the Strings panel” on page 380 You can use the Locale class to control how multilanguage text is displayed. You can specify content for text fields that span multiple languages.lang. see “Using the Locale class” on page 453 and Locale (mx. in the Samples folder on your hard disk. 452 Working with Text and Strings .0 Language Reference.You can find a sample source file. For general information on the Strings panel. and how to use it in your applications. ■ In Windows. browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Strings.Locale) in the ActionScript 2.

Select the Via ActionScript at Runtime option. Using ActionScript at runtime Create a new Flash document and save it as locale. With the Strings panel. and cannot be changed by Flash Player. en (English) and fr (French). For a demonstration of how to use the Locale class. 7.lang. Automatically at runtime Flash Player replaces string IDs with strings from the XML file. 4. In the String panel’s grid. With the text field selected on the Stage. You can control string ID replacement by using ActionScript. 2. 5.Using the Locale class The Locale class (mx. 6.fla.Locale) allows you to control how multilanguage text is displayed in a Flash application at runtime. which matches the default system language code that is returned by language (capabilities. type the string hello in the en column. which is controlled at runtime. and click OK. set the default runtime language to French. Open the Strings panel (Window > Other Panels > Strings) and click Settings. see the following procedure. you can use string IDs instead of string literals in dynamic text fields. type a string identifier of greeting in the ID text box of the Strings panel and click Apply. You’ll notice that Flash converts the greeting string into IDS_GREETING. Select two languages. This option gives you control over both the timing and the language of string ID replacement. Manually using stage language String IDs are replaced by strings when the SWF file compiles. About strings and the String class 453 . 8. Create a dynamic text field on the Stage using the Text tool and give the text field the instance name greeting_txt. You can use the following methods to display the language-specific strings contained in the XML Localization Interchange File Format (XLIFF) files. 3. and click Add to add the languages to the Active languages pane. You can use the properties and methods of the Locale class when you want to replace the string IDs by using ActionScript to control the application when it plays in Flash Player. Drag a ComboBox component from the User Interface folder of the Components panel (Window > Components) onto the Stage and give it the instance name lang_cb. To use the Locale class to create multilanguage sites: 1.language property). which allows you to create a SWF file that displays text loaded from a language-specific XML file.

localeListener().9. TI P C A U T IO N 454 Working with Text and Strings . Whenever the lang_cb value changes. } } The preceding ActionScript is split into two sections.sort(). You use these strings when you use the lang_cb combo box to change the language on the Stage.addEventListener("change". Locale. } function localeListener(success:Boolean):Void { if (success) { greeting_txt.0 Language Reference.target.loadString("IDS_GREETING"). and localeListener(). the lang_cb combo box is populated with a sorted array of available languages. since it is not part of the Flash Player. The XML file that you use must use the XML Localization Interchange File Format (XLIFF).languageCodeArray. The first section of code imports the Locale class and specifies a callback listener that is called whenever a language XML file is finished loading. is called whenever the lang_cb combo box’s value is changed by the user. The second section of code defines two functions. } else { greeting_txt.loadLanguageXML(lang_cb. function langListener(eventObj:Object):Void { Locale. and if so.text = Locale. is called whenever a language XML file is finished loading. The second function. because the class must be compiled into the SWF file.autoSize = "left".setLoadCallback(localeListener). The first function. sets the text property of the greeting_txt instance to the greeting for the selected language. langListener(). Select Control > Test Movie to test the Flash document.Locale. Type the string bonjour in the fr column. greeting_txt.value). langListener(). Using the Locale class increases the SWF file size slightly. The function checks if the load was successful. Locale. 10.loadLanguageXML(eventObj. which loads the specified-language XML file. Because this class installed in the Flash Authoring classpath. Next. The Locale class is different from the other classes in the ActionScript 2.value). it is automatically compiled into your SWF files. langListener).lang.dataProvider = Locale.". Add the following ActionScript to Frame 1 of the main Timeline: import mx. Flash’s event dispatcher triggers the langListener() function. lang_cb. lang_cb.text = "unable to load language XML file. 11.

capabilities.setConversionMode() method. 2. English to Japanese or Korean to Chinese) N OT E You can also disable or enable the IME by using your application at runtime. you cannot tell which IME is active (if any). If an IME is installed. The next example shows how to determine whether the user has an IME installed and active.IME.IME. Add the following ActionScript to Frame 1 of the main Timeline: if (System. Which conversion mode the current IME is using."). The IME class in ActionScript lets you directly manipulate the operating system’s IME in the Flash Player application that is running on a client computer.fla. } } else { trace("Please install an IME and try again. Using ActionScript.hasIME property. Flash checks whether it is currently enabled. } else { trace("You have an IME installed but not enabled. you can determine if the conversion mode is Hiragana. You can check whether a system has an IME by using the System. The IME class can determine which conversion mode the current IME is using: for example.Locale) in the ActionScript 2. see Locale (mx. and Korean.getEnabled()) { trace("You have an IME installed and enabled. and perform other functions. Create a new Flash document and save it as ime."). About strings and the String class 455 . You can set it with the System. Katakana (and so on) using the System. or change from one IME to another (for instance.getConversionMode() method.IME. Curently. Using an input method editor An input method editor (IME) lets users type non-ASCII text characters in Asian languages such as Chinese. To determine whether the user has an IME installed and active: 1.hasIME) { if (System. you can determine the following: ■ ■ ■ Whether an IME is installed on the user’s computer. Japanese.0 Language Reference. Whether the IME is enabled or disabled on the user’s computer. depending on the user’s operating system. if the Japanese IME is active.For more information.capabilities.").lang. } The preceding code first checks whether the current system has an IME installed.

getEnabled()) { trace("You have an IME installed and enabled. see the following links: ■ ■ ■ www. 100. Create a new Flash document and save it as ime2.IME.multiline = true. 240).apple.3.font = "_sans". ime_txt. my_fmt.setNewTextFormat(my_fmt). disable_btn. ime_txt. Select Control > Test Movie to test the document. return true.createTextField("ime_txt". For more information on installing an IME on your specific platform.onRelease = function() { System.setEnabled(false). Create two button symbol instances on the Stage and give them the instance names enable_btn and disable_btn.setEnabled(true). enable_btn.com You can enable and disable an IME while the SWF file plays.IME.fla.hasIME) { if (System.onRelease = function() { System. this. }. To enable and disable an input method editor at runtime: 1. The following example requires that you have an IME installed on your system. ime_txt. 10. var my_fmt:TextFormat = new TextFormat(). 3.com/globaldev/default. Add the following ActionScript to Frame 1 of the main Timeline: checkIME(). } else { trace("You have an IME installed but not enabled.type = "input".IME. 10.microsoft. 456 Working with Text and Strings . A message appears in the Output panel stating whether you have an IME installed and currently active. function checkIME():Boolean { if (System.wordWrap = true.com/documentation/ http://java. 2. }.").capabilities.").sun. You can also use the IME class to enable and disable the IME in Flash at runtime. ime_txt.border = true. ime_txt. as shown in the following example. 320.mspx http://developer.

The first section calls the checkIME() method. see hasIME (capabilities. and final. ContextMenu. This example requires that you have an IME installed on your system. N OT E Type some text into the input text field on the Stage. and FileReference instances.” The String class contains methods that let you work with text strings.hasIME. and values. “Data and Data Types. using the UTF-16 format. The fourth section creates some event handlers for the enable_btn and disable_btn instances created in an earlier step. The String data type represents a sequence of 16-bit characters that might include letters. The default value for a variable declared with the String data type is null. and the methods described in this chapter are useful in working with strings used in many objects. section of code defines the custom checkIME() function. Save the FLA file and select Control > Test Movie to test the document. 4. Strings are important in working with many objects.return false. Switch your IME to a different language and type in the input text field again. The fifth. } } else { trace("Please install an IME and try again. property) For information on System. The second section defines a custom text-format object. Strings are stored as Unicode characters. which sets the font to _sans. If you click the disable_btn button on the Stage."). such as TextField.0 Language Reference. see the links that precede this example.capabilities. For more information on strings. see Chapter 4. XML. which checks whether the current system has an IME installed and if so. whether or not the IME is active. which displays a message in the Output panel if the system has an IME installed or active.hasIME in the ActionScript 2. An operation on a String value returns a new instance of the string. The third section creates an input text field and applies the custom text format. Flash reverts to using the previous language and ignores the current IME settings. numbers. return false. Flash Player inputs characters by using the new IME. } } The preceding code is separated into five sections. For information on installing an IME. About strings and the String class 457 . and punctuation marks. data. About the String class A string is also a class and data type in the core ActionScript language.

are generic. the line of code creates the firstStr string literal. see Chapter 5. To declare a string literal. Do not confuse a string literal with a String object. ■ Creating strings You can call any of the methods of the String class by using the new String() constructor method or by using a string literal value. Because all string indexes are zero-based. and discards the temporary String object. the index of the last character for any myStr string is myStr.length property with a string literal. fromCharCode(). In the following example. ■ In Windows.The String class is a wrapper for the String primitive data type. You can also use the String. except for concat(). the ActionScript interpreter automatically converts it to a temporary String object.” on page 130. and you can use these methods with other non-String objects. “About literals. All the methods of the String class. in the Samples folder on your hard disk. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Strings. and provides methods and properties that let you manipulate primitive string values. On the Macintosh. calls the method. which means the methods call the toString() function before they perform their operations. For more information on string literals and the String object. use single straight quotation mark (') or double straight quotation mark (") delimiters. This file shows you how to build a simple word processor that compares and retrieves string and substring selections. browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Strings. slice(). You can convert the value of any object into a string by using the String() function. and substr(). 458 Working with Text and Strings .fla.length .1. You can find a sample source file. If you specify a string literal. strings.

2. and the other without an initial value.To create and use strings: 1. Strings can be compared by using the equality (==) operator. strings. 3. Create a new Flash document and save it as strings. be sure to use straight quote delimiters. Add the following ActionScript to Frame 1 of the main Timeline: var firstStr:String = "foo". ■ In Windows. see Chapter 5. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Strings. in the Samples folder on your hard disk. “About literals. To use single straight quotation mark (') and double straight quotation mark (") delimiters within a single string literal. var secondStr:String = 'That\'s "fine"'. trace(firstStr == secondStr). use the backslash character (\) to escape the character. they are different from the straight quotation marks (') and (") that you can use in your code. Remember that you cannot use “curly quotation mark” or “special quotation mark” characters within your ActionScript code. one that uses the new operator. // true var thirdStr:String. ■ About strings and the String class 459 . For more information on string literals and the String object. see “About the escape character” on page 460. as shown in the third line of code. trace(thirdStr).fla. When you paste text from another source into ActionScript. Select Control > Test Movie to test the document. // undefined This code defines three String objects. browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Strings. You can find a sample source file.” on page 130. This file shows you how to build a simple word processor that compares and retrieves string and substring selections. you specify the data type only when the variable is being defined. For more information on using the backslash character in strings. The following two strings are equivalent: var firstStr:String = "That's \"fine\"". one that uses a string literal. var secondStr:String = new String("foo"). On the Macintosh.fla. Always use string literals unless you specifically need to use a String object. When referring to variables. such as the web or a Word document.

The Unicode character with the character code specified by the hexidecimal number nnnn. “About literals. trace(firstStr. to define other characters in string literals. The form feed character. The index position of the first character is 0. A single backslash character. in the string yellow.” on page 130 and “Creating strings” on page 458. For example. The carriage return. The newline character. Every string has a length property. see Chapter 5. \xnn \' \" \\ For more information on string literals. // 0 var secondStr:String = "". // 0 460 Working with Text and Strings . trace(companyStr. \u263a is the smile character. which is equal to the number of characters in the string: var companyStr:String = "macromedia". A single quotation mark. For example.length).length).About the escape character You can use the backslash escape character (\). Analyzing and comparing characters in strings Every character in a string has an index position in the string (an integer). // 10 An empty string and a null string both have a length of zero: var firstStr:String = new String(). The tab character. Escape sequence \b \f \n \r \t \unnnn Description The backspace character. The ASCII character with the character code specified by the hexidecimal number nn. trace(secondStr. the character y is in position 0 and the character w is in position 5. A double quotation mark.length).

The following example creates a variable named myStr and sets the string’s value based on ASCII values passed to the String. Create a new Flash document.toString(10)).114. For example. although the unicode value must be converted from hexidecimal to decimal values.101.108.fromCharCode() method: var myStr:String = String.fromCharCode() method to convert Unicode values.111. for (var i:Number = 0. To loop over a string: 1. trace(String. For more information on character codes and character encoding. i < myStr. W A R NI N G You can also use character codes to define a string. its length is set to undefined: var thirdStr:String. see “About strings and the String class” on page 450. About strings and the String class 461 . 2. trace(myStr).119. as shown in the following ActionScript: // Unicode 0068 == "h" var letter:Number = Number(new Number(0x0068).length). trace(thirdStr. You should see each character traced to the Output panel on a separate line.32. // undefined If your string contains a null byte character (\0).100.33). the ASCII value 104 represents a lowercase h. You can also use the String.If a string doesn’t contain a value. and the ASCII value 32 represents the space character. // hello world! Each number listed in the fromCharCode() method in the previous code represents a single character. the string value will be truncated.length. as in the following example.fromCharCode(letter)).108. } 3. Select Control > Test Movie to preview your Flash document.charAt(i)). Add the following ActionScript to Frame 1 of the main Timeline: var myStr:String = "hello world!". i++) { trace(myStr.111.fromCharCode(104. // h You can examine the characters in various positions in a string.108.

charAt(i) + " . When you run this code. Create a new Flash document and save it as comparestr. Save the current Flash document and select Control > Test Movie to preview the SWF file. for example."). You can use operators to compare strings. } TIP 3. For information on using operators with strings. var str2:String = "apple". To compare two strings: 1. The following example uses operators and strings to make a comparison.4. var charArray:Array = myStr. 2.charCodeAt(i)). 462 Working with Text and Strings . such as if and while.length. as shown in the following example. see “About using operators with strings” on page 182.split() method and entering an empty string ("") as a delimiter. for (var i:Number = 0. if (str1 < str2) { trace("Uppercase letters sort first.split("").fla.ASCII=" + myStr. Add the following ActionScript to Frame 1 of the main Timeline: var str1:String = "Apple". i++) { trace(myStr. the following is displayed in the Output panel: h e l l o w o r l d ! ASCII=104 ASCII=101 ASCII=108 ASCII=108 ASCII=111 ASCII=32 ASCII=119 ASCII=111 ASCII=114 ASCII=108 ASCII=100 ASCII=33 You can also split a string into an array of characters by using the String. You can use these operators with conditional statements. i < myStr. Modify the existing ActionScript code so that it traces the ASCII value for each character: var myStr:String = "hello world!". } 5. You can use the equality (==) and inequality (!=) operators to compare strings with other types of objects. Save the Flash document and select Control > Test Movie to test the SWF file.

The following example uses strict comparison operators to ensure that Flash doesn’t try to convert data types while trying to compare values. Save the Flash document and select Control > Test Movie. 2. var total:Number = 4. browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Strings.fla. } 3. Use the strict equality (===) and strict inequality (!==) operators to verify that both comparison objects are of the same type.fla. if (myStr == total) { trace("Types are converted. Add the following ActionScript to Frame 1 of the main Timeline: var str1:String = "4". if (str1 !== total) { trace("Types are not converted. Add the following ActionScript to Frame 1 of the main Timeline: var myStr:String = "4". } 3.To compare strings to other data types: 1. This file shows you how to build a simple word processor that compares and retrieves string and substring selections. You can find a sample source file. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Strings. To force strict data type comparisons: 1. 2. On the Macintosh. ■ About strings and the String class 463 . When comparing two different data types (such as strings and numbers).fla."). strings. but the strings don't match. var total:Number = 4. ■ In Windows. Save the Flash document and select Control > Test Movie to test the SWF file.")."). Flash tries to convert the data types so that a comparison can be made. For more information on using operators with strings. Create a new Flash document and save it as comparenum. } if (str1 !== str2) { trace("Same type. Create a new Flash document and save it as comparestrict. in the Samples folder on your hard disk. see “About using operators with strings” on page 182. var str2:String = "5".

bob roberts. trace(myStr. trace(typeof(n. Create a new Flash document and save it as convert. #9. 2.". To transform the source string. you can use the addition (+) operator to concatenate two strings. 3. see the second procedure in this section. trace(str3).toUpperCase(). Add the following code to Frame 1 of the Timeline: var str1:String var str2:String trace(str2). use the following: N OT E myStr = myStr. you take two strings and join them sequentially into one string. The next example shows you how to concatenate two strings. Most built-in objects have a toString() method for this purpose: var n:Number = 0.Converting and concatenating strings You can use the toString() method to convert many objects to strings. After these methods are executed. For details on concatenation. Create a new Flash document and save it as concat. trace(myStr). Bob Roberts. the source string remains unchanged. // // var str3:String str3 += "ish". you don’t need to use the toString() method. To concatenate two strings: 1. // = "green". #9.470.fla.toUpperCase()). // DR. When you concatenate strings. trace(myStr. Save the Flash document and select Control > Test Movie. = str1 + "ish". // dr.toString())). Bob Roberts. #9. The following example demonstrates how to convert a string from lowercase to uppercase characters.toLowerCase()). For example. yellowish 464 Working with Text and Strings . greenish = "yellow". Type the following code on Frame 1 of the Timeline: var myStr:String = "Dr. // string When you use the addition (+) operator with a combination of string and nonstring instances. To convert a string from lowercase to uppercase: 1. #9. 2. // Dr.fla. The toLowerCase() method and the toUpperCase() method convert alphabetical characters in the string to lowercase and uppercase. BOB ROBERTS. respectively.

trace(version). = "Paris".46 trace("Total: $" + (4. " ". The second method uses the addition and assignment (+=) operator to concatenate the string "ish" with the current value of str3. For example. Add the following code to Frame 1 of the Timeline: var str1:String var str2:String var str3:String var str4:String trace(str4).01 You can use the split() method to create an array of substrings of a string. which is divided based on a delimiter character.The preceding code shows two methods of concatenating strings. Bonjour from Paris 3.or tab-delimited string into multiple strings. You can also use the concat() method of the String class to concatenate strings. This conversion is demonstrated in the following code example: var version:String = "Flash Player ". // = "Bonjour". var rel:Number = 8. 3. To concatenate two strings with the concat() method: 1. Select Control > Test Movie to test the Flash document. = "from". version = version + rel. str2.fla. This method is demonstrated in the following example.46)). Save the Flash document and select Control > Test Movie. The first method uses the addition (+) operator to join the str1 string with the string "ish". as demonstrated in the following ActionScript code: trace("Total: $" + 4.551. // Total: $6. the following code shows how you can split an array into substrings by using the ampersand (&) character as a delimiter. About strings and the String class 465 . // Flash Player 8 However.46). Create a new Flash document and save it as concat2.concat(" ". str3).55 + 1. = str1. If you use the addition (+) operator (or the addition and assignment [+=] operator) with a string and a nonstring object. For example. you can use parentheses to force the addition (+) operator to evaluate arithmetically. you could segment a comma. // Total: $4. ActionScript automatically converts nonstring objects to strings in order to evaluate the expression. 2.55 + 1.

This file shows you how to build a simple word processor that compares and retrieves string and substring selections. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Strings. trace(my_lv. see “About using operators with strings” on page 182. browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Strings. The second parameter of the split() method defines the maximum size of the array. you can omit the second parameter. // joe For more information on using operators with strings. Create a new Flash document and save it as strsplit. 2). trace(params).fla. my_lv.split("&". var my_lv:LoadVars = new LoadVars(). 2. You can find a sample source file.fla. Select Control > Test Movie to test the Flash document.To create an array of substrings segmented by delimiter: 1. ■ In Windows. // first=joe. If you don’t want to limit the size of the array created by the split() method. On the Macintosh. as shown in the following ActionScript: TIP TIP var queryStr:String = "first=joe&last=cheng&title=manager&startDate=3/6/ 65". strings.decode() method. in the Samples folder on your hard disk. The easiest way to parse a query string (a string delimited with & and = characters) is to use the LoadVars.last=cheng /* params is set to an array with two elements: params[0] == "first=joe" params[1] == "last=cheng" */ 3. var params:Array = queryStr.decode(queryStr). Add the following ActionScript to Frame 1 of the main Timeline: var queryStr:String = "first=joe&last=cheng&title=manager&startDate=3/6/ 65".first). ■ 466 Working with Text and Strings .

trace(myStr. Create a new Flash document and save it as substring. Add the following ActionScript below the code added in the preceding step: trace(myStr. the slice() method can take negative integers as parameters. returns a string four characters long by grabbing all characters between the eleventh and fifteenth index. // Pari The first method. However. Select Control > Test Movie to test the Flash document.15)). 15)). This example shows the difference between these two methods: To find a substring by character position: 1. When given two non-negative integers as parameters. in the substr() method. You can combine non-negative and negative integers as the parameters of the slice() method. trace(myStr. it works exactly the same. // Pari -1)). In both methods. About strings and the String class 467 . // Paris. N O TE You can use the indexOf() and lastIndexOf() methods to locate matching substrings within a string. 4. substring().slice(-3. the second parameter is the length of the substring to return.slice(11.15)). returns a string 15 characters long starting from the eleventh character. Add the following ActionScript to Frame 1 of the main Timeline: var myStr:String = "Hello from Paris. substr().slice(-8. trace(myStr. trace(myStr. as shown in the following example. Both return a substring of a string and both take two parameters. and in the substring() method the second parameter is the position of the character at the end of the substring (which is not included in the returned string).length)). // !!! -3)). the first parameter is the position of the starting character in the given string. 3. Texas!!!".slice(-3. trace(myStr.substring(11. // Texas The slice() method functions similarly to the substring() method. 2.Returning substrings The substr() and substring() methods of the String class are similar. // !! 26)). // !!! myStr.slice(-3.fla.substr(11. However. The second method. Texas!!! trace(myStr.

indexOf("the". if you include a second parameter with the lastIndexOf() method. On the Macintosh. You can also specify a second parameter to the indexOf() method to indicate the index position in the string from which to start the search. 11)). strings. // 21 The lastIndexOf() method finds the last occurrence of a substring in the string.lastIndexOf("the". the search is conducted from that index position. the sea. In the preceding code. the land". 4. Select Control > Test Movie to test your Flash document. Similarly to the indexOf() method. // 10 trace(myStr. For example. // 21 The first index of the word the begins at the 10th character because the indexOf() method is case sensitive.fla.To find the character position of a matching substring: 1.indexOf("the")). lastIndexOf() starts from the end of a string and works backward. instead searching for a character or substring from the beginning of a string. 29)). although with lastIndexOf() the string is searched backward (from right to left). 2. 3. Create a new Flash document and save it as indexof. Add the following ActionScript below the code that you added in the previous step: trace(myStr. trace(myStr.lastIndexOf("the")). in the Samples folder on your hard disk. The indexOf() and lastIndexOf() methods are case sensitive. Add the following ActionScript to Frame 1 of the main Timeline: var myStr:String = "The moon. the stars. browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Strings. This file shows you how to build a simple word processor that compares and retrieves string and substring selections. ■ In Windows. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Strings. therefore the first instance of The isn’t considered. Flash searches for the first index of the word the that occurs after the 11th character. TIP You can find a sample source file. // 30 trace(myStr. ■ 468 Working with Text and Strings .fla.

. . the Tween and TransitionManager classes. . . . . . . . . . . . . and can also improve the performance and consistency of the animation itself. . This chapter contains the following sections. . . . . . . . . . . . . . 498 Working with filters using ActionScript . . .CHAPTER 13 Animation. . . . . . . . . . . . . . . and it’s easy to apply to many instances at once or reuse in other applications. which describe using ActionScript to create animation and add effects. . . . . . . . This chapter also shows you how to animate by using fundamental ActionScript basics. . . . . . . . . . You can use the Drawing API. . . . . . .0 . . . .470 About bitmap caching. . . . . . . . . 540 Understanding scaling and slice guides . 530 Creating bitmaps with the BitmapData class . and Drawings This chapter describes how to add animation to your Macromedia Flash Basic 8 and Macromedia Flash Professional 8 applications using ActionScript instead of (or in addition to) timeline-based animations that use motion or shape tweens. . . . . . . . . . . . . . . to add animation and draw. . . . . . . . . . . to quickly apply an effect and animate it. . . . . . . . . . and shapes. . . . . filter classes. . . . 480 About the Tween and TransitionManager classes . . . . . . . . . . . . . . . . You can use code to add and animate filter effects. . . . . . . . . . . . . . . . . and performance . . . . . . . . . . . . . . . . .534 About blending modes . . . . . 505 Manipulating filter effects with code . . . . . 540 Drawing with ActionScript . . . . 537 About operation order . . . . . . . . . . . .556 13 469 . . . . . . . . . . . . . Filters and other expressive effects are also important in many Flash applications. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 481 Using filter effects. . . . . . . . . . . . . ActionScript-based animations might even reduce your workload: code can be faster to write. . . . . . At times. . . . blend modes. . . the Drawing API. . . . . . . . . . . which consists of the drawing methods in the MovieClip class. . . . . . . . . These methods let you use code to create lines. . . . . . . . . . . Using code to create animation and effects often reduces the file size of your finished application. . . . . . . . . . . . . . Filters. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . and bitmap images. . . scrolling. . . . . fills. . . . . . . . . . . . . . . . . . as well as using the Drawing API to draw in ActionScript: Scripting animation with ActionScript 2. . . . . . . and blend modes. . . . . . . instead of using the drawing tools in the authoring tool. . . .

■ 470 Animation. ■ In Windows.fla.fla.fla and gallery_tween. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Animation. animation. These classes help you add advanced easing equations and transition animations to movie clip instances in your application. because the code you need to use involves writing complex mathematical equations to achieve the effect.Scripting animation with ActionScript 2. see “TransitionManager class” on page 1201 and “Tween class” on page 1273. and Drawings .0 You can use ActionScript 2.The following sections show you how to use code to animate instances. The following sections describe how to script animations: ■ ■ ■ ■ ■ “About animation and frame rate” on page 471 “Fading objects with code” on page 472 “Adding color and brightness effects with code” on page 474 “Moving objects with code” on page 477 “Panning an image with code” on page 478 For an example of scripted animation in Flash. see “Drawing with ActionScript” on page 540. which includes scripted animation.These files provide examples of how to use ActionScript to control movie clips dynamically while loading image files into a SWF file. you can find a sample source file. gallery_tree. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Galleries. For more information about how to animate drawings that you create with code. For information on using the Tween and TransitionManager classes to further automate codebased animations. You can find the sample source files. browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Animation. Many of these effects are difficult to recreate using ActionScript without these prebuilt classes. such as changing the transparency and appearance of the instance. On the Macintosh. instead of using motion or shape tweens on a timeline. in the Samples folder on your hard disk. Filters.0 to add animation to your Flash applications. On the Macintosh. browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Galleries. in the Samples folder on your hard disk. and moving the instance around the Stage. ■ In Windows. ■ You can find samples of photo gallery applications on your hard disk.

0 Language Reference). you call functions at a specified interval. If the document’s frame rate is set to 24 fps. check the duration. especially if you’re working with timeline-based animation. and the SWF file size. the animation runs at the document’s frame rate. of your animation. When you test the SWF file. high frame rates put a lot of stress on processors. Try not to use a frame rate that’s more than 30 to 40 fps. Like onEnterFrame. your animation at 24 fps also plays much faster than it does at 12 fps. Therefore. Also. An alternative to the onEnterFrame event handler is setInterval (see setInterval function in the ActionScript 2. select a frame rate for your animation as early as possible in the development process. so the total duration (in seconds) is shorter. it means you need to add additional frames to fill those five seconds than at a lower frame rate (and thus.0 471 . you also need to consider the frame rate setting. Setting a frame rate too high can lead to processor problems. similar to if you created a motion tween on a timeline. an animation set to 12 frames per second (fps) in the Property inspector plays 12 frames each second.About animation and frame rate When you add animation to an application. Scripting animation with ActionScript 2. this raises the total file size of your animation). For example. The frame rate greatly affects the speed of the animation. which helps reduce the strain on the end-user’s processor. the more resource intensive the animation is on your processor. N OT E Use the lowest possible frame rate that makes your animation appear to play smoothly at runtime. the more frequently you use setInterval to call a function. You need to think about frame rate when working with animations because it can affect the performance of your SWF file and the computer that plays it. the animation appears to animate more smoothly than if it ran at 12 fps. Instead of depending on frame rate. and do not change the appearance of the animation much or at all at runtime. A 5-second animation at 24 fps typically has a higher file size than a 5-second animation at 12 fps. if you need to make a 5-second animation using a higher frame rate. However. consider the frame rate that you set your FLA file to. However. because it affects how smoothly your animation plays. When you use an onEnterFrame event handler to create scripted animations. especially when you use many assets or use ActionScript to create animation.

Select Frame 1 of the Timeline. Draw some graphics on the Stage using the drawing tools. This code uses an onEnterFrame event handler. 3. delete img1_mc. Select the Movie clip option and click OK to create the symbol. To fade a movie clip by using code: 1. 7. if (img1_mc. the event handler is invoked 30 times per second. 4.Fading objects with code When you work with movie clips on the Stage. Filters. Select the content on the Stage and select Modify > Convert to Symbol. You can modify the _alpha property by using the setInterval() function instead of an onEnterFrame event handler.fla. if the Flash document’s frame rate is 30 fps. and Drawings . as the next procedure shows. The number of times per second that the event handler is called depends on the frame rate at which the Flash document is set. Create a new Flash document called fade1. you might want to fade the movie clip in or out instead of toggling its _visible property. } }._visible = false._alpha -= 5. the onEnterFrame event handler is invoked 12 times per second. 2. and add the following code to the Actions panel: img1_mc._alpha <= 0) { img1_mc. If the frame rate is 12 frames per second (fps). 6. The following procedure demonstrates how to use an onEnterFrame event handler to animate a movie clip. The movie clip you added to the Stage slowly fades out. Select the movie clip instance on the Stage and type img1_mc in the Instance Name text box in the Property inspector. Select Control > Test Movie to test the document. 472 Animation.onEnterFrame = function() { img1_mc. which is invoked repeatedly at the frame rate of the SWF file. or import an image to the Stage (File > Import > Import to Stage). 5. Likewise.onEnterFrame.

fla. or import an image to the Stage (File > Import > Import to Stage). In this code example. which causes the fadeImage() function to stop executing. 2. see setInterval function in the ActionScript 2. the user-defined fadeImage() function is called every 50 milliseconds (20 times per second). For more information on the setInterval() function._visible = false.fla. For more information on the onEnterFrame event handler. browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Animation. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Animation. } } The setInterval() function behaves slightly differently than the onEnterFrame event handler. 5. Draw some graphics on the Stage. 6. When the _alpha value is equal to or less than 0.To fade an object by using the setInterval() function: 1. ■ In Windows. see onEnterFrame (MovieClip. For more information on user-defined functions. img1_mc). Select the Movie clip option and click OK to create the symbol. 50. The movie clip you added to the Stage slowly fades out. if (target_mc.0 473 . Create a new Flash document called fade2. On the Macintosh. see “Defining global and timeline functions” on page 212. The fadeImage() function decrements the value of the current movie clip’s _alpha property. clearInterval(alpha_interval). Select Control > Test Movie to test the document. in the Samples folder on your hard disk. Select Frame 1 of the Timeline and add the following code to the Actions panel: var alpha_interval:Number = setInterval(fadeImage. 3.0 Language Reference. Select the content on the Stage and select Modify > Convert to Symbol. Select the movie clip instance on the Stage and type img1_mc in the Instance Name text box in the Property inspector. For an example of scripted animation in Flash.0 Language Reference. 4. the interval is cleared. you can find a sample source file. animation. because the setInterval() function tells Flash precisely how frequently the code should call a particular function.onEnterFrame handler) in the ActionScript 2. ■ Scripting animation with ActionScript 2._alpha <= 0) { target_mc. 7. function fadeImage(target_mc:MovieClip):Void { target_mc._alpha -= 5.

helpexamples.fla. you can animate various color and brightness effects by using code instead of using the Filters panel in the Property inspector. The following procedure loads a JPEG image and applies a color transform filter.com/flash/images/ image1. var colorTransformer:ColorTransform = transformer. clipLoader.Transform. and then move the mouse pointer around the Stage.height) * 1. import flash.greenMultiplier = (_ymouse / Stage. 3.addListener(mouseListener).geom. colorTransformer. } Mouse.ColorTransform. imageClip).onMouseMove = function():Void { var transformer:Transform = new Transform(imageClip). Filters. To change an object’s color channels by using ActionScript: 1. Create a new Flash document called colorTrans.createEmptyMovieClip("imageClip". and Drawings .colorTransform = colorTransformer. var imageClip:MovieClip = this. You can also use the ColorMatrixFilter class to convert a color image to a black and white image. Select Frame 1 of the Timeline. mouseListener.colorTransform. and add the following code to the Actions panel: import flash. var clipLoader:MovieClipLoader = new MovieClipLoader().jpg". 2. var mouseListener:Object = new Object(). 1). Select Control > Test Movie to test the document. transformer. 474 Animation. colorTransformer. The image file that loads transforms colors as you move the mouse.Adding color and brightness effects with code In addition to using ActionScript to set and animate alpha fades (see “Fading objects with code” on page 472).redMultiplier = (_xmouse / Stage.geom. which modifies the red and green channels as the mouse pointer moves along the x-axis and y-axis.width) * 1. as the following procedure shows.loadClip("http://www.

com/flash/images/image1.0 475 . Finally.helpexamples.jpg) to see the original color of the image. Scripting animation with ActionScript 2.filters. mcl_obj.com").getNextHighestDepth()).security. 0.59. 0. The preceding code begins by importing the ColorMatrixFilter class. 2. var img_mcl:MovieClipLoader = new MovieClipLoader(). 0. var myColorMatrix_filter:ColorMatrixFilter = new ColorMatrixFilter(myElements_array).com/flash/images/image1.3. View the image online (http://www. 1.59.11.3. Select Control > Test Movie to test the document. 0. } this.loadClip("http://www. 0. 0.createEmptyMovieClip("img_mc". target_mc.onLoadInit = function(target_mc:MovieClip):Void { var myElements_array:Array = [0. 0. 0. The image that you load onto the Stage changes to a grayscale image. Select Frame 1 of the Timeline. System. img_mcl. and creates a listener object that will be used with a new MovieClipLoader instance created in some later code.helpexamples. img_mcl.ColorMatrixFilter.11. 0. Create a new Flash document called grayscale. a new movie clip instance is created with the instance name img_mc. 0. You can also set an image’s brightness by using the ActionScript code in the following procedure. When the image is successfully loaded. the source movie clip is loaded into the img_mc movie clip on the Stage.helpexamples. Next. var mcl_obj:Object = new Object().59. 0. 0. the onLoadInit event handler is called and attaches a ColorMatrixFilter to the loaded image. this.allowDomain("http://www. 0. as well as a new movie clip loader instance with the instance name img_mcl. 0.addListener(mcl_obj).jpg".To use the ColorMatrixFilter class to change an image to a grayscale image: 1.3. 0. 0.11.fla. 0]. img_mc). 0. 3.filters = [myColorMatrix_filter]. and add the following code to the Actions panel: import flash.

0. in the Samples folder on your hard disk. 0. For an example of scripted animation in Flash. this. When the image successfully loads.fla. and Drawings . Select Control > Test Movie to test the document. 0. in the Samples folder on your hard disk. 0. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Animation. 0. browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Animation.com/flash/images/ image2.loadClip("http://www. img_mc).fla. ■ In Windows. 0.helpexamples. 3.com/").helpexamples.To change an image’s brightness: 1.onLoadInit = function(target_mc:MovieClip):Void { var myElements_array:Array = [1. 100.jpg". 0. 0]. Create a new Flash document called brightness.allowDomain("http://www. 0. ■ You can also find samples of photo gallery applications on your hard disk. img_mcl. 1. View the image online (http://www.addListener(mcl_obj). which includes scripted animation. img_mcl. browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Galleries. 0. } this. 1. 1. you can find a sample source file. mcl_obj. target_mc.security. The image that you load into the SWF file changes its brightness when you test the SWF file.com/flash/images/image2. This block of code uses the MovieClipLoader class to load an external JPEG. These files provide examples of how to use ActionScript to control movie clips dynamically while loading image files into a SWF file. var img_mcl:MovieClipLoader = new MovieClipLoader(). 100. the MovieClipLoader class onLoadInit event handler is called and modifies the image brightness to 100 using the ColorMatrixFilter filter.helpexamples. 0.getNextHighestDepth()).jpg) to see the original appearance of the image. var myColorMatrix_filter:ColorMatrixFilter = new ColorMatrixFilter(myElements_array). ■ In Windows.ColorMatrixFilter. 476 Animation. gallery_tree. 0. Select Frame 1 of the Timeline and add the following code to the Actions panel: import flash. Filters. 2. animation.fla. 100.fla and gallery_tween.filters. 0.createEmptyMovieClip("img_mc". var mcl_obj:Object = new Object(). You can find the sample source files. System.filters = [myColorMatrix_filter]. On the Macintosh.

Change the frame rate of the document to 24 fps in the Property inspector.width. delete target_mc. this. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Galleries.createEmptyMovieClip("img1_mc". This code example loads an external image from a remote web server and.com/flash/images/image1. 4. Moving objects with code Using ActionScript to move an object is similar to modifying an object’s _alpha property.onEnterFrame. when the image is fully loaded. The image loads and then animates from the right side of the Stage to the upper-left corner of the Stage.0 477 .loadClip("http://www._x <= 0) { target_mc. // Load an image into the movie clip img_mcl. Scripting animation with ActionScript 2. 3.■ On the Macintosh. img1_mc). Instead of using an onEnterFrame event handler. img_mcl. animates it horizontally across the Stage.fla. such as 24 fps. mcl_obj.helpexamples. Select Control > Test Movie to test the document. } }. Select Frame 1 of the Timeline. The following procedure animates a dynamically loaded JPEG image and slides it horizontally across the Stage. Create a new Flash document called moveClip._x = Stage.jpg"._x = 0. var img_mcl:MovieClipLoader = new MovieClipLoader().addListener(mcl_obj). // decrease current _x position by 3 pixels if (target_mc.onLoadInit = function (target_mc:MovieClip):Void { target_mc. except that you instead modify the object’s _x or _y property. 2. 10). and add the following code to the Actions panel: // Create a movie clip instance.onEnterFrame = function() { target_mc. }. To move an instance on the Stage by using code: 1._x -= 3. you could use the setInterval() function to animate the image. The animation is much smoother if you use a higher frame rate. var mcl_obj:Object = new Object(). target_mc.

browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Animation. which includes scripted animation. gallery_tree. On the Macintosh. On the Macintosh. This is useful when your image doesn’t fit on the Stage. see “Fading objects with code” on page 472. For an example of scripted animation in Flash. browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Galleries. 478 Animation. but you don’t want to reduce the dimensions of your image or increase the dimensions of your Stage. or you want to create an animation effect in which you pan a movie clip from one side of the Stage to the other. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Galleries. ■ You can also find samples of photo gallery applications on your hard disk. you can create a movie clip that acts as a mask for the larger image.These files provide examples of how to use ActionScript to control movie clips dynamically while loading image files into a SWF file. Filters. you can easily pan large images within your Flash documents. ■ In Windows.fla. For example. in the Samples folder on your hard disk. in the Samples folder on your hard disk. browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Animation. animation.fla. You can find the sample source files. if you have a large panoramic image that is larger than your Stage size. ■ In Windows.fla and gallery_tween.For information on using an onEnterFrame event handler or setInterval() function to animate the image. and Drawings . you can find a sample source file. The following procedure demonstrates how you can dynamically mask a movie clip and use an onEnterFrame event handler to animate an image behind the mask. ■ Panning an image with code Using ActionScript.

var speed:Number = 5. }._x >= 0)) { direction *= -1.security._width-mask_mc. 2. my_mcl. 100). Select Frame 1 of the Timeline._x += speed * direction.fla. var my_mcl:MovieClipLoader = new MovieClipLoader(). } }.jpg".helpexamples. reverse the animation direction if ((target_mc.onEnterFrame = function() { target_mc. 10). 100). The animation is much smoother if you use a higher frame rate.setMask(mask_mc). 3. 20).com/"). such as 24 fps._width)) || (target_mc. } var mcl_obj:Object = new Object(). my_mcl. and add the following code to the Actions panel: System.allowDomain("http://www. // create clip to load an image into this. lineTo(0. Scripting animation with ActionScript 2. 0).To pan an instance on the Stage using code: 1.onLoadInit = function(target_mc:MovieClip) { // set the target movie clip's mask to mask_mc target_mc.helpexamples. mcl_obj. img_mc).createEmptyMovieClip("img_mc". Change the frame rate of the document to 24 fps in the Property inspector. endFill(). 0). lineTo(0. Create a new Flash document called pan. // if the target_mc is at an edge. 0).com/flash/images/image1. // create a clip to use as a mask this.loadClip("http://www. lineTo(300.0 479 . moveTo(0.addListener(mcl_obj)._x <= -(target_mc.createEmptyMovieClip("mask_mc". target_mc. 0). // initialize variables var direction:Number = -1. lineTo(300. // use the Drawing API to draw/create a mask with (mask_mc) { beginFill(0xFF0000.

specifies the listener object you created earlier. The direction variable controls whether the masked image scrolls from left to right (1) or right to left (-1). The image is masked at runtime. About bitmap caching. and begins loading the JPEG image into the img_mc movie clip. unrotated pixels snapped to the nearest pixel boundaries.cacheAsBitmap property to true. Pixels are mapped one-to-one with the parent object. instead of to the main Stage. 4.cacheAsBitmap or Button. the animation reverses. This object defines an event listener for the onLoadInit event. When you set the MovieClip. although the animation appears a bit less smooth. The bitmap is copied to the main Stage as unstretched. scrolling. a new object (mcl_obj) is created. and sets up the scrolling animation. After the image reaches the left or right edge of the mask. you can view it online (http://www. To see the original image.jpg). The speed variable controls how many pixels are moved each time the onEnterFrame event handler is called. and performance Flash Player 8 introduces bitmap caching. The final block of code defines a MovieClipLoader instance. A 300 pixel by 100 pixel rectangle is drawn inside the mark_mc movie clip using the Drawing API. and Drawings . Next. This can improve performance for movie clips that contain complex vector content. masks the dynamically loaded image. which helps you enhance the performance of nonchanging movie clips in your applications. NO T E 480 Animation. Larger numbers cause the animation to move more quickly. If the bounds of the bitmap change. All of the vector data for a movie clip that has a cached bitmap is drawn to the bitmap. Filters. the bitmap is re-created instead of being stretched. The next section of code creates two empty movie clips: img_mc and mask_mc. Select Control > Test Movie to test the document. The image loads and then animates back and forth in a panning motion (side to side motion).helpexamples. Flash Player caches an internal bitmap representation of the movie clip or button instance.com/flash/images/image1.The first section of code in this code example defines two variables: direction and speed. which you use as a listener for a MovieClipLoader instance created in the final block of code.

0 only). you also install two powerful classes: the Tween and TransitionManager classes. which is similar to when you create a PowerPoint presentation. You can find a sample source file that shows you how bitmap caching can be applied to an instance. Find the sample source file. ■ In Windows. you can select behaviors that add different kinds of transitions between slides. On the Macintosh.For detailed information on caching button or movie clip instances see the following sections in Chapter 11. browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\CacheBitmap. which generate ActionScript that animates the screens depending on the behavior that you choose. in the Samples folder on your hard disk.fla. in the Samples folder on your hard disk. “Working with Movie Clips”: ■ ■ ■ “About caching and scrolling movie clips with ActionScript” on page 369 “Caching a movie clip” on page 373 “Setting the background of a movie clip” on page 375 It’s ideal to use the cacheAsBitmap property with movie clips that have mostly static content and that do not scale and rotate frequently. With such movie clips. see “When to enable caching” on page 371. ■ In Windows. ■ About the Tween and TransitionManager classes When you install Flash Basic 8 or Flash Professional 8. ■ You can also find a sample source file that shows you how to apply bitmap caching to scrolling text. For detailed information about when to use this feature. browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\FlashType. You add this functionality into a screen application by using the Tween and TransitionManager classes. This section describes how to use these classes with movie clips and Macromedia V2 components (included with Flash MX 2004 and Flash 8) to add animation easily to your SWF files. On the Macintosh. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/CacheBitmap. flashtype. About the Tween and TransitionManager classes 481 . Find the file called cacheBitmap. If you create a slide presentation or form application with Flash Professional 8 (ActionScript 2. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/FlashType.fla. using the cacheAsBitmap property can lead to performance improvements when the movie clip is translated (when its x and y position is changed).

You can also use the Tween and TransitionManager classes. you can use the classes with the component set of version 2 of the Macromedia Component Architecture. “Tween class” in the Components Language Reference. For information on each method and property of the TransitionManager class. If you want to change the way a ComboBox component animates. or with movie clips. Easing refers to gradual acceleration or deceleration during an animation. and Drawings . but these classes are available in both Flash Basic 8 and Flash Professional 8. see Chapter 51. see “Working with filter packages” on page 499. Filters. instead of creating motion tweens on the timeline or writing custom code. which helps your animations appear more realistic. to create your own animated menu system. For example. The Tween and TransitionManager classes are available only in ActionScript 2. “TransitionManager class” in the Components Language Reference.You can also use the Tween and TransitionManager classes outside of a screen-based document. NO TE ■ ■ ■ ■ ■ ■ ■ ■ For information on each method and property of the Tween class. On the Macintosh. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Tween ProgressBar. Find tweenProgress.fla in the Samples folder on your hard disk. In Windows. you can use the TransitionManager class to add some easing when the menu opens. see Chapter 48. browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Tween ProgressBar. “Adding tweens and transitions to a file in Flash Professional 8 (Flash Professional 8 only)” on page 483 “Animating with the TransitionManager and Tween classes” on page 485 “About easing classes and methods” on page 488 “About the Tween class” on page 489 “Using the Tween class” on page 490 “Combining the TransitionManager and Tween classes” on page 496 For more information on the Tween and TransitionManager classes.0. You can find a sample source file that uses these classes to add scripted animation. For information on working with packages. see the following topics: 482 Animation. in either Flash Basic 8 or Flash Professional 8.

Select Window > Behaviors to open the Behaviors panel. easing:mx.start(eventObj.transitions.TransitionManager. 4. NO T E The Tween and TransitionManager classes are designed to let you use simple ActionScript to add animations to parts of your SWF file. 2. Select File > New to create a new slide presentation in Flash Professional 8. 5. Before you start to use these transitions with movie clips in Flash. Select the Zoom transition.easing. The Flash authoring environment contains behaviors that let you use these prebuilt classes for transitions in a screen-based application. 6. you should see what they do when you use a screen-based application.transitions. duration:1.Bounce. Select Bounce from the Easing pop-up menu.transitions. The following snippet shows the relevant transition code: mx. Click Add Behavior (+). The following sections include examples that show you how. About the Tween and TransitionManager classes 483 . This adds about 15 lines of ActionScript directly onto the slide.Zoom. To view the ActionScript that creates a transition in a slide presentation: 1. Click OK to apply the settings and close the dialog box. To create a slide presentation or form application. 9. param1:empty. you can select behaviors that add different kinds of transitions between slides. Type 1 into the Duration text box.easeOut. 3. Select Screen > Transition from the pop-up menu to open the Transitions dialog box. param2:empty}). 8. direction:0. you can add transitions and tweens to your Flash Basic 8 (or Flash Professional 8) applications if you use code. Select Flash Slide Presentation from the General tab and click OK. However.Adding tweens and transitions to a file in Flash Professional 8 (Flash Professional 8 only) This section describes adding tweens and transitions to a Flash Professional slide presentation to demonstrate what they look like for Flash Professional users. 7.target. {type:mx.

Has the screen or movie clip appear like a photographic flash. but slow down before it arrives at a full stop at the end of the animation.target to the desired movie clip’s instance name. To apply this effect to a movie clip. Masks the screen or movie clip by using disappearing or appearing rectangles. Filters. which helps your animations appear more realistic.This code calls the TransitionManager class and then applies the Zoom transition with the specified mx. 484 Animation. which you can customize by using the easing methods and several optional parameters. Zooms the screen or movie clip in or out. There are many equations for this acceleration and deceleration. Remember. Modifying the code to work with a movie clip symbol is easy: change the first parameter from eventObj. Reveals the next screen or movie clip by using disappearing or appearing rectangles. Reveals the screen or movie clip by using an animated mask of a shape that moves horizontally.easing. Slides in the screen or movie clip from a particular direction. and Drawings . For example. you can modify the ActionScript to use in your Flash animations. easing refers to gradual acceleration or deceleration during an animation. which change the easing animation accordingly. Rotates the current screen or movie clip. Flash comes with ten transitions. The following table describes the transitions included in Flash Basic 8 (using code) and Flash Professional 8 (using code or behaviors): Transition Iris Wipe Pixel Dissolve Blinds Fade Fly Zoom Squeeze Rotate Photo Description Reveals the screen or movie clip by using an animated mask of a shape that zooms in. a ball might gradually increase its speed near the beginning of an animation.easeOut easing method.transitions.Bounce. Fades the screen or movie clip in or out. In this case. the transition applies to the selected slide. Scales the current screen or movie clip horizontally or vertically.

The Transitions dialog box lets you preview a sample animation before you apply the effect to the slide or form. About the Tween and TransitionManager classes 485 . components. Click OK to convert the bitmap image into a movie clip. Select the imported image on the Stage and select Modify > Convert to Symbol Name the symbol img1.Each transition has slightly different customizations that you can apply to the animation. Select File > Import > Import to Stage. 4. you have to write custom code to animate movie clips or modify their level of transparency (alpha) and coordinates (location). To animate a movie clip using the TransitionManager class: 1. 7. If you add easing to the animation. so you need to convert the image manually into a movie clip symbol. However. 6. Select File > New and select Flash Document. you can double-click Transition. 3. 5. the registration point of the symbol is in the upper-left corner of the symbol. Save the FLA file as zoom.swf in boot drive\Program Files\Macromedia\Flash 8\language\First Run\Behaviors\ folder or Macintosh HD:Applications:Macromedia Flash 8:First Run:Behaviors: to open the SWF file in the stand-alone player. The image is imported into your file as a bitmap image. the ActionScript (and mathematics) can become complex quickly. To preview how each transition works with the different methods in the easing classes. you can select a different class instead of trying to figure out the new mathematical equations you need to create a smooth animation. if you want to change the easing on a particular animation and you use these prebuilt classes. and select an image on your hard disk to import into the FLA file. 8. If you don’t use the TransitionManager or the Tween class. By default. TI P Animating with the TransitionManager and Tween classes You can use the TransitionManager and Tween classes in Flash Basic 8 and Flash Professional 8 to add animations to movie clips.fla. Click OK to create the new FLA file. The following procedure animates a movie clip so that it uses the TransitionManager class to zoom in on the Stage. and make sure you set the behavior to Movie Clip. 2. and frames using ActionScript. Click Open to import the image.

direction:0. modify the symbol’s registration point when you convert the image from a bitmap into a symbol. param2:empty}). 3. With the bitmap image still selected on the Stage. param1:empty. If the animation moves too quickly.transitions.9. Frame 1 of the main Timeline and add the following ActionScript to the Actions panel: mx. 2. see “Working with filter packages” on page 499. 4. Save the file as zoom2.transitions. you don’t need to write complex math to create easing methods. Name the symbol img2. The image grows and has a slight bouncing effect before it returns to its original size.TransitionManager.start(img1_mc. Select 11. Creating complex animations is easy using the Tween and TransitionManager classes and doesn’t require you to create motion or shape tweens on the timeline. N OT E 10. Complete the steps in the previous procedure. duration:3). Open the zoom.transitions.fla file. press F8 to convert the symbol into a movie clip.easeOut. increase the animation’s duration (in the previous code snippet) from one second to two or three seconds (for example. With the image still selected.Bounce. 486 Animation.Zoom. Most importantly. To zoom images in from the center of the image: 1. easing:mx. Filters. This is different from the preview you see in the Transitions dialog box.fla. duration:1. {type:mx. open the Property inspector (Window > Properties > Properties). Drag a copy of the bitmap symbol from the Library panel onto the Stage beside the current movie clip symbol. Select Control > Test Movie to test the animation.easing. and Drawings . and assign the movie clip the instance name img1_mc. and select File > Save As to save a new copy of the document. If you want images to zoom in from the center instead of anchoring on a corner. For information on working with packages. You might notice that the image is anchored in the upper-left corner and grows toward the lower-right corner.

easing.TransitionManager. 8. Find tweenProgress. direction:mx.transitions. Select the new movie clip on the Stage and use the Property inspector to give it an instance name of img2_mc. N OT E For information on each method and property of the Tween class.Bounce. 7. ■ In Windows. 6.5.easeOut}). browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Tween ProgressBar.transitions. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Tween ProgressBar. if the registration point is in the upper-left corner (default) when you use the Zoom transition. Select Control > Test Movie to test the animation. Select Frame 1 of the main Timeline and add the following ActionScript to the existing code: mx.fla in the Samples folder on your hard disk. duration:1. For example. “Tween class” in the Components Language Reference. easing:mx. You can find a sample source file that uses these classes to add scripted animation. {type:mx. For information on each method and property of the TransitionManager class. “TransitionManager class” in the Components Language Reference. the transition begins from that location.transitions. see Chapter 51.Zoom. The second movie clip grows from the center of the symbol instead of the corner. click the center of the 3 x 3 grid to set the registration point to the center of the bitmap and click OK. On the Macintosh.transitions. see Chapter 48.IN. In the Convert to Symbol dialog box.start(img2_mc.Transition. Changing the registration point can have a dramatic effect on how the animation looks in a SWF file. Some transitions are sensitive to where you locate the registration point. ■ About the Tween and TransitionManager classes 487 .

browse to Hard Disk\Program Files\Macromedia\Flash 8\language\First Run\Classes\mx\transitions\easing\ folder on Windows (assumes a default installation). This effect is similar to Regular easing. or both. the ActionScript refers to the easeOut() method within the Bounce.as class. Provides the easing effect at the beginning and end of the transition. slowing down. Flash 8 offers five additional easing classes. and Drawings . or Macintosh HD:Applications:Macromedia Flash 8:First Run:Classes:mx:transitions:easing. which are described in the following table: Method easeIn easeOut easeInOut Description Provides the easing effect at the beginning of the transition. In addition to Bounce. 488 Animation. Adds a bouncing effect within the transition range at one or both ends. Adds slower movement at one or both ends. Elastic Regular Strong None These six easing classes each have three easing methods.easing. a slowing down effect. which are described in the following table: Transition Back Bounce Description Extends the animation beyond the transition range at one or both ends once to resemble an overflow effect. Adds an equal movement from start to end without effects. or speeding up. Adds slower movement at one or both ends. The number of bounces relates to the duration—longer durations produce more bounces. but it’s more pronounced.easeOut easing class and method. Provides the easing effect at the end of the transition. The procedure on zooming images under “Animating with the TransitionManager and Tween classes” on page 485 used the mx. The amount of elasticity is unaffected by the duration. Filters.Bounce. This feature lets you add a speeding up effect. In the folder on your hard disk. This ActionScript file is in the easing folder.transitions. This transition is also called a linear transition. To open these classes in Flash or your ActionScript editor. Adds an elastic effect that falls outside the transition range at one or both ends.About easing classes and methods “Adding tweens and transitions to a file in Flash Professional 8 (Flash Professional 8 only)” on page 483 describes how to use the Bounce easing class to add a bouncing effect to the movie clip.

and fade movie clips easily on the Stage. useSeconds) { // code . begin. the duration is set to infinity by default. Find tweenProgress. } obj prop func The movie clip object that the Tween instance targets.transitions. finish A number that indicates the ending value of prop (the target object property to be tweened).. To preview how each transition works with the different methods in the easing classes. see Chapter 51.swf in boot drive\Program Files\Macromedia\Flash 8\language\First Run\Behaviors\ or Macintosh HD:Applications:Macromedia Flash 8:First Run:Behaviors: to open the SWF file in the stand-alone player. begin A number that indicates the starting value of prop (the target object property to be tweened). prop. A string name of a property in obj to which the values are to be tweened. func. A number that indicates the length of time of the tween motion. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Tween ProgressBar. resize. which indicates to use seconds if true. browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Tween ProgressBar. About the Tween and TransitionManager classes 489 . you can double-click Transition. “TransitionManager class” in the Components Language Reference. About the Tween class The Tween class lets you move. The easing method that calculates an easing effect for the tweened object’s property values.Tween class has the following parameter names and types: function Tween(obj. In Windows. duration. If omitted. On the Macintosh. finish.For information on each method and property of the Tween class.. see Chapter 48. duration useSeconds A Boolean value related to the value you specify in the duration parameter. TIP ■ ■ You can find a sample source file that adds scripted animation using these classes. or frames if false. “Tween class” in the Components Language Reference. The constructor for the mx.fla in the Samples folder on your hard disk. For information on each method and property of the TransitionManager class.

mx. as the following procedure shows. you can write some code in an onEnterFrame event handler. 300. true). which animates the ball_mc movie clip on the Stage along the x-axis (left to right). This means that the ball extends past 300 pixels on the x-axis before using a fluid motion effect to animating back.Elastic.easing. new Tween(ball_mc. You can add keyframes to a timeline and insert a motion or shape tween between them. To take advantage of the Tween class. The movie clip animates from 0 pixels to 300 pixels in three seconds. Create a new document and call it easeTween. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Tween ProgressBar.fla. imagine that you want to move a movie clip across the Stage. You can also add the previously described easing methods. 3.easeOut. 0.transitions. Stage. To import and use the Tween class: 1.easeOut. "_x". 0. 4. import mx. you have another option that lets you modify a movie clip’s _x and _y properties. and the ActionScript applies an elastic easing method. you might opt to use an import statement.Tween. or you can use the setInterval() function to call a function at periodic intervals.transitions. and Drawings .*.easing. 3.fla in the Samples folder on your hard disk. If you use the Tween class. This lets you import the Tween class and easing methods rather than give the fully qualified class names each time you use them.width. browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Tween ProgressBar. 3.transitions. You can find a sample source file that adds scripted animation using these classes.transitions. 2. Select Frame 1 of the Timeline and add the following code in the Actions panel: import mx.For example.Tween(ball_mc. 490 Animation. ■ In Windows. Filters. true). On the Macintosh. Find tweenProgress. you can use the following ActionScript: new mx. This ActionScript snippet creates a new instance of the Tween class. Select the movie clip instance and type ball_mc into the Instance Name text box in the Property inspector. Elastic. ■ Using the Tween class If you use the Tween class in more than one place in your Flash document. Create a movie clip on the Stage. "_x".

2. Likewise. as the next procedure shows. For more information. You might agree that importing an entire package is much better than having to import the six classes separately. Select the movie clip instance. new Tween(ball_mc. The second statement imports an entire package of classes. 5. NO TE 5. see “Working with filter packages” on page 499. For information on animation and frame rate. Create a movie clip on the Stage. In this case.Tween class.fla. you set the _alpha property to fade instances in and out. 100. the package resides in the C:\Program Files\Macromedia\Flash 8\language\First Run\Classes\mx\transitions\easing folder (Windows). Instead of referring to the mx. see “About animation and frame rate” on page 471.This code example uses two import statements. import mx. Create a new document. 3. see “Working with filter packages” on page 499.Tween class only. 4. To fade instances using the Tween class: 1. Strong. Flash documentation defines package as directories that contain one or more class files and that reside in a designated classpath directory.easing.easeOut for example. and call it fadeTween. 0.transitions. For information on working with packages. and the second import statement uses the wildcard (*) shortcut to import each of the six easing classes by using a single line of code. Select Control > Test Movie to see the animation. mx. you can type Elastic.transitions.transitions. instead of the _x property.transitions.easing. Using similar code. Select Frame 1 of the Timeline and add the following code in the Actions panel: import mx. or HD:Applications:Macromedia Flash 8:First Run:Classes:mx:transitions:easing (Macintosh).transitions. About the Tween and TransitionManager classes 491 . the animation appears to play more smoothly. your ActionScript directly refers to the Tween class. 3. true). To make the symbol fade out more quickly. If you change the document’s frame rate.Elastic. Instead of moving around the Stage. The first statement imports the mx. now ball_mc fades from 100% visible to completely transparent in three seconds. Select Control > Test Movie to see the animation. change the duration parameter from 3 to 1 or 2.easeOut in your ActionScript code. instead of using the fully qualified class name for the easing classes.Tween.easeIn. "_alpha".*. and type ball_mc into the Instance Name text box in the Property inspector.

the duration is the number of frames you want to use for the tween. The next procedure shows how to set a tween to frames instead of seconds. If your Flash document uses a frame rate of 12 frames per second (fps). Return to the authoring environment and open the Property inspector. If you increase the frame rate of your FLA file. you change the final parameter. Instead of fading the instance for three seconds. you see the instance fade out sooner. 492 Animation. When you set the parameter to true. Select the movie clip instance. Select Control > Test Movie to see the animation.transitions. 7. 100. 4. see “About animation and frame rate” on page 471. and Drawings . and call it framesTween.*. However. Wait a moment. 3. you can write an event handler that triggers when the animation completes. it fades the instance across 24 frames. the previous code snippet fades the instance over two seconds (24 frames/12 fps = 2 seconds).easeIn easing method. Strong. you can significantly change the speed of your animation when you change the document’s frame rate. Change the document’s frame rate to 24 fps. 2. To set the duration in frames instead of seconds in the Tween class. import mx. new Tween(ball_mc. "_alpha". 0.Tween. 6. 24. To set a duration of frames instead of seconds: 1.easing. from true to false.Instead of using seconds. If you use frames to measure duration.easeIn. and add the following code in the Actions panel: import mx. Select Frame 1 of the Timeline. you can fade the symbol over a few frames.transitions. as the next procedure shows. The Tween class has several more useful features. Using frames instead of seconds offers more flexibility. you tell Flash that the specified duration is in seconds. then the instance fades out across 24 frames. false). Create a movie clip on the Stage. If you set the parameter to false. For information on animation and frame rate. Create a new document. but remember that the duration relates to the frame rate of the current Flash document. Filters. if your frame rate is 24 fps. For example. useSeconds. and type ball_mc into the Instance Name text box in the Property inspector. the same code fades the instance over one second (24 frames/24 fps = 1 second). without modifying your ActionScript. 5.fla. This code fades out the ball_mc instance using the Strong.

you see the message “onMotionFinished triggered” appear in the Output panel after ball_mc finishes fading on the Stage. }. tween_handler. import mx. see Chapter 7.To trigger code when an animation is completed: 1.fla. 5. “Classes.transitions.” About continuing animations using the continueTo() method “Using the Tween class” on page 490 demonstrates how to use the Tween class in your applications. the Tween class offers a simpler solution. 2. 0. The continueTo() method instructs the tweened animation to continue from its current value to a new value. var tween_handler:Object = new Tween(ball_mc. One solution is to reanimate the ball by using the onMotionFinished event handler. However. and then the instance fades out. as the following ActionScript shows: import mx. "_alpha". Regular. For more information on functions. 3.transitions. you see the message appear in the Output panel.continueTo(0. However. Create a movie clip on the Stage. Select Frame 1 of the Timeline and add the following code in the Actions panel: import mx. 3. }.*.transitions. var ball_tween:Object = new Tween(ball_mc.Tween. true). 3. Strong. if you want to move the ball after the initial animation is complete. 300. and call it triggerTween. Select the movie clip instance and type ball_mc into the Instance Name text box in the Property inspector.easeIn. Create a new document. ball_tween.onMotionFinished = function() { ball_tween. the continueTo() method.onMotionFinished = function() { trace("onMotionFinished triggered"). Wait for a moment. When it finishes tweening. 100.*. there are at least two ways you can do it.easing. "_x". Select Control > Test Movie to see the animation. 0.Tween. If you test this ActionScript in your FLA file. 4.easeIn.transitions.easing. About the Tween and TransitionManager classes 493 . true). 3). import mx.

The continueTo() method tells the target object (ball_mc) to proceed from its current position and animate for three seconds along the x-axis to 0 pixels and to use the same easing method.easing. Creating animations that run continuously You can make an animation continue moving back and forth along the x-axis without stopping. 3. useSeconds) { /* omitted to save space.onMotionFinished = function() { ball_tween. as the following snippet shows: function Tween (obj. as the following ActionScript shows: import mx.*. prop. This code moves the ball_mc instance along the x-axis from 0 pixels to 300 pixels in three seconds.transitions. Filters. import mx. duration:Number):Void { /* omitted to save space. it uses the duration you specify in the call to the Tween constructor. begin. finish. 3).easeIn. func (easing type). and then it reverses the begin and finish parameters.transitions. func. prop. The continueTo() method uses the finish value from the call to the Tween class. If you don’t specify a duration for the continueTo() method. true).After the initial tween finishes. "_x". the ball_mc movie clip tweens back to its original position at 0 pixels. the onMotionFinished event handler is triggered and calls the continueTo() method. var ball_tween:Object = new Tween(ball_mc. The Tween class accommodates this kind of animation with the aptly named yoyo() method. The yoyo() method waits for the onMotionFinished event handler to execute. instead of the seven arguments for the Tween constructor method. 300. */ } The five parameters that aren’t required by the continueTo() method (obj. instead of specifying a value for the begin argument.continueTo(0. begin.Tween. You use the values specified in the call to the Tween constructor method for any parameters that you don’t define in the continueTo() method. as the following procedure demonstrates. 494 Animation. prop. After the animation finishes. you assume that the obj. and Drawings . The animation begins again. 0. Regular. func. When you call the continueTo() method. */ } Only two arguments pass to the continueTo() method. }. The following snippet (edited for brevity) shows the function prototype for the continueTo() method: function continueTo(finish:Number. duration. and useSeconds arguments are the same as in the earlier call to the Tween class. and useSeconds) use the arguments that you defined earlier in the call to the Tween class. ball_tween.

lineTo(0. 5. 3. The box animates from left to right and back. as well as each class in the easing package.createEmptyMovieClip("box_mc".easeInOut. endFill(). About the Tween and TransitionManager classes 495 . it animates outside the boundaries of the Stage.fla.easing. To make adjustments.yoyo(). Regular.transitions. 2. 0). this. 0). 0. 4. While this might not seem significant. 3. Select Control > Test Movie to test the animation. }.box_mc. Regular._width). 3. As the box approaches the right edge of the Stage. Create a new Flash document called yoyo.Tween. The next section of code creates a new movie clip with an instance name of box_mc and draws a rectangle 20 pixels wide and the same height as the Stage. Open the Actions panel and enter the following ActionScript on Frame 1 of the Timeline: import mx. Stage.To create an animation that continues endlessly: 1.onMotionFinished = function() { box_tween. with (box_mc) { beginFill(0xFF0000. import mx. 60).width . lineTo(20. you might want to increase the document’s frame rate from 12 fps to 24 fps. you might not want the rectangle to disappear from view off the side of the Stage and then reappear a second later and animate in the other direction. this. Stage. true). "_x".*. 0). "_x". This code creates a new tween to animate the box_mc movie clip across the Stage along the x-axis over 3 seconds.height). To stop the rectangle from disappearing. 0.width.transitions. true). Add the following ActionScript after the code created in the previous step: var box_tween:Tween = new Tween(box_mc.height).getNextHighestDepth()). If the animation isn’t smooth. moveTo(0. animate the rectangle from 0 pixels to the width of the Stage minus the width of the box_mc movie clip. Stage. } The first section code begins by importing the Tween class. lineTo(20. lineTo(0. box_tween. revise the corresponding lines of code from step 3 to match the following code: var box_tween:Tween = new Tween(box_mc. (Stage.easeInOut.

496 Animation.com/flash/images/image1. this. true).createEmptyMovieClip("img_mc". duration:3. direction:Transition. Each class can use a different easing method. 2.loadClip("http://www.easeIn.transitions. Create a new Flash document and save the file as combination. import mx. 0. var my_mcl:MovieClipLoader = new MovieClipLoader().jpg". Now. mcl_obj.fla. Combining the TransitionManager and Tween classes You can generate interesting effects when you combine the TransitionManager and Tween classes. Add the following ActionScript on Frame 1 of the Timeline: import mx. as the following procedure shows. the box stops easing before it goes off the boundaries of the Stage. startPoint:6}).start(target_mc.getNextHighestDepth())).easing. Strong. Fly). my_mcl. TransitionManager. my_mcl.helpexamples. which means you have many animation possibilities for objects in your SWF files. "_alpha". To use the TransitionManager and Tween classes together: 1.onLoadInit = function(target_mc:MovieClip) { new Tween(target_mc. this.easeInOut.easing package. or the selected transition (in this case. This process can reduce the amount of code you type and save you from potential typographical errors.6. You import the entire transitions package in this example so you do not need to enter the fully qualified class name for the Tween class. 2. TransitionManager class. var mcl_obj:Object = new Object().IN. and Drawings . easing:Elastic. You can take advantage of the continueTo() and yoyo() methods in the Tween class or the onMotionFinished event handler to create a unique effect. This code is separated into three main sections. }.*. Filters. Test the animation again (Control > Test Movie).*. {type:Fly. 100.addListener(mcl_obj). You combine the TransitionManager and Tween classes to animate a dynamically loaded movie clip and fade it in on the Stage after it fully loads from the remote server.transitions. You can use the TransitionManager class to move a movie clip along the x-axis while you adjust the same clip’s _alpha property using the Tween class. The first section of code imports the classes within the transitions package as well as the transitions.

This event handler fades in the target movie clip because you modify the _alpha property in the Tween class. After the external JPEG image finishes downloading from the server. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Tween ProgressBar.The second section of ActionScript creates a listener object for the MovieClipLoader class instance. the image fades in gradually and animates from right to left across the Stage. For information on each method and property of the Tween class. Then you load the target JPEG image into a movie clip that you create dynamically by calling the createEmptyMovieClip() method. When the target movie clip loads into the MovieClipLoader instance. “Tween class” in the Components Language Reference. which calls both the Tween class and the TransitionManager class.fla in the Samples folder on your hard disk. browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Tween ProgressBar. For information on each method and property of the TransitionManager class. and flies the target movie clip along the x-axis. On the Macintosh. see “Using the Tween class” on page 490. which you create in the third section of code. see Chapter 48. “TransitionManager class” in the Components Language Reference. For information on using the Tween class. see Chapter 51. ■ About the Tween and TransitionManager classes 497 . The third section of ActionScript code creates a MovieClipLoader instance and applies the listener object that you created earlier (so the target movie clip loader instance can listen for the onLoadInit event). ■ In Windows. You can find a sample source file that adds scripted animation using these classes. the onLoadInit event triggers and executes the block of code. Find tweenProgress. 3. Save your document and select Control > Test Movie to view the animation in the test environment.

buttons. You can apply each of these filter effects to movie clips. box_mc.Using filter effects Filters are visual effects that you can apply to objects rendered at runtime by Flash Player. box_mc. blur. Create a new Flash document and save it as animFilter. contrast.filters = [new flash. movie clip. saturation.blur <= 10)) { dir *= -1. glow. } var filter_array:Array = box_mc.filters = filter_array. 0). box_mc.blur >= 30) || (box_mc.filters. 0). The following procedure demonstrates how you could use an onEnterFrame event handler to animate a glow filter effect on a movie clip.onEnterFrame = function() { box_mc. These filters are applied to the vector definitions. 0x000000). 10). box_mc. If you use ActionScript to apply the filters to an instance.fla.lineTo(0. You can also write ActionScript that lets you modify an existing filter that you applied to a text field. or text fields by using either the Filters tab in the Property inspector or by using ActionScript.beginFill(0x000000).blurY = box_mc.lineTo(160. box_mc.blur += dir. }. gradient glow. box_mc. box_mc. You can apply filters using the Flash user interface in Flash Professional 8. 0).moveTo(0. box_mc. if ((box_mc. or button. box_mc. box_mc. Add the following ActionScript to Frame 1 of the Timeline: this.blur = 10.GlowFilter()]. var dir:Number = 1. such as movie clip instances. and gradient bevel. You can also use an adjust color filter that lets you edit a movie clip’s brightness._y = 100. box_mc.endFill().blur. and hue. 498 Animation. Filters. box_mc. 2.filters. you can also use a displacement map filter (see “Using the displacement map filter” on page 528) or a convolution filter (see “Using the convolution filter” on page 527).lineStyle(20.blur. box_mc. box_mc. The filters include drop shadow. filter_array[0]. To animate a filter effect applied to a movie clip instance: 1.blurX = box_mc.createEmptyMovieClip("box_mc". filter_array[0].lineTo(0. and Drawings ._x = 100. or using ActionScript in Flash Basic 8 or Flash Professional 8. 120). 120).lineTo(160. bevel. so there is no overhead of storing a bitmap image within the SWF file.

■ In Windows. BlurFilter. rotating. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Filters. To use the import statement. “Working with filter packages” on page 499 “Working with filters.This code completes two different functionalities. or reference it using a fully qualified name. and so on) in Flash 8. 3. or less than or equal to 10. The second block of code applies a glow filter to the rectangle on the Stage and defines an onEnterFrame event handler.fla. in the Samples folder on your hard disk. skewing. The onEnterFrame event handler animates the glow filter between a blur of 10 and 30 pixels. and after the animation is greater than or equal to 30. The first section creates and positions a movie clip instance. and the MovieClip class” on page 501 “About hit detection. see the following topics: ■ ■ ■ ■ ■ For an example of using ActionScript to apply filters. DropShadowFilter.filters package is a directory on your hard disk that contains several class files for each filter type (such as BevelFilter. and filters” on page 504 For more information on working with filters in an application. performance. For example. Filters. N OT E Using filter effects 499 . you can find a sample source file. caching. ■ Working with filter packages Packages are directories that contain one or more class files and reside in a designated classpath directory. When class files are organized this way. which is responsible for animating the filter effect. You either import the class. and scaling filters” on page 503 “Applying filters to object instances and BitmapData instances” on page 503 “About error handling. On the Macintosh. Save your changes to the Flash document and select Control > Test Movie to test the SWF file. and draws a black rounded rectangle on the Stage. you must specify ActionScript 2. browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Filters.0 and Flash Player 6 or later in the Flash tab of your FLA file’s Publish Settings dialog box. you must access the classes in a specific way. the direction of the animation reverses. the flash.

and Drawings .*. Filters. This can save typing and reduces the chance of making typing mistakes: // with importing import flash.The import statement lets you access classes without specifying their fully qualified names.filters. DropShadowFilter. The first way to import multiple classes is to import each class by using a separate import statement. 10. var myBlur:BlurFilter = new BlurFilter(10.filters. If you don’t import the BlurFilter class. which imports all classes within a certain level of a package.BlurFilter = new flash. import flash.filters. and GlowFilter) you can use one of two ways to import each class. If you use individual import statements for each class within a package. On that frame. as seen in the following snippet: import flash.BlurFilter. You can avoid importing individual class files by using a wildcard import. // imports each class within flash. For example. 3).filters. The following ActionScript code demonstrates the differences between using the import statement and using fully qualified class names.filters. you must refer to it by its fully qualified name (flash. 3). The same code.filters package The import statement applies only to the current script (frame or object) in which it's called.filters. written with an import statement.filters. 10. To use the class name on another frame script. your code needs to use the fully qualified class name (package name followed by class name) in order to use the filter: // without importing var myBlur:flash. reference classes in that package by their fully qualified names or add an import statement to the other frame that imports the classes in that package. you can reference classes in the package by using their class names instead of their fully qualified name. lets you access the BlurFilter using the class name instead of continually referencing it using the fully qualified name.BlurFilter. To import several classes within a package (such as the BlurFilter. import flash. it becomes time consuming to write and prone to typing mistakes. For example. 500 Animation. if you import it.GlowFilter.filters.DropShadowFilter. to use a BlurFilter in a script.BlurFilter) or import it.BlurFilter(10.util package. suppose on Frame 1 of a Flash document you import all the classes in the macr. you can refer to it by its class name (BlurFilter) in your code instead. The following ActionScript shows an example of using a wildcard import: import flash.

If you import a class but don't use it in your script. in the Samples folder on your hard disk. Calling this property returns an array that contains each filter object currently associated with the movie clip instance.distance). In Windows. the class isn't exported as part of the SWF file. which helps improve performance. Working with filters. the bytecode associated with a class is included in a SWF file only if that class is actually used. Setting and getting the filters by using the property returns a duplicate of the filters object. remember that classes are only imported for the level that you specify.transitions package.easing package).fla. it’s marked to cache itself as a transparent bitmap when the SWF file loads. and the MovieClip class If a movie clip has an associated filter.transitions. The cached bitmap is used as a source image for the filter effects. TIP ■ ■ For an example of using ActionScript to apply filters. you can find a sample source file. This means that you can import large packages without being concerned about the size of the SWF file. On the Macintosh. not all classes within subdirectories (such as the classes in the mx. // 4 You can access and modify filters as you would a regular array object. Using filter effects 501 . Each movie clip usually has two bitmaps: one bitmap is the original unfiltered source movie clip.filters[0].filters[0]. // 45.filters property. such as the following: trace(my_mc. the second bitmap is the final image after filtering. Flash Player caches the movie clip as a bitmap at runtime by forcing the cacheAsBitmap property to be true. As long as the movie clip has at least one filter applied to it. if you import all classes in the mx.angle). not a reference. If you do not change the appearance of the movie clip at runtime. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Filters. You can access filters applied to an instance by calling the MovieClip. only the classes within the /transitions/ directory are imported. you can use code similar to the code in the following procedure. the final image does not need to update.0 trace(my_mc. A filter itself has a set of properties unique to that filter. browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Filters.When you use import statements. caching. Filters. For example. To modify an existing filter.

and Drawings . Filtered content has the same restrictions on size as content with its cacheAsBitmap property set to true. Add the following ActionScript to Frame 1 of the Timeline: this. The blur filter always blurs perfectly horizontally or vertically. If the author zooms in too far on the SWF file. lineTo(0.filters[0]. The second section of code applies a drop shadow filter to the square. Filters. the code creates a temporary array to hold the current filters to apply to the red square on the Stage._x = 100. 0). endFill().filters.distance). 100). independently of the rotation or skew of any item in the parent object tree. trace(my_mc. Create a new Flash document and save the file as modifyFilter. Select Control > Test Movie to test the document.To modify a filter’s properties when applied to a movie clip instance: 1. moveTo(0. The distance property of the first filter is set to 10 pixels. filter_array[0].distance). 2. it is a good idea to disable the zoom menu options.filters[0]. Next.filters = [new flash.createEmptyMovieClip("my_mc". N OT E TIP 502 Animation. lineTo(100. // 4 var filter_array:Array = my_mc. lineTo(0. and positions the shape on the Stage.DropShadowFilter()]. Currently. 10).fla. 3.distance = 10. // 10 The first section of this code uses the Drawing API to create a red square. } my_mc.filters = filter_array. trace(my_mc. 0). // draw square with (my_mc) { beginFill(0xFF0000. my_mc. lineTo(100. When you publish SWF files with filters._y = 100. // use default DropShadowFilter values my_mc. 100). 0). 100). the filters are no longer visible when the bitmap representation is greater than 2880 pixels in either direction.filters. my_mc. and the modified filter is reapplied to the my_mc movie clip instance. no support is available for having any filters perform rotation based upon their parent’s rotation or some sort of other rotation.

or skew with the instance. you can find a sample source file. On the Macintosh. the filter effect does not scale with the instance. skewing. browse to Macintosh HD/Applications/Macromedia Flash 8/Samples and Tutorials/Samples/ActionScript/Filters. the filter does not rotate. Filters. if the instance itself is scaled (_xscale and _yscale are not 100%). if you apply a bevel filter to a button instance. and scaling filters No filtered region (drop shadow. or nest instances and use the BitmapData class to animate filters to achieve this effect. scales. NO T E ■ Using filter effects 503 . for example) outside of a movie clip instance’s bounding box rectangle is considered to be part of the surface for hit detection purposes (determining if an instance overlaps or intersects with another instance).For an example of using ActionScript to apply filters. ■ About hit detection. rotating. in the Samples folder on your hard disk. however. scale.fla. you cannot perform a hit detection on the bitmap result. Use the following guidelines when you apply a filter to an object or BitmapData instance: ■ To apply filters to movie clips. For example.applyFilter() method. browse to boot drive\Program Files\Macromedia\Flash 8\Samples and Tutorials\Samples\ActionScript\Filters. ■ In Windows. rotating. text fields. Scaling. and skewing are not supported by filters. hit detection is not available on the beveled portion of the instance. This means that the original shape of the instance rotates. Because hit detection is vector-based. Calling applyFilter() on a BitmapData object modifies that BitmapData object and cannot be undone. use the filters property. Applying filters to object instances and BitmapData instances The use of filters depends on the object instance to which you apply the filter. use the BitmapData. Setting the filters property of an object does not modify the object and can be undone by clearing the filters property. or skews. (Flash Professional 8 only) You can also apply filter effects to images and video during authoring using the Filters tab in the Property inspector. To apply filters to BitmapData instances. and buttons at runtime. You can animate an instance with a filter to create realistic effects.

performance. and 32) can be computed faster and give a 20% to 30% performance improvement. using values for blurX and blurY that are powers of 2 (such as 2. Animation. After you see an out-of-memory error. these bitmaps can cause your application to use a significant amount of memory if you use many bitmaps. some constructors have restrictions on the length of arrays required as input parameters. it is always a good idea to disable the zoom menu options from the SWF file’s context menu. and use a lower quality setting when possible. Some filter parameters also have a particular valid range. the constructor fails and the filter is not created successfully. No bitmaps are cached for the movie clip. If a convolution filter or color matrix filter is created with an invalid array (not the right size). the value changes to a valid value that’s within the range. For example. Higher values require more CPU and memory for the effect to render. If you set a value that’s outside of the valid range. and Drawings . the following occurs: ■ ■ ■ The filters array is ignored. Also. 16. On a modern computer. Filters. whereas setting the quality parameter to a lower value requires less computer reso