MACROMEDIA FLASH MX 2004 - ACTIONSCRIPT Reference Manual

Actionscript reference guide
Hide thumbs Also See for FLASH MX 2004 - ACTIONSCRIPT:
Table of Contents

Advertisement

Quick Links

ActionScript Reference Guide

Advertisement

Table of Contents
loading

Summary of Contents for MACROMEDIA FLASH MX 2004 - ACTIONSCRIPT

  • Page 1 ActionScript Reference Guide...
  • Page 2 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.
  • Page 3: Table Of Contents

    CONTENTS INTRODUCTION: Getting Started with ActionScript ..... . . 9 Intended audience ..........9 System requirements .
  • Page 4 CHAPTER 3: Writing and Debugging Scripts ......55 Controlling when ActionScript runs ........56 Using the Actions panel and Script window.
  • Page 5 Handling movie clip events ......... 132 Assigning a class to a movie clip symbol .
  • Page 6 PART V: Reference CHAPTER 12: ActionScript Dictionary ....... . 205 Sample entry for most ActionScript elements .
  • Page 7 APPENDIX A: Error Messages ........783 APPENDIX B: Operator Precedence and Associativity .
  • Page 8 Contents...
  • Page 9: Introduction: Getting Started With Actionscript

    INTRODUCTION Getting Started with ActionScript Macromedia Flash MX 2004 and Flash MX Professional 2004 are the professional standard authoring tools for producing high-impact web experiences. ActionScript is the language you use when you want to develop an application within Flash. You don’t have to use ActionScript to use...
  • Page 10: Typographical Conventions

    • For information about accessing web services with Flash applications, see Using Flash Remoting. The Macromedia DevNet website (www.macromedia.com/devnet) is updated regularly with the latest information on Flash, plus advice from expert users, advanced topics, examples, tips, and other updates. Check the website often for the latest news on Flash and how to get the most out of the program.
  • Page 11: Part I: Welcome To Actionscript

    PART I Welcome to ActionScript This part includes basic information on the ActionScript language. Chapter 1 includes information on what is new or changed in ActionScript and Flash Player 7. If you have used ActionScript before, be sure to review this information carefully. If you are new to ActionScript, read Chapters 2 and 3 to get a good foundation for understanding ActionScript terminology and syntax and for learning how to write and debug your scripts.
  • Page 13: Chapter 1: What's New In Flash Mx 2004 Actionscript

    CHAPTER 1 What’s New in Flash MX 2004 ActionScript Macromedia Flash MX 2004 and Macromedia Flash MX Professional 2004 provide several enhancements that make it easier for you to write more robust scripts using the ActionScript language. These new features, which are discussed in this chapter, include new language elements, improved editing and debugging tools (see “ActionScript editor changes”...
  • Page 14: New Security Model And Legacy Swf Files

    • method lets you create MovieClip instances at MovieClip.getNextHighestDepth() runtime and be guaranteed that their objects render in front of the other objects in a parent movie clip’s z-order space. The method lets you access MovieClip.getInstanceAtDepth() dynamically created MovieClip instances using the depth as a search index. •...
  • Page 15: Porting Existing Scripts To Flash Player 7

    You might also need to implement a policy file if you are using runtime shared libraries. If either the loading or loaded SWF file is published for Flash Player 7 and the loading and loaded files aren’t served from the exact same domain, use a policy file to permit access. For more information on policy files, see “About allowing cross-domain data loading”...
  • Page 16 Unlike the changes mentioned above, the changes listed in the following table (some of which also improve ECMA compliance) may cause existing scripts to work differently than they did previously. If you used these features in existing scripts that you want to publish to Flash Player 7, review the changes to make sure your code still works as intended or to determine whether you need to rewrite your code.
  • Page 17 Domain-name rules for settings and local data In Flash Player 6, superdomain matching rules are used by default when accessing local settings (such as camera or microphone access permissions) or locally persistent data (shared objects). That is, the settings and data for SWF files hosted at here.xyz.com, there.xyz.com, and xyz.com are shared, and are all stored at xyz.com.
  • Page 18 Because Flash Player 7 implements exact-domain matching rules instead of superdomain matching rules, you might have to modify existing scripts if you want to access them from files that are published for Flash Player 7. (You can still publish the modified files for Flash Player 6.) If you used any LocalConnection.allowDomain() System.security.allowDomain()
  • Page 19 You have to make the following changes: • If the called SWF file is published for Flash Player 7, include System.security.allowDomain in the called SWF file, using exact domain- LocalConnection.allowDomain name matching. • If the called SWF file is published for Flash Player 6, modify the called file to add or change a statement, using exact System.security.allowDomain LocalConnection.allowDomain...
  • Page 20 XML.load() XML.sendAndLoad() LoadVars.load() LoadVars.sendAndLoad() loadVariables() loadVariablesNum(), , and Macromedia Flash Remoting MovieClip.loadVariables() XMLSocket.connect() ). Also, a SWF file can import runtime shared NetServices.createGatewayConnection libraries (RSLs), or assets defined in another SWF file, at runtime. By default, the data or RSL must reside in the same domain as the SWF file that is loading that external data or media.
  • Page 21: Actionscript Editor Changes

    If you are loading external data, you should create policy files even if you don’t plan to port any of your files to Flash Player 7. If you are using RSLs, you should create policy files if either the calling or called file is published for Flash Player 7. For more information, see “About allowing cross-domain data loading”...
  • Page 22: Debugging Changes

    Debugging changes This section describes changes that improve your ability to debug your scripts. Output window changed to Output panel You can now move and dock the Output panel in the same way as any other panel in Flash. Improved error reporting at compile time In addition to providing more robust exception handling, ActionScript 2.0 provides a number of new compile-time errors.
  • Page 23 Key facts about ActionScript 2.0 include the following points: • Scripts that use ActionScript 2.0 to define classes or interfaces must be stored as external script files, with a single class defined in each script; that is, classes and interfaces cannot be defined in the Actions panel.
  • Page 24 Chapter 1: What’s New in Flash MX 2004 ActionScript...
  • Page 25: Chapter 2: Actionscript Basics

    CHAPTER 2 ActionScript Basics ActionScript has rules of grammar and punctuation that determine which characters and words are used to create meaning and in which order they can be written. For example, in English, a period ends a sentence. In ActionScript, a semicolon ends a statement. The following general rules apply to all ActionScript.
  • Page 26: Unicode Support For Actionscript

    Unicode support for ActionScript Macromedia Flash MX 2004 and Macromedia Flash MX Professional 2004 support Unicode text encoding for ActionScript. This means that you can include text in different languages in an ActionScript file. For example, you could include text in English, Japanese, and French in the same file.
  • Page 27 Constants are elements that don’t change. For example, the constant always has the Key.TAB same meaning: it indicates the Tab key on a keyboard. Constants are useful for comparing values. Constructors are functions that you use to define the properties and methods of a class. By definition, constructors are functions within a class definition that have the same name as the class.
  • Page 28 Instance names are unique names that let you target movie clip and button instances in scripts. You use the Property inspector to assign instance names to instances on the Stage. For example, a master symbol in the library could be called and the two instances of that symbol in counter the SWF file could have the instance names...
  • Page 29: Syntax

    Target paths are hierarchical addresses of movie clip instance names, variables, and objects in a SWF file. You name a movie clip instance in the movie clip Property inspector. (The main Timeline always has the name .) You can use a target path to direct an action at a movie clip _root or to get or set the value of a variable.
  • Page 30 In addition, case sensitivity is implemented for external scripts, such as ActionScript 2.0 class files or scripts that you import using the command. If you are publishing files for Flash #include Player 7 and have previously created external files that you add to your scripts by using the statement, you should review each file and confirm that you used consistent #include capitalization throughout.
  • Page 31 Curly braces ActionScript event handlers, class definitions, and functions are grouped together into blocks with curly braces ( ). You can put the opening brace on the same line as your declaration or on the next line, as shown in the following examples. To make your code easier to read, it’s a good idea to choose one format and use it consistently.
  • Page 32 Parentheses When you define a function, place any parameters inside parentheses: function myFunction (name, age, reader){ // your code here When you call a function, include any parameters passed to the function in parentheses, as shown here: myFunction ("Steve", 10, true); You can also use parentheses to override the ActionScript order of precedence or to make your ActionScript statements easier to read.
  • Page 33 To create a comment block, place at the beginning of the commented lines and at the end. For example, when the following script runs, none of the code in the comment block is executed: // The code below runs var x:Number = 15; var y:Number = 20;...
  • Page 34: About Data Types

    About data types A data type describes the kind of information a variable or ActionScript element can hold. There are two kinds of data types built into Flash: primitive and reference. The primitive data types— String, Number, and Boolean—have a constant value and therefore can hold the actual value of the element they represent.
  • Page 35 To include a quotation mark in a string, precede it with a backslash character (\). This is called escaping a character. There are other characters that cannot be represented in ActionScript except by special escape sequences. The following table provides all the ActionScript escape characters: Escape sequence Character Backspace character (ASCII 8)
  • Page 36 MovieClip class. You call the methods using the dot ( operator, as shown here: my_mc.startDrag(true); parent_mc.getURL("http://www.macromedia.com/support/" + product); Null The null data type has only one value, . This value means “no value”—that is, a lack of data.
  • Page 37: Assigning Data Types To Elements

    Determining an item’s data type While testing and debugging your programs, you may discover problems that seem to be related to the data types of different items. In these cases, you may want to determine an item’s data type. To do so, use the operator, as shown in this example: typeof trace(typeof(variableName));...
  • Page 38 Strict data typing ActionScript 2.0 lets you explicitly declare the object type of a variable when you create it; this is called strict data typing. Because data type mismatches trigger compiler errors, strict data typing helps prevent you from assigning the wrong type of data to an existing variable. To assign a specific data type to an item, specify its type using the keyword and post-colon syntax: // strict typing of variable or object...
  • Page 39 The reason for this is that when you publish a file for ActionScript 1, Flash interprets a statement such as as slash syntax rather than as strict typing. (ActionScript 2.0 var x:String = "abc" doesn’t support slash syntax.) This behavior can result in an object that is assigned to a variable of the wrong type, causing the compiler to let illegal method calls and undefined property references pass through unreported.
  • Page 40: About Variables

    The following example shows the results of casting built-in object types. As the first line in the block shows, an illegal cast—in this case, casting a string to a movie clip— with(results) returns . As the last two lines show, casting to null or undefined returns null undefined var mc:MovieClip;...
  • Page 41 To test the value of a variable, use the action to send the value to the Output panel. For trace() example, sends the value of the variable to the Output panel trace(hoursWorked) hoursWorked in test mode. You can also check and set the variable values in the Debugger in test mode. For more information, see “Using the trace statement”...
  • Page 42 Local variables To declare local variables, use the statement inside the body of a function. A local variable is scoped to the block and expires at the end of the block. A local variable not declared within a block expires at the end of its script. For example, the variables are often used as loop counters.
  • Page 43 = "http://www.macromedia.com"; var myWebSite = "http://www.macromedia.com"; getURL(myWebSite); // browser displays www.macromedia.com You can change the value of a variable many times in a script. The type of data that the variable contains affects how and when the variable changes. Primitive data types, such as strings and numbers, are passed by value.
  • Page 44 As another example, the variable contains a primitive value, 3, so the actual value is inValue passed to the function and the returned value is 9: sqrt() function sqrt(x){ return x * x; var inValue = 3; var out = sqrt(inValue); The value of the variable does not change.
  • Page 45: Using Operators To Manipulate Values In Expressions

    Using operators to manipulate values in expressions An expression is any statement that Flash can evaluate and that returns a value. You can create an expression by combining operators and values or by calling a function. Operators are characters that specify how to combine, compare, or modify the values of an expression.
  • Page 46 The following table lists the ActionScript numeric operators: Operator Operation performed Addition Multiplication Division Modulo (remainder of division) Subtraction Increment Decrement Comparison operators Comparison operators compare the values of expressions and return a Boolean value ( true ). These operators are most commonly used in loops and in conditional statements. In the false following example, if the variable , a certain SWF file loads;...
  • Page 47 Logical operators Logical operators compare Boolean values ( ) and return a third Boolean value. true false For example, if both operands evaluate to , the logical AND operator ( ) returns . If true && true one or both of the operands evaluate to , the logical OR operator ( ) returns .
  • Page 48 The strict equality ( ) operator is like the equality operator, with one important difference: the strict equality operator does not perform type conversion. If the two operands are of different types, the strict equality operator returns . The strict inequality ( ) operator returns the false inversion of the strict equality operator.
  • Page 49 Operator Operation performed Modulo and assignment Division and assignment Bitwise shift left and assignment <<= >>= Bitwise shift right and assignment >>>= Shift right zero fill and assignment Bitwise XOR and assignment Bitwise OR and assignment &= Bitwise AND and assignment Dot and array access operators You can use the dot operator ( ) and the array access operator (...
  • Page 50: Specifying An Object's Path

    You create multidimensional arrays in ActionScript by constructing an array, the elements of which are also arrays. To access elements of a multidimensional array, you can nest the array access operator with itself, as shown in the following example: var chessboard = new Array(); for (var i=0;...
  • Page 51: Using Built-In Functions

    Using built-in functions A function is a block of ActionScript code that can be reused anywhere in a SWF file. If you pass values as parameters to a function, the function will operate on those values. A function can also return values.
  • Page 52 You can also define a function by creating a function literal—an unnamed function that is declared in an expression instead of in a statement. You can use a function literal to define a function, return its value, and assign it to a variable in one expression, as shown in the following example: area = (function() {return Math.PI * radius *radius;})(5);...
  • Page 53 Returning values from a function Use the statement to return values from functions. The statement stops the return return function and replaces it with the value of the action. The following rules govern the use of return statement in functions: return •...
  • Page 54 Chapter 2: ActionScript Basics...
  • Page 55: Chapter 3: Writing And Debugging Scripts

    CHAPTER 3 Writing and Debugging Scripts In Macromedia Flash MX 2004 and Macromedia Flash MX Professional 2004, you can write scripts that are embedded in your FLA file or stored externally on your computer. (If you are writing ActionScript 2.0 class files, you must store each class as an external file that has the same name as the class.) To write embedded scripts, use the Actions panel and attach the action to a...
  • Page 56: Controlling When Actionscript Runs

    Controlling when ActionScript runs When you write a script, you use the Actions panel to attach the script to a frame on a Timeline, or to a button or movie clip on the Stage. Scripts attached to a frame run, or execute, when the playhead enters that frame.
  • Page 57 You can use the statement to create the same kind of loop as a loop. In a do..while while loop, the expression is evaluated at the bottom of the code block so the loop always do..while runs at least once, as shown in the following example: i = 4;...
  • Page 58: Using The Actions Panel And Script Window

    Using the Actions panel and Script window You can embed Flash scripts in your FLA file or store them as external files. It’s a good idea to store as much of your ActionScript code in external files as possible. This makes it easier to reuse code in multiple FLA files.
  • Page 59 In the Actions panel, the Actions toolbox also contains a Script navigator, which is a visual representation of the locations in the FLA file that have associated ActionScript; you can navigate through your FLA file here to locate ActionScript code. If you click an item in the Script navigator, the script associated with that item appears in the Script pane, and the playhead moves to that position on the Timeline.
  • Page 60 Managing scripts in a FLA file If you don’t centralize all your code within a FLA file in one location, you can pin (lock in place) multiple scripts in the Actions panel to make it easier to move among them. In the following figure, the script associated with the current location on the Timeline is on Frame 1 of the layer named Cleanup.
  • Page 61: Using The Actionscript Editor

    Action Windows shortcut key Macintosh shortcut key Move focus to tab on the left Control-Shift-, (comma) Command-Shift-, Unpin all scripts Control-Shift-- (minus) Command-Shift-- Using the ActionScript editor Flash MX 2004 and Flash MX Professional 2004 provide several tools to help you write syntactically correct code and lets you set preferences for code formatting and other options.
  • Page 62 Strictly typing objects to trigger code hints When you use ActionScript 2.0, you can strictly type a variable that is based on a built-in class, such as Button, Array, and so on. If you do so, the ActionScript editor displays code hints for the variable.
  • Page 63 Array methods and properties; and so on. // Object theObject; // Array theArray; // MovieClip mc; However, Macromedia recommends using strict data typing (see “Strictly typing objects to trigger code hints” on page 62) or suffixes (see “Using suffixes to trigger code hints”...
  • Page 64 To specify settings for automatic code hints, do one of the following: • Select Edit > Preferences, and then enable or disable Code Hints on the ActionScript tab. • In the Actions panel, select Preferences from the Options pop-up menu (at the upper right of the panel) and enable or disable Code Hints on the ActionScript tab.
  • Page 65 To work with menu-style code hints: Display the code hint by typing a period after the variable or object name. The code hint menu appears. Note: If a code hint doesn’t appear, make sure you haven’t disabled code hints on the ActionScript tab.
  • Page 66 Similarly, if you type Escape+c+h, the following code is placed in your script, and the insertion point is placed between the parentheses, so you can begin typing your condition: catch () { If you want to learn (or be reminded) which commands have Escape shortcut keys, you can display them next to elements in the Actions panel.
  • Page 67 To check for punctuation balance: Click between braces ( , array access operators ( , or parentheses ( ) in your script. Press Control+' (Windows) or Command+' (Macintosh) to highlight the text between braces, brackets, or parentheses. The highlighting helps you check whether opening punctuation has correct corresponding closing punctuation.
  • Page 68: Debugging Your Scripts

    Debugging your scripts Flash provides several tools for testing ActionScript in your SWF files. The Debugger, discussed in the rest of this section, lets you find errors in a SWF file while it’s running in Flash Player. Flash also provides the following additional debugging tools: •...
  • Page 69 To activate the Debugger in test mode: • Select Control > Debug Movie. This opens the Debugger. It also opens the SWF file in test mode. Status bar Watch list Display list Code view Debugging a SWF file from a remote location You can debug a remote SWF file using the stand-alone, ActiveX, or plug-in versions of Flash Player.
  • Page 70 To enable remote debugging of a Flash movie: Select File > Publish Settings. On the Flash tab of the Publish Settings dialog box, select Debugging permitted. To set a password, enter a password in the Password box. After you set this password, no one can download information to the Debugger without the password.
  • Page 71 To activate the Debugger from a remote location: Open the Flash authoring application. In a browser or in the stand-alone player, open the published SWF file from the remote location. The Remote Debug dialog box appears. If that dialog box doesn’t appear, Flash can’t find the SWD file. In this case, right-click (Windows) or Control-click (Macintosh) in the SWF file to display the context menu, and select Debugger.
  • Page 72 , or "Hello" 3523 "http:// , and you cannot use . The value can be a www.macromedia.com" x + 2 eval("name:" +i) string (any value surrounded by quotation marks), a number, or a Boolean value ( true false Note: To write the value of an expression to the Output panel in test mode, use the statement.
  • Page 73 Using the Watch list To monitor a set of critical variables in a manageable way, you can mark variables to appear in the Watch list. The Watch list displays the absolute path to the variable and the value. You can also enter a new variable value in the Watch list the same way as in the Variables tab.
  • Page 74 Displaying movie clip properties and changing editable properties The Debugger’s Properties tab displays all the property values of any movie clip on the Stage. You can change a value and see its effect in the SWF file while it runs. Some movie clip properties are read-only and cannot be changed.
  • Page 75 You can set breakpoints in the Actions panel or in the Debugger. (To set breakpoints in external scripts, you must use the Debugger.) Breakpoints set in the Actions panel are saved with the Flash document (FLA file). Breakpoints set in the Debugger are not saved in the FLA file and are valid only for the current debugging session.
  • Page 76 As you step through lines of code, the values of variables and properties change in the Watch list and in the Variables, Locals, and Properties tabs. A yellow arrow along the left side of the Debugger’s code view indicates the line at which the Debugger stopped. Use the following buttons along the top of the code view: Continue Stop Debugging...
  • Page 77: Using The Output Panel

    Using the Output panel In test mode, the Output panel displays information to help you troubleshoot your SWF file. Some information, such as syntax errors, is displayed automatically. You can display other information by using the List Objects and List Variables commands. (See “Listing a SWF file’s objects”...
  • Page 78 Listing a SWF file’s variables In test mode, the List Variables command displays a list of all the variables currently in the SWF file. This is especially useful for finding the correct variable target path and variable name. Unlike the Debugger, the list does not update automatically as the SWF file plays; you must select the List Variables command each time you want to send the information to the Output panel.
  • Page 79: Updating Flash Player For Testing

    " + enterFrame++) Updating Flash Player for testing You can download the latest version of Flash Player from the Macromedia Support Center at www.macromedia.com/support/flash and use it to test your SWF files with the most recent version of Flash Player.
  • Page 80 Chapter 3: Writing and Debugging Scripts...
  • Page 81: Part Ii: Handling Events And Creating Interaction

    XML file loading over the network. The first chapter in this part describes the different types of events in Macromedia Flash and discusses how to handle them in ActionScript. The second chapter shows how to apply these principles to create simple interactive presentations, applications, and animations.
  • Page 83: Chapter 4 Handling Events

    CHAPTER 4 Handling Events An event is a software or hardware occurrence that requires a response from a Macromedia Flash application. For example, an event such as a mouse click or a keypress is called a user event, since it occurs as a result of direct user interaction.
  • Page 84 For example, suppose you have a button named on the Stage. The following code next_btn assigns a function to the button’s event handler; this function advances the playhead to onPress the next frame in the Timeline. next_btn.onPress = function () nextFrame();...
  • Page 85: Using Event Listeners

    Using event listeners Event listeners let an object, called a listener object, receive events generated by another object, called a broadcaster object. The broadcaster object registers the listener object to receive events generated by the broadcaster. For example, you could register a movie clip object to receive notifications from the Stage, or a button instance could receive onResize onChanged...
  • Page 86 To create a simple focus manager with event listeners: Using the Text tool, create a text field on the Stage. Select the text field and, in the Property inspector, select Input from the Text Type pop-up menu, and select the Show Border Around Text option. Create another input text field below the first one.
  • Page 87: Using Button And Movie Clip Event Handlers

    Using button and movie clip event handlers You can attach event handlers directly to a button or movie clip instance by using the handlers. The handler handles movie clip events, and onClipEvent() on() onClipEvent() handler handles button events. You can also use with movie clips to create movie on() on()
  • Page 88: Creating Movie Clips With Button States

    Creating movie clips with button states When you attach an handler to a movie clip, or assign a function to one of the MovieClip on() mouse event handlers for a movie clip instance, the movie clip responds to mouse events in the same way as a button does.
  • Page 89 For instance, the following event handler will produce different results depending on on() whether it’s attached to a movie clip or button object. In the first case, the function call play() starts the playback head of the Timeline that contains the button; in the second case, the play() function call starts the Timeline of the movie clip to which the handler is attached.
  • Page 90: Scope Of The "This" Keyword

    Scope of the “this” keyword keyword refers to the object in the currently executing scope. Depending on what type this of event handler technique you’re using, can refer to different objects. this Within an event handler or event listener function refers to the object that defines the this event handler or event listener method.
  • Page 91: Chapter 5: Creating Interaction With Actionscript

    CHAPTER 5 Creating Interaction with ActionScript In simple animation, Macromedia Flash Player plays the scenes and frames of a SWF file sequentially. In an interactive SWF file, your audience uses the keyboard and mouse to jump to different parts of a SWF file, move objects, enter information in forms, and perform many other interactive operations.
  • Page 92: Controlling Swf File Playback

    Controlling SWF file playback The following ActionScript functions let you control the playhead in the Timeline and load a new web page into a browser window: • functions send the playhead to a frame or scene. gotoAndPlay() gotoAndStop() These are global functions that you can call from any script. You can also use the methods to navigate the MovieClip.gotoAndPlay() MovieClip.gotoAndStop()
  • Page 93 HTML anchor ( ) tag. <a></a> For example, the following code opens the macromedia.com home page in a blank browser window when the user clicks the button instance named homepage_btn homepage_btn.onRelease = function () {...
  • Page 94: Creating Interactivity And Visual Effects

    Creating interactivity and visual effects To create interactivity and other visual effects, you need to understand the following techniques: • Creating a custom mouse pointer • Getting the mouse position • Capturing keypresses • Setting color values • Creating sound controls •...
  • Page 95 Buttons still function when you use a custom pointer. It’s a good idea to put the custom pointer on the top layer of the Timeline so that it moves in front of buttons and other objects as you move the mouse in the SWF file. Also, the tip of a custom mouse pointer is the registration point of the movie clip you’re using as the custom pointer.
  • Page 96 To get the current mouse position within a movie clip: Create a movie clip. Select the movie clip instance on the Stage. Using the Property inspector, name it myMovieClip Select Window > Development Panels > Actions to open the Actions panel if it is not already visible.
  • Page 97 • Assign the following handler to a movie clip, then select Control > Test Movie onClipEvent() and press the desired key. onClipEvent(keyDown) { trace(Key.getCode()); The key code of the desired key appears in the Output panel. A common place to use Key class methods is within an event handler. In the following example, the user moves the car using the arrow keys.
  • Page 98 To create a keyboard-activated movie clip: On the Stage, create a movie clip that will move in response to keyboard arrow activity. In this example, the movie clip instance name is On the Stage, create a dynamic text box that will be updated with the direction of the car. Using the Property inspector, give it an instance name of display_txt Note: Don’t confuse variable names with instance names.
  • Page 99 Use similar code to check if the Left Arrow, Up Arrow, or Down Arrow key is being pressed. Your code should look like this: var distance = 10; car.onEnterFrame = function() { with (car) { if (Key.isDown(Key.RIGHT)) { _x += distance; if (_x >= 400) { _x = 400;...
  • Page 100 Setting color values You can use the methods of the built-in Color class to adjust the color of a movie clip. The method assigns hexadecimal RGB (red, green, blue) values to the movie clip. The setRGB() following example uses to change an object’s color based on user input. setRGB() The button action creates a Color object and changes the color of the car based on user input.
  • Page 101 Repeat step 6 for the other buttons (red, green, and black) to change the color of the movie clip to the corresponding color. Your code should now look like this: myColor = new Color(_root.carColor) _root.blue.onRelease = function(){ myColor.setRGB(0x0000ff) _root.red.onRelease = function(){ myColor.setRGB(0xff0000) _root.green.onRelease = function(){ myColor.setRGB(0x00ff00)
  • Page 102 The Sound class’s method controls the volume, and the method adjusts setVolume() setPan() the left and right balance of a sound. When the user drags the volume slider, the setVolume() method is called. The following procedures show how to create sound controls like the ones shown above. To attach a sound to a Timeline: Select File >...
  • Page 103 Select Frame 1 in the main Timeline, and select Window > Development Panels > Actions. Add the following code to the Actions panel: speaker.stop(); song = new Sound(); song.onSoundComplete = function() { speaker.stop(); song.attachSound("a_thousand_ways"); playButton.onRelease = function() { song.start(); speaker.play(); stopButton.onRelease = function () { song.stop();...
  • Page 104 Enter the following actions: onClipEvent (load) { top = _y; bottom = _y; left = _x; right = _x+100; _x += 100; onClipEvent (enterFrame) { _parent.song.setVolume(_x-left); Select Control > Test Movie to use the volume slider. To create a sliding balance control: Drag a button to the Stage.
  • Page 105 Detecting collisions method of the MovieClip class detects collisions in a SWF file. It checks to see if hitTest() an object has collided with a movie clip and returns a Boolean value ( true false There are two cases in which you would want to know whether a collision has occurred: to test if the user has arrived at a certain static area on the Stage, and to determine when one movie clip has reached another.
  • Page 106 The following procedures show how to detect collision using the car example. To perform collision detection between a movie clip and a point on the Stage: Create a new movie clip on the Stage, and enter as the instance name in the Property inspector.
  • Page 107 Creating a simple line drawing tool You can use methods of the MovieClip class to draw lines and fills on the Stage as the SWF file plays. This allows you to create drawing tools for users and to draw shapes in the SWF file in response to events.
  • Page 108: Deconstructing A Sample Script

    Deconstructing a sample script In the sample SWF file zapper.swf (which you can view in Using Flash Help), when a user drags the bug to the electrical outlet, the bug falls and the outlet shakes. The main Timeline has only one frame and contains three objects: the ladybug, the outlet, and a reset button.
  • Page 109 There are two handlers with two different events: . The onClipEvent() load enterFrame actions in the statement execute only once, when the SWF file loads. The onClipEvent(load) actions in the statement execute every time the playhead enters a onClipEvent(enterFrame) frame. Even in a one-frame SWF file, the playhead still enters that frame repeatedly and the script executes repeatedly.
  • Page 110 Chapter 5: Creating Interaction with ActionScript...
  • Page 111 PART III Working with Objects and Classes This part discusses the Macromedia Flash runtime object model and its capabilities, focusing on working with movie clips and text. This part also describes how to create your own classes and interfaces with ActionScript 2.0.
  • Page 113: Chapter 6: Using The Built-In Classes

    “Core classes” on page 115.) The rest of the built-in ActionScript classes are specific to Macromedia Flash and Flash Player object model. To understand the distinction between core ActionScript classes and those specific to Flash, consider the distinction between core and client-side JavaScript: just as client-side...
  • Page 114: About Classes And Instances

    About classes and instances In object-oriented programming, a class defines a category of object. A class describes the properties (data) and behavior (methods) for an object, much like an architectural blueprint describes the characteristics of a building. To use the properties and methods defined by a class, you must first create an instance of that class.
  • Page 115: Overview Of Built-In Classes

    Overview of built-in classes This section lists all the ActionScript classes, including a brief description of each class and cross- references to other relevant sections of the documentation. Core classes The core ActionScript classes are those borrowed directly from ECMAScript. In the Actions toolbox, these classes are located in the Built-in Classes >...
  • Page 116 Classes specific to Flash Player The following tables list the classes that are specific to Flash Player and the Flash runtime model. These classes are typically split into four categories: movie classes (which provide overall control of SWF files and Flash Player), media classes (for working with sound and video), client-server classes (for working with XML and other external data sources), and authoring classes (which provide control over the Flash authoring environment).
  • Page 117 Class Description LocalConnection The LocalConnection class lets two SWF files running on the same computer communicate. See the LocalConnection class entry in Chapter 12, “ActionScript Dictionary,” on page 205. Mouse The Mouse class provides control over the mouse in a SWF file; for example, this class lets you hide or show the mouse pointer.
  • Page 118 Media classes The media classes provide playback control of sound and video in a SWF file, as well as access to the user’s microphone and camera, if they are installed. These classes are located in the Built-In Classes > Media subfolder in the Actions toolbox. Class Description Camera...
  • Page 119 These classes are located in the Built-In Classes > Client/Server subfolder in the Actions panel. Class Description LoadVars The LoadVars class is an alternative to the action for loadVariables() transferring variables between a SWF file and a server in name-value pairs. “Using the LoadVars class”...
  • Page 120 Chapter 6: Using the Built-In Classes...
  • Page 121: Chapter 7: Working With Movie Clips

    In this way, movie clips provide the foundation of component-based architecture in Macromedia Flash MX 2004 and Macromedia Flash MX Professional 2004. In fact, the components available in the Components panel (Window >...
  • Page 122: Calling Multiple Methods On A Single Movie Clip

    To use a method, invoke it by using the target path of the instance name, a dot, and then the method name and parameters, as in the following statements: myMovieClip.play(); parentClip.childClip.gotoAndPlay(3); In the first statement, moves the playhead in the instance.
  • Page 123: Loading And Unloading Additional Swf Files

    The above code is also equivalent to the following: with (donut){ hole._alpha = 20; hole._xscale = 150; hole._yscale = 150; Loading and unloading additional SWF files To play additional SWF files without closing Flash Player, or to switch SWF files without loading another HTML page, you can use the global function or method of...
  • Page 124: Loading Jpeg Files Into Movie Clips

    When contents.swf loads into the movie clip in container.swf, the value of that’s userName attached to the root Timeline of the hosting SWF file (container.swf ) would be set to "Mary" This could cause code in container.swf (as well as contents.swf ) to malfunction. To force to always evaluate to the Timeline of the loaded SWF file, rather than the actual _root...
  • Page 125: Changing Movie Clip Position And Appearance

    Changing movie clip position and appearance To change the properties of a movie clip as it plays, write a statement that assigns a value to a property or use the function. For example, the following code sets the rotation of setProperty() instance to 45:...
  • Page 126: Creating Movie Clips At Runtime

    Creating movie clips at runtime Not only can you create movie clip instances in the Flash authoring environment, but you can also create them at runtime. ActionScript provides three ways to create new movie clips at runtime: • By creating a new, empty movie clip instance •...
  • Page 127 Attaching a movie clip symbol to the Stage The last way to create movie clip instances at runtime is to use . The attachMovie() method attaches an instance of a movie clip symbol in the SWF file’s library to attachMovie() the Stage.
  • Page 128: Adding Parameters To Dynamically Created Movie Clips

    To attach a movie clip to another movie clip: Assign a linkage identifier to a movie clip library symbol, as described above. With the Actions panel open (Window > Development Panels > Actions), select a frame in the Timeline. In the Actions panel’s Script pane, type the name of the movie clip or level to which you want to attach the new movie clip.
  • Page 129: Managing Movie Clip Depths

    To populate a movie clip with parameters by using attachMovie() In a new Flash document, create a movie clip symbol by selecting Insert > New Symbol. Type in the Symbol Name text box and select the Movie Clip behavior. dynamic Inside the symbol, create a dynamic text field on the Stage with an instance name of name_txt Select the first frame of the movie clip’s Timeline and open the Actions panel (Window >...
  • Page 130 Determining the next highest available depth To determine the next highest available depth within a movie clip, use . The integer value returned by this method indicates the MovieClip.getNextHighestDepth() next available depth that will render in front of all other objects in the movie clip. The following code creates a new movie clip, with a depth value of 10, on the Timeline of the movie clip named .
  • Page 131: Drawing Shapes With Actionscript

    Drawing shapes with ActionScript You can use methods of the MovieClip class to draw lines and fills on the Stage. This allows you to create drawing tools for users and to draw shapes in the movie in response to events. The drawing methods are beginFill() beginGradientFill()
  • Page 132: Using Movie Clips As Masks

    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. The mask movie clip plays all the frames in its Timeline, just like a regular movie clip.
  • Page 133: Assigning A Class To A Movie Clip Symbol

    Assigning a class to a movie clip symbol Using ActionScript 2.0, you can create your own class that extends the behavior of the built-in MovieClip class, and then assign that class to a movie clip library symbol using the Linkage Properties dialog box.
  • Page 134: Initializing Class Properties

    Initializing class properties In the example presented earlier, you added the instance of the Ball symbol to the Stage manually—that is, while authoring. As discussed previously (see “Adding parameters to dynamically created movie clips” on page 128), you can assign parameters to clips you create at runtime using the parameter of .
  • Page 135: Chapter 8: Working With Text

    CHAPTER 8 Working with Text A dynamic or input text field is a TextField object (an instance of the TextField class). When you create a text field, you can assign it an instance name in the Property inspector. You can use the instance name in ActionScript statements to set, change, and format the text field and its content using the TextField and TextFormat classes.
  • Page 136 To control a dynamic or input text field using ActionScript, you must assign it an instance name in the Property inspector. 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.
  • Page 137: Creating Text Fields At Runtime

    Creating text fields at runtime You can use the method of the MovieClip class to create an empty text field createTextField() on the Stage at runtime. The new text field is attached to the Timeline of the movie clip that calls the method.
  • Page 138 To format a text field with the TextFormat class: In a new Flash document, create a text field on the Stage using the Text tool. Type some text in the text field on the Stage, like “Bold, italic, 24 point text”. In the Property inspector, type in the Instance Name text box, select Dynamic myText_txt...
  • Page 139: Formatting Text With Cascading Style Sheets

    Getting text metric information You can use the method to obtain detailed text measurements TextFormat.getTextExtent() for a text string with specific formatting applied. For example, suppose you need to create, at runtime, a new TextField object containing an arbitrary amount of text that is formatted with a 24-point, bold, Arial font, and a 5-pixel indent.
  • Page 140 Supported CSS properties Flash Player supports a subset of properties in the original CSS1 specification (www.w3.org/TR/ REC-CSS1). The following table shows the supported CSS properties and values, and their corresponding ActionScript property names. (Each ActionScript property name is derived from the corresponding CSS property name;...
  • Page 141 Loading external CSS files You can define styles in an external CSS file and then load that file into a style sheet object. The styles defined in the CSS file are added to the style sheet object. To load an external CSS file, you use the method of the TextField.StyleSheet class.
  • Page 142 Creating new styles with ActionScript You can create new text styles with ActionScript by using the method of the setStyle() TextField.StyleSheet class. This method takes two parameters: the name of the style and an object that defines that style’s properties. For example, the following code creates a style sheet object named that defines two styles styles...
  • Page 143 Using style classes You can create style “classes” that you can apply to a tag using either tag’s <p> <span> class attribute. When applied to a tag, the style affects the entire paragraph. You can also style a <p> span of text that uses a style class by using the tag.
  • Page 144 An example of using styles with HTML This section presents an example of using styles with HTML tags. You’ll create a style sheet that styles some built-in tags and defines some style classes. You’ll then apply that style sheet to a TextField object that contains HTML-formatted text.
  • Page 145 = "<p class='headline'>Flash Player now supports Cascading Style Sheets!</p><p><span class='byline'>San Francisco, CA</ span>--Macromedia Inc. announced today a new version of Flash Player that supports Cascading Style Sheet (CSS) text styles. For more information, visit the <a href='http://www.macromedia.com'>Macromedia Flash web site.</ a></p>";...
  • Page 146 You could then populate a text field associated with that style sheet with the following XML- formatted text: <sectionHeading>This is a section</sectionHeading> <mainBody>This is some main body text, with one <emphasized>emphatic</emphasized> word. </mainBody> An example of using styles with XML In this section, you’ll create the same FLA file that you created earlier (see “An example of using styles with HTML”...
  • Page 147: Using Html-Formatted Text

    To create the XML text to assign to the text field, add the following code to the Actions panel: var storyText = "<title>Flash Player now supports CSS</ title><mainBody><byline>San Francisco, CA</byline>--Macromedia Inc. announced today a new version of Flash Player that supports Cascading Style Sheets (CSS) text styles.
  • Page 148 Specifies the name of the target window to load the page into. target For example, the following HTML snippet creates the link “Go home,” which opens www.macromedia.com in a new browser window. <a href="../home.htm" target="_blank">Go home</a> You can also define , and styles for anchor tags by using style sheets.
  • Page 149 Image tag (<img>) tag lets you embed external JPEG files, SWF files, and movie clips inside text fields. <img> Text automatically flows around images you embed in text fields. This tag is supported only in dynamic and input text fields that are multiline and wrap their text. To create a multiline text field with word wrapping, do one of the following: •...
  • Page 150 List item tag (<li>) tag places a bullet in front of the text that it encloses. <li> Grocery list: <li>Apples</li> <li>Oranges</li> <li>Lemons</li> The above code would render as follows: Grocery list: Apples Oranges Lemons Paragraph tag (<p>) tag creates a new paragraph. It supports the following attributes: <p>...
  • Page 151 • Specifies the amount of leading (vertical space) between lines; corresponds to leading . (See on page 722.) TextFormat.leading TextFormat.leading • Specifies the left margin of the paragraph, in points; corresponds to leftmargin . (See on page 723.) TextFormat.leftMargin TextFormat.leftMargin •...
  • Page 152 Embedding images, SWF files, and movie clips in text fields In Flash Player 7 and later, you can use the tag to embed JPEG files, SWF files, and movie <img> clips inside dynamic and input text fields. (For a full list of attributes for the tag, see <img>...
  • Page 153: Creating Scrolling Text

    For example, the following code embeds a SWF file named animation.swf in the text field named on level 0 and assigns the instance name to the movie clip that textField_txt animation_mc contains the SWF file. _level0.textField_txt.htmlText = "Here’s an interesting animation: <img src='animation.swf' id='animation_mc'>...
  • Page 154 To use the scroll property to create scrolling text: Do one of the following: Use the Text tool to drag a text field on the Stage. Assign the text field the instance name in the Property inspector. textField Use ActionScript to create a text field dynamically with the method.
  • Page 155: Chapter 9: Creating Classes With Actionscript 2.0

    Java. The OOP model provided by 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.
  • Page 156: Principles Of Object-Oriented Programming

    This section provides a brief introduction to principles involved in developing object-oriented programs. These principles are described in more depth in the rest of this chapter, along with details on how they are implemented in Macromedia Flash MX 2004 and Macromedia Flash MX Professional 2004.
  • Page 157: Using Classes: A Simple Example

    Interfaces Interfaces in object-oriented programming can be described as classes whose methods are not implemented (defined). Another class can implement the methods declared by the interface. An interface can also be thought of as a “programming contract” that can be used to enforce relationships between otherwise unrelated classes.
  • Page 158 To create the class file: Create a new directory on your hard disk and name it PersonFiles. This directory will contain all the files for this project. Do one of the following: Create a new file in your preferred text or code editor. (Flash Professional only) Select File >...
  • Page 159 Next you’ll create the method, which returns a preformatted string containing the showInfo() values of the properties. Add the function definition to the class name showInfo() body, as shown below. class Person { var age:Number; var name:String; // Method to return property values function showInfo():String { return("Hello, my name is "...
  • Page 160 Creating an instance of the Person class The next step is to create an instance of the Person class in another script, such as a frame script in a Flash (FLA) document or another AS script, and assign it to a variable. To create an instance of a custom class, you use the operator, just as you would when creating an instance of a built-in ActionScript class (such as the XML or TextField class).
  • Page 161: Creating And Using Classes

    Creating and using classes As discussed previously, a class consists of two parts: the declaration and the body. The class declaration consists minimally of the statement, followed by an identifier for the class class name, then left and right curly braces. Everything inside the braces is the class body. class className { // class body You can define classes only in ActionScript (AS) files.
  • Page 162 Similarly, any function declared within a class is considered a method of the class. In the Person class example, you created a single method called showInfo() class Person { var age:Number; var name:String; function showInfo() { // showInfo() method definition Initializing properties inline You can initialize properties inline—that is, when you declare them—with default values, as shown here:...
  • Page 163 The class you specify in inherits all the properties and methods defined by the SubClass superclass. For example, you might create a Mammal class that defines properties and methods common to all mammals. To create a variation of the Mammal class, such as a Marsupial class, you would extend the Mammal class—that is, create a subclass of the Mammal class.
  • Page 164 If no constructor function is explicitly declared—that is, if you don’t create a function whose name matches that of the class—the compiler automatically creates an empty constructor function for you. A class can contain only one constructor function; overloaded constructor functions are not allowed in ActionScript 2.0.
  • Page 165: Instance And Class Members

    Instance and class members In object-oriented programming, members (properties or methods) of a class can be either instance members or class members. Instance members are created for, and copied into, each instance of the class; in contrast, class members are created just once per class. (Class members are also known as static members.) To invoke an instance method or access an instance property, you reference an instance of the class.
  • Page 166 Using class members: a simple example One use of class (static) members is to maintain state information about a class and its instances. For example, suppose you want to keep track of the number of instances that have been created from a particular class.
  • Page 167: Creating And Using Interfaces

    Class members and subclasses Class members propagate to subclasses of the superclass that defines those members. In the previous example (see “Using class members: a simple example” on page 166), you used a class property to keep track of the number of instances of that class you created. You could create a subclass of the Widget class, as shown below.
  • Page 168 For example, the following code declares an interface named MyInterface that contains two methods, . The first method takes no parameters and has no return method_1() method_2() type (specified as ). The second method declaration takes a single parameter of type String, Void and specifies a return type of Boolean.
  • Page 169: Understanding The Classpath

    Flash. The location of this directory is shown here: • Windows 2000 or Windows XP: C:\Documents and Settings\<user>\Local Settings\ Application Data\Macromedia\Flash MX2004\<language>\Configuration\ • Windows 98: C:\Windows\Application Data\Macromedia\Flash MX 2004\ <language>\Configuration\ • Macintosh OS X: Hard Drive/Users/Library/Application Support/Macromedia/ Flash MX 2004/<language>/Configuration/ The document-level classpath is empty by default.
  • Page 170 Modifying the classpath You can modify the global classpath using the Preferences dialog box. To modify the document- level classpath setting, you use the Publish Settings dialog box for the FLA file. You can add absolute directory paths (for example, C:/my_classes) and relative directory paths (for example, ../ my_classes or “.”).
  • Page 171: Using Packages

    Using packages You can organize your ActionScript class files in packages. A package is a directory that contains one or more class files, and that resides in a designated classpath directory. (See “Understanding the classpath” on page 169.) A package can, in turn, contain other packages, called subpackages, each with its own class files.
  • Page 172: Implicit Get/Set Methods

    You can use the fully qualified class name to type your variables, as well: var dataInstance:com.network.Data = new Data(); You can use the statement to import packages into a script, which lets you use a class’s import abbreviated name rather than its fully qualified name. You can also use the wildcard character (*) to import all the classes in a package.
  • Page 173: Creating Dynamic Classes

    As you can see, returns the current value of , and sets the getUserName userName setUserName value of to the string parameter passed to the method. An instance of the class would userName then use the following syntax to get or set the property.
  • Page 174: How Classes Are Compiled And Exported

    In some cases, however, you might want to add and access properties or methods of a class at runtime that aren’t defined in the original class definition. The class modifier lets you do dynamic just that. For example, the following code adds the modifier to the Person class dynamic discussed previously:...
  • Page 175: Part Iv: Working With External Data And Media

    PART IV Working with External Data and Media This part discusses how to incorporate external data and media into your Macromedia Flash applications. Chapter 10: Working with External Data........177...
  • Page 177: Chapter 10: Working With External Data

    SWF file for processing by an application server (such as Macromedia ColdFusion MX or Macromedia JRun) or another type of server-side script, such as PHP or Perl. Flash Player can send and load data over HTTP or HTTPS or from a local text file. You can also create persistent TCP/IP socket connections for applications that require low latency—for example, chat...
  • Page 178 Several ActionScript functions and methods let you pass information into and out of a SWF file. Each function or method uses a protocol to transfer information, and requires information to be formatted in a certain way. • The functions and MovieClip methods that use the HTTP or HTTPS protocol to send information in URL-encoded format are getURL() loadVariables()
  • Page 179 For more information, see “Using the XML class” on page 181 “Using the XMLSocket class” on page 184. Using HTTP to connect to server-side scripts , and loadVariables() loadVariablesNum() getURL() loadMovie() loadMovieNum() functions and the , and MovieClip.loadVariables() MovieClip.loadMovie() methods can all communicate with server-side scripts over HTTP or MovieClip.getURL() HTTPS protocols.
  • Page 180 Using the LoadVars class You can use the LoadVars class instead of to transfer variables between a SWF loadVariables() file and a server. The LoadVars class lets you send all the variables in an object to a specified URL and load all the variables at a specified URL into an object. The response from the server triggers method and sets variables in the target.
  • Page 181 About XML XML (Extensible Markup Language) is becoming the standard for the interchange of structured data in Internet applications. You can integrate data in Flash with servers that use XML technology to build sophisticated applications, such as chat systems or brokerage systems. In XML, as with HTML, you use tags to mark up, or specify, a body of text.
  • Page 182 The server-side script that passes information between Flash and the database reads and writes the data in XML format. You can use ActionScript to convert information collected in the SWF file (for example, a user name and password) to an XML object and then send the data to the server- side script as an XML document.
  • Page 183 The server receives the XML, generates an XML response, and sends it back to the SWF file. If the password is accepted, the server responds with the following: <LOGINREPLY STATUS="OK" SESSION="rnr6f7vkj2oe14m7jkkycilb" /> This XML includes a attribute that contains a unique, randomly generated session ID, SESSION which will be used in all communications between the client and server for the rest of the session.
  • Page 184 Note: This design is only an example, and Macromedia can make no claims about the level of security it provides. If you are implementing a secure password-protected system, make sure you have a good understanding of network security.
  • Page 185: Sending Messages To And From Flash Player

    Sending messages to and from Flash Player To send messages from a SWF file to its host environment (for example, a web browser, a Macromedia Director movie, or the stand-alone Flash Player), you can use the fscommand() function. This function lets you extend your SWF file by using the capabilities of the host. For...
  • Page 186 Using fscommand() Use the function to send a message to whichever program is hosting Flash Player. fscommand() function has two parameters: . To send a message to fscommand() command arguments the stand-alone version of Flash Player, you must use predefined commands and arguments. For example, the following action sets the stand-alone player to scale the SWF file to the full monitor screen size when the button is released: on(release){...
  • Page 187 "Hello, " + name + ", welcome to our website!") Select File > Publish Preview > HTML to test the document. function can send messages to Macromedia Director that are interpreted by fscommand() Lingo as strings, events, or executable Lingo code. If the message is a string or an event, you must...
  • Page 188: Flash Player Security Features

    65.57.83.12 The following table shows examples of incompatible domains: www.macromedia.com data.macromedia.com macromedia.com www.macromedia.com www.macromedia.com macromedia.com 65.57.83.12 www.macromedia.com (even if this domain resolves to 65.57.83.12 ) www.macromedia.com 65.57.83.12 (even if www.macromedia.com resolves to this IP) Chapter 10: Working with External Data...
  • Page 189 // In macromedia.swf, after data.swf has loaded: target_mc.getData(); // This method call will fail However, data.swf may grant access to SWF files served from www.macromedia.com by using the handler or the method, LocalConnection.allowDomain...
  • Page 190 For example, a policy file located at https://www.macromedia.com:8080/crossdomain.xml will apply only to data loading calls made to www.macromedia.com over HTTPS at port 8080. An exception to this rule is the use of an XMLSocket object to connect to a socket server in another domain.
  • Page 191 For example, in Flash Player 6, a SWF file that resides in www.macromedia.com could access data on a server located at data.macromedia.com. That is, Flash Player 6 allowed a SWF file from one domain to load data from a “similar” domain.
  • Page 192 Chapter 10: Working with External Data...
  • Page 193: Chapter 11: Working With External Media

    CHAPTER 11 Working with External Media If you import an image or a sound while you author a document in Macromedia Flash MX 2004 or Macromedia Flash MX Professional 2004, the image and sound are packaged and stored in the SWF file when you publish it.
  • Page 194: Loading External Swf And Jpeg Files

    Flash Video (FLV) is the native video format used by Flash Player. You can play back FLV files over HTTP, or from the local file system. Playing external FLV files provides several advantages over embedding video in a Flash document, such as better performance and memory management, and independent video and Flash frame rates.
  • Page 195: Loading External Mp3 Files

    About loaded SWF files and the root Timeline The ActionScript property specifies or returns a reference to the root Timeline of a SWF _root file. If you load a SWF file into a movie clip in another SWF file, any references to in the _root loaded SWF file resolve to the root Timeline in the host SWF file, not that of the loaded SWF...
  • Page 196: Reading Id3 Tags In Mp3 Files

    For example, suppose you’re creating an online game that uses different sounds depending on what level the user has reached in the game. The following code loads an MP3 file (blastoff.mp3) into a Sound object named , and then plays the sound when it has gameSound completely downloaded: var gameSound = new Sound();...
  • Page 197: Playing Back External Flv Files Dynamically

    You can create FLV files by importing video into the Flash authoring tool and exporting it as an FLV file. (See “Macromedia Flash Video” in Using Flash Help.) If you have Flash Professional, you can use the FLV Export plug-in to export FLV files from supported video-editing applications.
  • Page 198: Preloading External Media

    To play back an external FLV file in a Flash document: With the document open in the Flash authoring tool, in the Library panel (Window > Library) select New Video from the Library options menu to create a video object. Drag a video object from the Library panel onto the Stage.
  • Page 199 Preloading SWF and JPEG files To preload SWF and JPEG files into movie clip instances, you can use the MovieClipLoader class. This class provides an event listener mechanism to give notification about the status of file downloads into movie clips. Using a MovieClipLoader object to preload SWF and JPEG files involves the following steps: Create a new MovieClipLoader object You can use a single MovieClipLoader object to track...
  • Page 200 To display download progress using the ProgressBar component: In a new Flash document, create a movie clip on the Stage and name it target_mc Open the Components panel (Window > Development Panels > Components). Drag a ProgressBar component from the Components panel to the Stage. In the Property inspector, give the ProgressBar component the name and, on the pBar...
  • Page 201 Preloading MP3 and FLV files To preload MP3 and FLV files, you can use the function to create a “polling” setInterval() mechanism that checks the bytes loaded for a Sound or NetStream object at predetermined intervals. To track the download progress of MP3 files, use the Sound.getBytesLoaded() methods;...
  • Page 202 Chapter 11: Working with External Media...
  • Page 203 PART V Reference This part contains the ActionScript Dictionary, which provides syntax and usage information for every element in the ActionScript language. It also contains appendixes that provide reference material you may want to review as you write your scripts. Chapter 12: ActionScript Dictionary .
  • Page 205: Chapter 12: Actionscript Dictionary

    This dictionary describes the syntax and use of ActionScript elements in Macromedia Flash MX 2004 and Macromedia Flash MX Professional 2004. To use examples in a script, copy the example code from this dictionary and paste it in the Script pane or into an external script file.
  • Page 206: Sample Entry For Most Actionscript Elements

    This is not the same as the version of Flash used to author the content. For example, if you use Macromedia Flash MX 2004 or Macromedia Flash MX Professional 2004 to create content for Flash Player 6, you can use only ActionScript elements that are available to Flash Player 6.
  • Page 207: Sample Entry For Classes

    Sample entry for classes The following sample dictionary entry explains the conventions used for built-in ActionScript classes. Classes are listed alphabetically with all other elements in the dictionary. Entry title The entry title provides the name of the class. The class name is followed by general descriptive information.
  • Page 208 Symbolic operators See entry &= &= (bitwise AND assignment) () (parentheses) – – (minus) * (multiplication) *= (multiplication assignment) , (comma) . (dot) : (type) ?: (conditional) / (division) // (comment delimiter) /* (comment delimiter) /= (division assignment) [] (array access) ^ (bitwise XOR) ^= (bitwise XOR assignment) {} (object initializer)
  • Page 209 Symbolic operators See entry >= >= (greater than or equal to) >> >> (bitwise right shift) >>= >>= (bitwise right shift and assignment) >>> >>> (bitwise unsigned right shift) >>>= >>>= (bitwise unsigned right shift and assignment) The following table lists all ActionScript elements that are not symbolic operators. ActionScript element See entry #endinitclip...
  • Page 210 ActionScript element See entry _width Button._width MovieClip._width TextField._width Button._x MovieClip._x TextField._x _xmouse Button._xmouse MovieClip._xmouse TextField._xmouse _xscale Button._xscale MovieClip._xscale TextField._xscale Button._y MovieClip._y TextField._y _ymouse Button._ymouse MovieClip._ymouse TextField._ymouse _yscale Button._yscale MovieClip._yscale TextField._yscale Math.abs() Accessibility class Accessibility acos Math.acos() activityLevel Camera.activityLevel Microphone.activityLevel Key.addListener(), , MovieClipLoader.addListener(), addListener Mouse.addListener()
  • Page 211 ActionScript element See entry attachVideo Video.attachVideo() attributes XML.attributes autosize TextField.autoSize avHardwareDisable System.capabilities.avHardwareDisable background TextField.background backgroundColor TextField.backgroundColor BACKSPACE Key.BACKSPACE bandwidth Camera.bandwidth beginFill MovieClip.beginFill() beginGradientFill MovieClip.beginGradientFill() blockIndent TextFormat.blockIndent bold TextFormat.bold Boolean class Boolean Boolean() border TextField.border borderColor TextField.borderColor bottomScroll TextField.bottomScroll break break bufferLength NetStream.bufferLength bufferTime...
  • Page 212 ActionScript element See entry ceil Math.ceil() charAt String.charAt() charCodeAt String.charCodeAt() childNodes XML.childNodes class class , SharedObject.clear(), clear MovieClip.clear() Video.clear() clearInterval clearInterval() cloneNode XML.cloneNode() LocalConnection.close(), close NetStream.close() XMLSocket.close() Color class, Color TextFormat.color concat Array.concat() String.concat() connect LocalConnection.connect() NetConnection.connect() XMLSocket.connect() condenseWhite TextField.condenseWhite Array class, Boolean...
  • Page 213 ActionScript element See entry customItems ContextMenu.customItems data SharedObject.data Date class Date deblocking Video.deblocking default default delete delete DELETEKEY Key.DELETEKEY do while do while docTypeDecl XML.docTypeDecl domain LocalConnection.domain() DOWN Key.DOWN duplicateMovieClip duplicateMovieClip() MovieClip.duplicateMovieClip() duration Sound.duration dynamic dynamic Math.E else else else if else if embedFonts TextField.embedFonts...
  • Page 214 ActionScript element See entry firstChild XML.firstChild floor Math.floor() flush SharedObject.flush() focusEnabled MovieClip.focusEnabled font TextFormat.font for..in for..in Camera.fps fromCharCode String.fromCharCode() fscommand fscommand() Function class function function gain Microphone.gain ge (greater than or equal to — string specific) Camera.get() CustomActions.get() Microphone.get() getAscii Key.getAscii() getBeginIndex Selection.getBeginIndex()
  • Page 215 ActionScript element See entry getMilliseconds Date.getMilliseconds() getMinutes Date.getMinutes() getMonth Date.getMonth() getNewTextFormat TextField.getNewTextFormat() getNextHighestDepth MovieClip.getNextHighestDepth() getPan Sound.getPan() MovieClipLoader.getProgress() getProgress getProperty getProperty getRGB Color.getRGB() getSeconds Date.getSeconds() getSelected TextSnapshot.getSelected() getSelectedText TextSnapshot.getSelectedText() getSize SharedObject.getSize() getStyle TextField.StyleSheet.getStyle() getStyleNames TextField.StyleSheet.getStyleNames() getSWFVersion MovieClip.getSWFVersion() getText TextSnapshot.getText() getTextExtent TextFormat.getTextExtent() getTextFormat TextField.getTextFormat() MovieClip.getTextSnapshot()
  • Page 216 ActionScript element See entry getVersion getVersion getVolume Sound.getVolume() getYear Date.getYear() globalToLocal MovieClip.globalToLocal() goto gotoAndPlay() gotoAndStop() gotoAndPlay gotoAndPlay() MovieClip.gotoAndPlay() gotoAndStop gotoAndStop() MovieClip.gotoAndStop() gt (greater than — string specific) hasAccessibility System.capabilities.hasAccessibility hasAudio System.capabilities.hasAudio hasAudioEncoder System.capabilities.hasAudioEncoder hasChildNodes XML.hasChildNodes() hasEmbeddedVideo System.capabilities.hasEmbeddedVideo hasMP3 System.capabilities.hasMP3 hasPrinting System.capabilities.hasPrinting hasScreenBroadcast System.capabilities.hasScreenBroadcast...
  • Page 217 ActionScript element See entry ignoreWhite XML.ignoreWhite implements implements import import indent TextFormat.indent index Camera.index Microphone.index indexOf String.indexOf() Infinity Infinity -Infinity -Infinity INSERT Key.INSERT insertBefore XML.insertBefore() install CustomActions.install() instanceof instanceof interface interface isActive Accessibility.isActive() isDebugger System.capabilities.isDebugger isDown Key.isDown() isFinite isFinite isNaN isNaN() isToggled Key.isToggled()
  • Page 218 ActionScript element See entry lineStyle MovieClip.lineStyle() lineTo MovieClip.lineTo() list CustomActions.list() LN10 Math.LN10 Math.LN2 load LoadVars.load() TextField.StyleSheet.load() XML.load() MovieClipLoader.loadClip() loadClip loaded LoadVars.loaded XML.loaded loadMovie loadMovie() MovieClip.loadMovie() loadMovieNum loadMovieNum() loadSound Sound.loadSound() loadVariables loadVariables() MovieClip.loadVariables() loadVariablesNum loadVariablesNum() LoadVars class LoadVars LocalConnection LocalConnection class localFileReadDisable System.capabilities.localFileReadDisable localToGlobal...
  • Page 219 ActionScript element See entry message Error.message Microphone class Microphone Math.min() MIN_VALUE Number.MIN_VALUE MMExecute MMExecute() motionLevel Camera.motionLevel motionTimeOut Camera.motionTimeOut Mouse Mouse class mouseWheelEnabled TextField.mouseWheelEnabled moveTo MovieClip.moveTo() MovieClip MovieClip class MovieClipLoader MovieClipLoader class multiline TextField.multiline muted Camera.muted Microphone.muted name Error.name Microphone.name names Camera.names Microphone.names Number.NaN...
  • Page 220 ActionScript element See entry on() onActivity Camera.onActivity Microphone.onActivity onChanged TextField.onChanged onClipEvent onClipEvent() onClose XMLSocket.onClose() onConnect XMLSocket.onConnect() onData LoadVars.onData MovieClip.onData XML.onData XMLSocket.onData() onDragOut Button.onDragOut MovieClip.onDragOut onDragOver Button.onDragOver MovieClip.onDragOver onEnterFrame MovieClip.onEnterFrame onID3 Sound.onID3 onKeyDown Button.onKeyDown Key.onKeyDown MovieClip.onKeyDown onKeyUp Button.onKeyUp Key.onKeyUp MovieClip.onKeyUp onKillFocus Button.onKillFocus MovieClip.onKillFocus TextField.onKillFocus...
  • Page 221 ActionScript element See entry onSetFocus Button.onSetFocus MovieClip.onSetFocus Selection.onSetFocus TextField.onSetFocus onSoundComplete Sound.onSoundComplete onStatus Camera.onStatus LocalConnection.onStatus Microphone.onStatus NetStream.onStatus SharedObject.onStatus, System.onStatus onUnload MovieClip.onUnload onUpdate onUpdate onXML XMLSocket.onXML() or (logical OR) System.capabilities.os parentNode XML.parentNode parseCSS TextField.StyleSheet.parseCSS() parseFloat parseFloat() parseInt parseInt parseXML XML.parseXML() password TextField.password pause NetStream.pause() PGDN...
  • Page 222 ActionScript element See entry PrintJob PrintJob class printNum printNum() private private prototype Function.prototype public public push Array.push() quality Camera.quality random random Math.random() rate Microphone.rate registerClass Object.registerClass() removeListener Key.removeListener() Mouse.removeListener() MovieClipLoader.removeListener() Selection.removeListener() Stage.removeListener() TextField.removeListener() removeMovieClip removeMovieClip() MovieClip.removeMovieClip() removeNode XML.removeNode() removeTextField TextField.removeTextField() replaceSel TextField.replaceSel() replaceText...
  • Page 223 ActionScript element See entry Selection Selection class send LoadVars.send() LocalConnection.send() PrintJob.send() XML.send() XMLSocket.send() sendAndLoad LoadVars.sendAndLoad() XML.sendAndLoad() separatorBefore ContextMenuItem.separatorBefore serverString System.capabilities.serverString set variable set variable setBufferTime NetStream.setBufferTime() System.setClipboard() setClipboard setDate Date.setDate() setFocus Selection.setFocus() setFullYear Date.setFullYear() setGain Microphone.setGain() setHours Date.setHours() setInterval setInterval() setMask MovieClip.setMask() setMilliseconds...
  • Page 224 ActionScript element See entry setStyle TextField.StyleSheet.setStyle() setTextFormat TextField.setTextFormat() setTime Date.setTime() setTransform Color.setTransform() Sound.setTransform() setUseEchoSuppression Microphone.setUseEchoSuppression() setUTCDate Date.setUTCDate() setUTCFullYear Date.setUTCFullYear() setUTCHours Date.setUTCHours() setUTCMilliseconds Date.setUTCMilliseconds() setUTCMinutes Date.setUTCMinutes() setUTCMonth Date.setUTCMonth() setUTCSeconds Date.setUTCSeconds() setVolume Sound.setVolume() setYear Date.setYear() SharedObject SharedObject class SHIFT (constant) Key.SHIFT shift (method) Array.shift() show Mouse.show()
  • Page 225 ActionScript element See entry SQRT1_2 Math.SQRT1_2 SQRT2 Math.SQRT2 Stage class Stage start PrintJob.start() Sound.start() startDrag startDrag() MovieClip.startDrag() static static status XML.status stop stop() MovieClip.stop() Sound.stop() stopAllSounds stopAllSounds() stopDrag stopDrag() MovieClip.stopDrag() String class, String String() StyleSheet (class) TextField.StyleSheet class styleSheet (property) TextField.styleSheet substr String.substr()
  • Page 226 ActionScript element See entry TextSnapshot TextSnapshot object textWidth TextField.textWidth this this throw throw time NetStream.time toggleHighQuality toggleHighQuality() toLowerCase String.toLowerCase() toString Array.toString() Boolean.toString() Date.toString() Error.toString() LoadVars.toString() Number.toString() Object.toString() XML.toString() toUpperCase String.toUpperCase() trace trace() trackAsMenu Button.trackAsMenu MovieClip.trackAsMenu true true try..catch..finally type TextField.type typeof typeof undefined...
  • Page 227 ActionScript element See entry valueOf Boolean.valueOf() Number.valueOf() Object.valueOf() variable TextField.variable version System.capabilities.version Video Video class visible ContextMenuItem.visible void void watch Object.watch() while while width Camera.width Stage.width Video.width with with wordwrap TextField.wordWrap XML class xmlDecl XML.xmlDecl XMLNode XMLNode class XMLSocket class XMLSocket ––...
  • Page 228 Example The pre-decrement form of the operator decrements to 2 ( ), and returns the result x - 1 = 2 x = 3; y = --x; //y is equal to 2 The post-decrement form of the operator decrements to 2 ( ), and returns the original x - 1 = 2 value of...
  • Page 229 Example The following example uses ++ as a post-increment operator to make a loop run five times. while i = 0; while(i++ < 5){ trace("this is execution " + i); This example uses ++ as a pre-increment operator. var a = []; var i = 0;...
  • Page 230 Example In the following example, the variable is set to . The condition evaluates the happy false condition , and if the condition is , the action sends a string to the !happy true trace() Output panel. happy = false; if (!happy) { trace("don’t worry, be happy");...
  • Page 231 !== (strict inequality) Availability Flash Player 6. Usage expression1 !== expression2 Description Operator; tests for the exact opposite of the operator. The strict inequality operator performs the same as the inequality operator except that data types are not converted. If expression1 equal to , and their data types are equal, the result is...
  • Page 232 % (modulo) Availability Flash Player 4. In Flash 4 files, the operator is expanded in the SWF file as x - int(x/y) * y and may not be as fast or as accurate in later versions of Flash Player. Usage expression1 % expression2 Parameters None.
  • Page 233 Example The following example assigns the value to the variable x = 14; y = 5; trace(x %= y); // returns 4 See also % (modulo) & (bitwise AND operator) Availability Flash Player 5. In Flash 4, the operator was used for concatenating strings. In Flash 5 and later, &...
  • Page 234 Description Operator (logical); performs a Boolean operation on the values of one or both of the expressions. Evaluates (the expression on the left side of the operator) and returns if the expression1 false expression evaluates to . If evaluates to (the expression false expression1...
  • Page 235 () (parentheses) Availability Flash Player 4. Usage (expression1, expression2) function(parameter1,..., parameterN) Parameters Numbers, strings, variables, or text. expression1, expression2 The function to be performed on the contents of the parentheses. function A series of parameters to execute before the results are passed as parameter1...parameterN parameters to the function outside the parentheses.
  • Page 236 See also with – (minus) Availability Flash Player 4. Usage (Negation) - expression (Subtraction) expression1 expression2 Parameters None. Returns Nothing. Description Operator (arithmetic); used for negating or subtracting. Usage 1: When used for negating, it reverses the sign of the numerical expression Usage 2: When used for subtracting, it performs an arithmetic subtraction on two numerical expressions, subtracting...
  • Page 237 * (multiplication) Availability Flash Player 4. Usage expression1 * expression2 Parameters None. Returns Nothing. Description Operator (arithmetic); multiplies two numerical expressions. If both expressions are integers, the product is an integer. If either or both expressions are floating-point numbers, the product is a floating-point number.
  • Page 238 Example Usage 1: The following example assigns the value 50 to the variable x = 5; y = 10; trace (x *= y); // returns 50 Usage 2: The second and third lines of the following example calculate the expressions on the right-hand side of the equals sign and assign the results to i = 5;...
  • Page 239 . (dot) Availability Flash Player 4. Usage object.property_or_method instancename.variable instancename.childinstance.variable Parameters An instance of a class. The object can be an instance of any of the built-in ActionScript object classes or a custom class. This parameter is always to the left of the dot (.) operator. The name of a property or method associated with an object.
  • Page 240 Parameters An identifier for a variable. variableName A native data type, class name that you have defined, or interface name. type An identifier for a function. functionName An identifier for a function parameter. parameter Description Operator; specifies the variable type, function return type, or function parameter type. When used in a variable declaration or assignment, this operator specifies the variable’s type;...
  • Page 241 ?: (conditional) Availability Flash Player 4. Usage expression1 ? expression2 : expression3 Parameters An expression that evaluates to a Boolean value, usually a comparison expression, expression1 such as x < 5 Values of any type. expression2 expression3 Returns Nothing. Description Operator;...
  • Page 242 Example The following statement divides the floating-point number 22.0 by 7.0 and then displays the result in the Output panel. trace(22.0 / 7.0); The result is , which is a floating-point number. 3.1429 // (comment delimiter) Availability Flash 1. Usage // comment Parameters Any characters.
  • Page 243 /* (comment delimiter) Availability Flash Player 5. Usage /* comment */ comment comment Parameters Any characters. comment Returns Nothing. Description Comment; indicates one or more lines of script comments. Any characters that appear between the opening comment tag and the closing comment tag , are interpreted as a comment and ignored by the ActionScript interpreter.
  • Page 244 /= (division assignment) Availability Flash Player 4. Usage expression1 /= expression2 Parameters A number or a variable that evaluates to a number. expression1,expression2 Returns Nothing. Description Operator (arithmetic compound assignment); assigns the value of expression1 expression1 / . For example, the following two statements are the same: expression2 x /= y x = x / y...
  • Page 245 Returns Nothing. Description Operator; initializes a new array or multidimensional array with the specified elements ( , and so on), or accesses elements in an array. The array access operator lets you dynamically set and retrieve instance, variable, and object names. It also lets you access object properties. Usage 1: An array is an object whose properties are called elements, which are each identified by a number called an index.
  • Page 246 Usage 1 and 2: The following example creates an array called and uses the employee_array action to send the elements to the Output panel. In the fourth line, an element in the trace() array is changed and the fifth line sends the newly modified array to the Output panel: employee_array = ["Barbara", "George", "Mary"];...
  • Page 247 Description Operator (bitwise); converts to 32-bit unsigned integers, and expression1 expression2 returns a 1 in each bit position where the corresponding bits in expression1 expression1 but not both, are 1. Example The following example uses the bitwise XOR operator on the decimals 15 and 9 and assigns the result to the variable // 15 decimal = 1111 binary // 9 decimal = 1001 binary...
  • Page 248 {} (object initializer) Availability Flash Player 5. Usage object = {name1: value1, name2: value2,...nameN: valueN} Parameters The object to create. object The names of the properties. name1,2,...N The corresponding values for each property. value1,2,...N name Returns None. Description Operator; creates a new object and initializes it with the specified property pairs.
  • Page 249 See also Object class [] (array access) | (bitwise OR) Availability Flash Player 5. Usage expression1 | expression2 Parameters A number. expression1,expression2 Returns None. Description Operator (bitwise); converts to 32-bit unsigned integers, and expression1 expression2 returns a 1 in each bit position where the corresponding bits of either expression1 are 1.
  • Page 250 Description Operator (logical); evaluates . The result is if either or both expression1 expression2 true expressions evaluate to ; the result is only if both expressions evaluate to . You true false false can use the logical OR operator with any number of operands; if any operand evaluates to true the result is true...
  • Page 251 Description Operator (bitwise compound assignment); assigns the value of expression1 expression1 | . For example, the following two statements are the same: expression2 x |= y; x = x | y; Example The following example uses the operator: // 15 decimal = 1111 binary x = 15;...
  • Page 252 + (addition) Availability Flash Player 4; Flash Player 5. In Flash 5 and later, is either a numeric operator or string concatenator depending on the data type of the parameter. In Flash 4, is only a numeric operator. Flash 4 files brought into the Flash 5 or later authoring environment undergo a conversion process to maintain data type integrity.
  • Page 253 Usage 3: This statement adds the integers 2 and 3 and displays the resulting integer, 5, in the Output panel: trace (2 + 3); This statement adds the floating-point numbers 2.5 and 3.25 and displays the result, 5.75 floating-point number, in the Output panel: trace (2.5 + 3.25);...
  • Page 254 < (less than) Availability Flash Player 4; Flash Player 5. In Flash 5 and later, the (less than) operator is a comparison < operator capable of handling various data types. In Flash 4, is an numeric operator. Flash 4 files <...
  • Page 255 << (bitwise left shift) Availability Flash Player 5. Usage expression1 << expression2 Parameters A number or expression to be shifted left. expression1 A number or expression that converts to an integer from 0 to 31. expression2 Returns Nothing. Description Operator (bitwise); converts to 32-bit integers, and shifts all of expression1 expression2...
  • Page 256 Returns Nothing. Description Operator (bitwise compound assignment); this operator performs a bitwise left shift operation and stores the contents as a result in . The following two expressions are equivalent. expression1 A <<= B A = (A << B) See also <<...
  • Page 257 • Numbers, strings, and Boolean values are compared by value. • Variables, objects, arrays, and functions are compared by reference. This operator was deprecated in Flash 5, and Macromedia recommends that you use the operator. See also != (inequality) <> (inequality)
  • Page 258 = (assignment) Availability Flash Player 4. Flash 4 file: x = y Converted Flash 5 or later file: Number(x) == Number(y) Usage expression1 = expression2 Parameters A variable, element of an array, or property of an object. expression1 A value of any type. expression2 Returns Nothing.
  • Page 259 -= (subtraction assignment) Availability Flash Player 4. Usage expression1 -= expression2 Parameters A number or expression that evaluates to a number. expression1,expression2 Returns Nothing. Description Operator (arithmetic compound assignment); assigns the value of expression1 expression1 - . For example, the following two statements are the same: expression2 x -= y;...
  • Page 260 == (equality) Availability Flash Player 5. Usage expression1 == expression2 Parameters A number, string, Boolean value, variable, object, array, expression1,expression2 or function. Returns A Boolean value. Description Operator (equality); tests two expressions for equality. The result is if the expressions true are equal.
  • Page 261 === (strict equality) Availability Flash Player 6. Usage expression1 === expression2 Returns A Boolean value. Description Operator; tests two expressions for equality; the strict equality operator performs just like the equality operator except that data types are not converted. The result is if both expressions, true including their data types, are equal.
  • Page 262 > (greater than) Availability Flash Player 4. Flash 4 file: x > y Converted Flash 5 or later file: Number(x) > Number(y) Usage expression1 >expression2 Parameters A number or string. expression1,expression2 Returns A Boolean value. Description Operator (comparison); compares two expressions and determines whether expression1 greater than ;...
  • Page 263 Description Operator (comparison); compares two expressions and determines whether expression1 greater than or equal to ), or whether is less than expression2 true expression1 expression2 false In Flash 5 or later, greater than or equal to ( ) is a comparison operator capable of handling >...
  • Page 264 This is because -1 decimal equals 11111111111111111111111111111111 binary (thirty-two 1’s), shifting right by one bit causes the least significant (bit farthest to the right) to be discarded and the most significant bit to be filled in with 1. The result is 11111111111111111111111111111111 (thirty-two 1’s) binary, which represents the 32-bit integer -1.
  • Page 265 See also << (bitwise left shift) >>> (bitwise unsigned right shift) Availability Flash Player 5. Usage expression1 >>> expression2 Parameters A number or expression to be shifted right. expression1 A number or expression that converts to an integer between 0 and 31. expression2 Returns Nothing.
  • Page 266: Accessibility Class

    >>>= (bitwise unsigned right shift and assignment) Availability Flash Player 5. Usage expression1 >>>= expression2 Parameters A number or expression to be shifted left. expression1 A number or expression that converts to an integer from 0 to 31. expression2 Returns Nothing.
  • Page 267 Accessibility.isActive() Availability Flash Player 6 version 65. Usage Accessibility.isActive() Parameters None. Returns A Boolean value of if there are active Microsoft Active Accessibility (MSAA) clients and the true player is running in an environment that supports communication between Flash Player and accessibility aids, otherwise.
  • Page 268 Description Method; causes Flash Player to reexamine all accessibility properties, update its description of objects for screen readers, and, if necessary, send events to screen readers to indicate that changes have occurred. For information on setting accessibility properties, see _accProps. To determine whether the player is running in an environment that supports accessibility aids, use System.capabilities.hasAccessibility If you modify the accessibility properties for multiple objects, only one call to...
  • Page 269 To determine whether the player is running in an environment that supports accessibility aids, use System.capabilities.hasAccessibility The following table lists the name and data type of each property, its equivalent _accProps setting in the Accessibility panel, and the kinds of objects to which the property can be applied. The term inverse logic means that the property setting is the inverse of the corresponding setting in the Accessibility panel.
  • Page 270 If you are specifying several accessibility properties, make as many changes as you can before calling , instead of calling it after each Accessibility.updateProperties() property statement: _accprops.name = "Pet Store"; animal_mc._accProps.name = "Animal"; animal_mc._accProps.description = "Cat, dog, fish, etc."; price_mc._accProps.name = "Price"; price_mc._accProps.description = "Cost of a single item";...
  • Page 271 Flash 5 or later authoring environment. However, the operator was deprecated in Flash Player 5, and Macromedia recommends that you use the operator when creating content for Flash Player 5 or later. Use the operator to concatenate strings if you are creating content for Flash Player 4 or earlier versions of the player.
  • Page 272: Arguments Class

    Arguments class Availability Flash Player 5; property added in Flash Player 6. Description The Arguments class is an array that contains the values that were passed as parameters to any function. Each time a function is called in ActionScript, an Arguments object is automatically created for that function.
  • Page 273: Array Class

    arguments.caller Availability Flash Player 6. Usage arguments.caller Description Property; refers to the calling function. arguments.length Availability Flash Player 5. Usage arguments.length Description Property; the number of parameters actually passed to a function. Array class Availability Flash Player 5 (became a native object in Flash Player 6, which improved performance significantly).
  • Page 274 Method summary for the Array class Method Description Concatenates the parameters and returns them as a new array. Array.concat() Joins all elements of an array into a string. Array.join() Removes the last element of an array and returns its value. Array.pop() Adds one or more elements to the end of an array and returns the array’s new Array.push()
  • Page 275 Description Constructor; lets you create an array. You can use the constructor to create different types of arrays: an empty array, an array with a specific length but whose elements have no values, or an array whose elements have specific values. Usage 1: If you don’t specify any parameters, an array with a length of 0 is created.
  • Page 276 Array.concat() Availability Flash Player 5. Usage my_array.concat( [ value0, value1,...valueN ]) Parameters Numbers, elements, or strings to be concatenated in a new array. If you value0,...valueN don’t pass any values, a duplicate of is created. my_array Returns Nothing. Description Method; concatenates the elements specified in the parameters with the elements in my_array and creates a new array.
  • Page 277 Array.join() Availability Flash Player 5. Usage my_array.join([separator]) Parameters A character or string that separates array elements in the returned string. If you omit separator this parameter, a comma is used as the default separator. Returns String. Description Method; converts the elements in an array to strings, inserts the specified separator between the elements, concatenates them, and returns the resulting string.
  • Page 278 Array.length Availability Flash Player 5. Usage my_array.length Description Property; a nonzero-based integer specifying the number of elements in the array. This property is automatically updated when new elements are added to the array. When you assign a value to an array element (for example, ), if is a number, and...
  • Page 279 Array.push() Availability Flash Player 5. Usage my_array.push(value,...) Parameters One or more values to append to the array. value Returns The length of the new array. Description Method; adds one or more elements to the end of an array and returns the array’s new length. Example The following example creates the array with two elements,...
  • Page 280 Array.shift() Availability Flash Player 5. Usage my_array.shift() Parameters None. Returns The first element in an array. Description Method; removes the first element from an array and returns that element. Example The following code creates the array and then removes the first element from the array myPets and assigns it to the variable shifted...
  • Page 281 Description Method; extracts a slice or a substring of the array and returns it as a new array without modifying the original array. The returned array includes the element and all elements up to, but not start including, the element. If you don’t pass any parameters, a duplicate of is created.
  • Page 282 Description Method; sorts the elements in an array. Flash sorts according to ASCII (Unicode) values. If either of the elements being compared does not contain the field specified in the parameter, fieldName the field is assumed to be , and the elements are placed consecutively in the sorted undefined array in no particular order.
  • Page 283 trace ("Unsorted:"); trace (passwords.join()); passwords.sort(order); trace ("Sorted:"); trace (passwords.join()); The Output panel displays the following results: Unsorted: mom:glam,ana:ring,jay:mag,anne:home,regina:silly Sorted: ana:ring,anne:home,jay:mag,mom:glam,regina:silly See also | (bitwise OR) Array.sortOn() Array.sortOn() Availability Flash Player 6; additional capabilities added in Flash Player 7. Usage my_array.sortOn("fieldName" ) my_array.sortOn("fieldName", option | option |...
  • Page 284 Returns The return value depends on whether you pass any parameters: • If you specify a value of 4 or Array.UNIQUE for , and two or more elements being option sorted have identical sort fields, Flash returns a value of 0 and does not modify the array. •...
  • Page 285 Performing a default sort on the password field produces the following results: my_array.sortOn("password") // Bob // abcd // barb // catchy Performing a case-insensitive sort on the password field produces the following results: my_array.sortOn("password", Array.CASEINSENSITIVE) // abcd // barb // Bob // catchy Performing a case-insensitive, descending sort on the password field produces the following results:...
  • Page 286 Performing a sort that returns an index array doesn’t change the elements in the array: // Before sorting // my_array[0].age = 29; // my_array[1].age = 3; // my_array[2].age = 35; // my_array[3].age = 4; // After a sort that returns an array containing index values // Note that the original array is unchanged.
  • Page 287 Array.splice() Availability Flash Player 5. Usage my_array.splice(start, deleteCount [, value0, value1...valueN]) Parameters The index of the element in the array where the insertion or deletion begins. start The number of elements to be deleted. This number includes the element deleteCount specified in the parameter.
  • Page 288 Example The following example creates , converts it to a string, and displays 1,2,3,4,5 in the my_array Output panel. my_array = new Array(); my_array[0] = 1; my_array[1] = 2; my_array[2] = 3; my_array[3] = 4; my_array[4] = 5; trace(my_array.toString()); Array.unshift() Availability Flash Player 5.
  • Page 289: Boolean Class

    asfunction Availability Flash Player 5. Usage asfunction:function,"parameter" Parameters An identifier for a function. function A string that is passed to the function named in the parameter. parameter function Returns Nothing. Description Protocol; a special protocol for URLs in HTML text fields. In HTML text fields, text may be hyperlinked using the HTML tag.
  • Page 290 Method summary for the Boolean class Method Description Returns the string representation of the Boolean object. Boolean.toString() ("true" "false") Returns the primitive value type of the specified Boolean object. Boolean.valueOf() Constructor for the Boolean class Availability Flash Player 5. Usage new Boolean([x]) Parameters Any expression.
  • Page 291 Boolean.valueOf() Availability Flash Player 5. Usage myBoolean.valueOf() Parameters None. Returns A Boolean value. Description Method; returns if the primitive value type of the specified Boolean object is true, true false it is false. Example var x:Boolean = new Boolean(); trace(x.valueOf()); // false x = (6==3+3);...
  • Page 292 is undefined, the return value is expression false is a movie clip or an object, the return value is expression true See also Boolean class break Availability Flash Player 4. Usage break Parameters None. Returns Nothing. Description Statement; appears within a loop ( ) or within a block of for..in do while...
  • Page 293: Button Class

    Button class Availability Flash Player 6. Description All button symbols in a SWF file are instances of the Button object. You can give a button an instance name in the Property inspector, and use the methods and properties of the Button class to manipulate buttons with ActionScript.
  • Page 294 Property Description A Boolean value that indicates whether a button instance is hidden or Button._visible visible. The width of a button instance, in pixels. Button._width The x coordinate of a button instance. Button._x The x coordinate of the mouse pointer relative to a button instance. Button._xmouse The value specifying the percentage for horizontally scaling a button Button._xscale...
  • Page 295 Button._alpha Availability Flash Player 6. Usage my_btn._alpha Description Property; the alpha transparency value of the button specified by . Valid values are 0 (fully my_btn transparent) to 100 (fully opaque). The default value is 100. Objects in a button with _alpha to 0 are active, even though they are invisible.
  • Page 296 Button.getDepth() Availability Flash Player 6. Usage my_btn.getDepth() Returns An integer. Description Method; returns the depth of a button instance. Button._height Availability Flash Player 6. Usage my_btn._height Description Property; the height of the button, in pixels. Example The following code example sets the height and width of a button when the user clicks the mouse: my_btn._width = 200;...
  • Page 297 Button.menu Availability Flash Player 7. Usage my_button.menu = contextMenu Parameters A ContextMenu object. contextMenu Description Property; associates the ContextMenu object with the button object contextMenu my_button The ContextMenu class lets you modify the context menu that appears when the user right-clicks (Windows) or Control-clicks (Macintosh) in Flash Player.
  • Page 298 Button.onDragOut Availability Flash Player 6. Usage my_btn.onDragOut = function() { // your statements here Parameters None. Returns Nothing. Description Event handler; invoked when the mouse button is pressed over the button and the pointer then rolls outside the button. You must define a function that executes when the event handler is invoked. Button.onDragOver Availability Flash Player 6.
  • Page 299 See also Button.onKeyUp Button.onKeyDown Availability Flash Player 6. Usage my_btn.onKeyDown = function() { // your statements here Parameters None. Returns Nothing. Description Event handler; invoked when a button has keyboard focus and a key is pressed. The onKeyDown event handler is invoked with no parameters. You can use Key.getAscii() Key.getCode() to determine which key was pressed.
  • Page 300 Returns Nothing. Description Event handler; invoked when a button has input focus and a key is released. The event onKeyUp handler is invoked with no parameters. You can use Key.getAscii() Key.getCode() determine which key was pressed. You must define a function that executes when the event handler is invoked. Example In the following example, a function that sends a action to the Output panel is defined...
  • Page 301 Returns Nothing. Description Event handler; invoked when a button is pressed. You must define a function that executes when the event handler is invoked. Example In the following example, a function that sends a action to the Output panel is defined trace() for the handler.
  • Page 302 Button.onReleaseOutside Availability Flash Player 6. Usage my_btn.onReleaseOutside = function() { // your statements here Parameters None. Returns Nothing. Description Event handler; invoked when the mouse is released while the pointer is outside the button after the button is pressed while the pointer is inside the button. You must define a function that executes when the event handler is invoked.
  • Page 303 Example In the following example, a function that sends a action to the Output panel is defined trace() for the handler. onRollOut my_btn.onRollOut = function () { trace ("onRollOut called"); Button.onRollOver Availability Flash Player 6. Usage my_btn.onRollOver = function() { // your statements here Parameters None.
  • Page 304 Description Event handler; invoked when a button receives keyboard focus. The parameter is the oldFocus object that loses the focus. For example, if the user presses the Tab key to move the input focus from a text field to a button, contains the text field instance.
  • Page 305 Button._rotation Availability Flash Player 6. Usage my_btn._rotation Description Property; the rotation of the button, in degrees, from its original orientation. Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation. Values outside this range are added to or subtracted from 360 to obtain a value within the range. For example, the statement is the same as my_btn._rotation = 450...
  • Page 306 Button.tabIndex Availability Flash Player 6. Usage my_btn.tabIndex Description Property; lets you customize the tab ordering of objects in a SWF file. You can set the tabIndex property on a button, movie clip, or text field instance; it is by default. undefined If any currently displayed object in the SWF file contains a property, automatic tab...
  • Page 307 Button.trackAsMenu Availability Flash Player 6. Usage my_btn.trackAsMenu Description Property; a Boolean value that indicates whether other buttons or movie clips can receive mouse release events. This allows you to create menus. You can set the property on any trackAsMenu button or movie clip object. If the property has not been defined, the default trackAsMenu behavior is...
  • Page 308 Button._visible Availability Flash Player 6. Usage my_btn._visible Description Property; a Boolean value that indicates whether the button specified by is visible. my_btn Buttons that are not visible ( property set to ) are disabled. _visible false See also MovieClip._visible TextField._visible Button._width Availability Flash Player 6.
  • Page 309 Button._x Availability Flash Player 6. Usage my_btn._x Description Property; an integer that sets the x coordinate of a button relative to the local coordinates of the parent movie clip. If a button is on the main Timeline, then its coordinate system refers to the upper left corner of the Stage as (0, 0).
  • Page 310 Button._xscale Availability Flash Player 6. Usage my_btn._xscale Description Property; the horizontal scale of the button as applied from the registration point of the button, expressed as a percentage. The default registration point is (0,0). Scaling the local coordinate system affects the property settings, which are defined in pixels.
  • Page 311 The default registration point is (0,0). See also Button._y, Button._x, Button._xscale call() Availability Flash Player 4. This action was deprecated in Flash 5, and Macromedia recommends that you use action instead. function Usage call(frame) Parameters The label or number of a frame in the Timeline.
  • Page 312: Camera Class

    Flash Player 6. Description The Camera class is primarily for use with Macromedia Flash Communication Server, but can be used in a limited fashion without the server. The Camera class lets you capture video from a video camera attached to the computer that is running the Macromedia Flash Player—for example, to monitor a video feed from a web camera...
  • Page 313 Property (read-only) Description The number of milliseconds between the time when the camera stops Camera.motionTimeOut detecting motion and the time is invoked. Camera.onActivity(false) A Boolean value that specifies whether the user has allowed or denied Camera.muted access to the camera. The name of the camera as specified by the camera hardware.
  • Page 314 Camera.bandwidth Availability Flash Player 6. Usage active_cam.bandwidth Description Read-only property; an integer that specifies the maximum amount of bandwidth the current outgoing video feed can use, in bytes. A value of 0 means that Flash video can use as much bandwidth as needed to maintain the desired frame quality.
  • Page 315 Camera.fps Availability Flash Player 6. Usage active_cam.fps Description Read-only property; the maximum rate at which you want the camera to capture data, in frames per second. The maximum rate possible depends on the capabilities of the camera; that is, if the camera doesn’t support the value you set here, this frame rate will not be achieved.
  • Page 316 Returns • is not specified, this method returns a reference to the default camera or, if it is in use index by another application, to the first available camera. (If there is more than one camera installed, the user may specify the default camera in the Flash Player Camera Settings panel.) If no cameras are available or installed, the method returns null •...
  • Page 317 You can’t use ActionScript to set the Allow or Deny value for a user, but you can display the Privacy panel for the user by using . If the user selects Remember, System.showSettings(0) Flash Player no longer displays the Privacy dialog box for movies from this domain. returns , either the camera is in use by another application, or there are no Camera.get...
  • Page 318 Camera.height Availability Flash Player 6. Usage active_cam.height Description Read-only property; the current capture height, in pixels. To set a value for this property, use Camera.setMode() Example The following line of code updates a text box in the user interface with the current height value. my_txt._height = myCam.height;...
  • Page 319 Camera.motionLevel Availability Flash Player 6. Usage active_cam.motionLevel Description Read-only property; a numeric value that specifies the amount of motion required to invoke . Acceptable values range from 0 to 100. The default value is 50. Camera.onActivity(true) Video can be displayed regardless of the value of the property.
  • Page 320 Camera.muted Availability Flash Player 6. Usage active_cam.muted Description Read-only property; a Boolean value that specifies whether the user has denied access to the camera ( ) or allowed access ( ) in the Flash Player Privacy Settings panel. When this true false value changes,...
  • Page 321 Camera.names Availability Flash Player 6. Usage Camera.names Note: The correct syntax is . To assign the return value to a variable, use syntax like Camera.names . To determine the name of the current camera, use cam_array = Camera.names active_cam.name Description Read-only class property;...
  • Page 322 Description Event handler; invoked when the camera starts or stops detecting motion. If you want to respond to this event handler, you must create a function to process its value. activity To specify the amount of motion required to invoke and the Camera.onActivity(true) amount of time that must elapse without activity before invoking...
  • Page 323 • If the user allows access, the property is set to , and this handler is Camera.muted false invoked with an information object whose property is and whose code "Camera.Unmuted" property is level "Status" • If the user denies access, the property is set to , and this handler is invoked Camera.muted...
  • Page 324 Camera.setMode() Availability Flash Player 6. Usage active_cam.setMode(width, height, fps [,favorSize]) Parameters The requested capture width, in pixels. The default value is 160. width The requested capture height, in pixels. The default value is 120. height The requested rate at which the camera should capture data, in frames per second. The default value is 15.
  • Page 325 on (press) // Sets width, height, and fps to user's input. _root.myCam.setMode(txt_width, my_txt._height, txt_fps); // Update the user’s text fields with the new settings. _root.txt_width = myCam.width; _root.txt_height = myCam.height; _root.txt_fps = myCam.fps; See also , Camera.fps, Camera.currentFps Camera.height Camera.width Camera.setMotionLevel() Availability Flash Player 6.
  • Page 326 This method is similar in purpose to ; both methods are used Microphone.setSilenceLevel() to specify when the event handler should be invoked. However, these methods have onActivity a significantly different impact on publishing streams: • is designed to optimize bandwidth. When an audio stream Microphone.setSilenceLevel() is considered silent, no audio data is sent.
  • Page 327 Description Method; sets the maximum amount of bandwidth per second or the required picture quality of the current outgoing video feed. This method is generally applicable only if you are transmitting video using Flash Communication Server. Use this method to specify which element of the outgoing video feed is more important to your application—bandwidth use or picture quality.
  • Page 328 Camera.width Availability Flash Player 6. Usage active_cam.width Description Read-only property; the current capture width, in pixels. To set a desired value for this property, Camera.setMode() Example The following line of code updates a text box in the user interface with the current width value. myTextField.text=myCam.width;...
  • Page 329 Availability Flash Player 4. This function was deprecated in Flash 5 in favor of String.fromCharCode() Usage chr(number) Parameters An ASCII code number. number Returns Nothing. Description String function; converts ASCII code numbers to characters. Example The following example converts the number 65 to the letter A and assigns it to the variable myVar myVar = chr(65);...
  • Page 330 Description Statement; defines a custom class, which lets you instantiate objects that share methods and properties that you define. For example, if you are developing an invoice-tracking system, you could create an invoice class that defines all the methods and properties that each invoice should have.
  • Page 331: Color Class

    In an external script file or in the Actions panel, use the operator to create a Plant object. var pineTree:Plant = new Plant("Evergreen","N/A"); // Confirm parameters were passed correctly trace(pineTree.getLeafType()); trace(pineTree.getBloomSeason()); See also dynamic extends implements interface clearInterval() Availability Flash Player 6. Usage clearInterval( intervalID ) Parameters...
  • Page 332 Method summary for the Color class Method Description Returns the numeric RGB value set by the last call. Color.getRGB() setRGB() Color.getTransform() Returns the transform information set by the last call. setTransform() Sets the hexadecimal representation of the RGB value for a Color object. Color.setRGB() Sets the color transform for a Color object.
  • Page 333 Description Method; returns the numeric values set by the last call. setRGB() Example The following code retrieves the RGB value for the Color object , converts it to a my_color hexadecimal string, and assigns it to the variable. value value = my_color.getRGB().toString(16); See also Color.setRGB() Color.getTransform()
  • Page 334 Returns Nothing. Example This example sets the RGB color value for the movie clip . To see this code work, place a my_mc movie clip on the Stage with the instance name . Then place the following code on Frame 1 my_mc in the main Timeline and choose Control >...
  • Page 335: Contextmenu Class

    You create a parameter as follows: colorTransformObject myColorTransform = new Object(); myColorTransform.ra = 50; myColorTransform.rb = 244; myColorTransform.ga = 40; myColorTransform.gb = 112; myColorTransform.ba = 12; myColorTransform.bb = 90; myColorTransform.aa = 40; myColorTransform.ab = 70; You can also use the following syntax to create a parameter: colorTransformObject myColorTransform = { ra: ‘50’, rb: ‘244’, ga: ‘40’, gb: ‘112’, ba: ‘12’, bb:...
  • Page 336 Flash Player has three types of context menus: the standard menu (which appears when you right- click in Flash Player), the edit menu (which appears when you right-click over a selectable or editable text field), and an error menu (which appears when a SWF file has failed to load into Flash Player.) Only the standard and edit menus can be modified with the ContextMenu class.
  • Page 337 Description Constructor; creates a new ContextMenu object. You can optionally specify an identifier for an event handler when you create the object. The specified function is called when the user invokes the context menu, but before the menu is actually displayed. This is useful for customizing menu contents based on application state or based on the type of object (movie clip, text field, or button) that the user right-clicks or Control-clicks.
  • Page 338 Example In this example, the built-in Quality and Print menu items are disabled for the ContextMenu object , which is attached to the root Timeline of the SWF file. my_cm var my_cm = new ContextMenu (); my_cm.builtInItems.quality=false; my_cm.builtInItems.print=false; _root.menu = my_cm; In the next example, a loop enumerates through all names and values of the built-in for..in...
  • Page 339 ContextMenu.customItems Availability Flash Player 7. Usage my_cm.customItems Description Property; an array of ContextMenuItem objects. Each object in the array represents a context menu item that you have defined. Use this property to add, remove, or modify these custom menu items. To add new menu items, you first create a new ContextMenuItem object, and then add it to the array (using , for example).
  • Page 340 This method hides only menu items that appear in the standard context menu; it does not affect items that appear in the edit or error menus. For more information about the different menu types, see the ContextMenu class entry. This method works by setting all the Boolean members of .
  • Page 341: Contextmenuitem Class

    Menu items are compared without regard to case, punctuation, or white space. None of the following words can appear in a custom item: Macromedia, Flash Player, or Settings. Method summary for the ContextMenuItem class...
  • Page 342 Property summary for the ContextMenuItem class Property Description Specifies the text displayed in the menu item. ContextMenuItem.caption Specifies whether the menu item is enabled or disabled. ContextMenuItem.enabled Specifies whether a separator bar should appear above the ContextMenuItem.separatorBefore menu item. Specifies whether the menu item is visible or not. ContextMenuItem.visible Event handler summary for the ContextMenuItem class Event handler...
  • Page 343 my_cm = new ContextMenu(); my_cm.customItems.push(new ContextMenuItem("Start", startHandler)); my_cm.customItems.push(new ContextMenuItem("Stop", stopHandler, true)); function stopHandler(obj, item) { trace("Stopping..."); function startHandler(obj, item) { trace("Starting..."); _root.menu = my_cm; ContextMenuItem.caption Availability Flash Player 7. Usage menuItem_cmi.caption Description Property; a string that specifies the menu item caption (text) displayed in the context menu. Example This example displays the caption for the selected menu item (Pause Game) in the Output panel.
  • Page 344 Example This example creates a new ContextMenuItem object named with the caption text original_cmi Pause and a callback handler set to the function . The example then creates a copy of the onPause ContextMenuItem object and assigns it to the variable copy_cmi original_cmi = new ContextMenuItem("Pause", onPause);...
  • Page 345 Description Event handler; invoked when the specified menu item is selected from the Flash Player context menu. The specified callback handler receives two parameters: , a reference to the object under the mouse when the user invoked the Flash Player context menu, and menuItem reference to the ContextMenuItem object that represents the selected menu item.
  • Page 346 ContextMenuItem.visible Availability Flash Player 7. Usage menuItem_cmi.visible Description Property; a Boolean value that indicates whether the specified menu item is visible when the Flash Player context menu is displayed. By default, this property is true continue Availability Flash Player 4. Usage continue Parameters...
  • Page 347: Customactions Class

    CustomActions class Availability Flash Player 6. Description The methods of the CustomActions class allow a SWF file playing in the Flash authoring tool to manage any custom actions that are registered with the authoring tool. A SWF file can install and uninstall custom actions, retrieve the XML definition of a custom action, and retrieve the list of registered custom actions.
  • Page 348 CustomActions.install() Availability Flash Player 6. Usage CustomActions.install(customActionsName, customXMLDefinition) Parameters The name of the custom action definition to install. customActionsName The text of the XML definition to install. customXMLDefinition Returns A Boolean value of if an error occurs during installation; otherwise, a value of false true returned to indicate that the custom action has been successfully installed.
  • Page 349: Date Class

    CustomActions.uninstall() Availability Flash Player 6. Usage CustomActions.uninstall(customActionsName) Parameters The name of the custom action definition to uninstall. customActionsName Returns A Boolean value of if no custom actions are found with the name . If false customActionsName the custom actions were successfully removed, a value of is returned.
  • Page 350 Flash Player 5 handles daylight saving time on the following operating systems as follows: • Windows—the U.S. rules for daylight saving time are always applied, which leads to incorrect transitions in Europe and other areas that employ daylight saving time but have different transition times than the U.S.
  • Page 351 Method Description Sets the milliseconds according to local time. Returns the new time Date.setMilliseconds() in milliseconds. Sets the minutes according to local time. Returns the new time Date.setMinutes() in milliseconds. Sets the month according to local time. Returns the new time Date.setMonth() in milliseconds.
  • Page 352 An integer from 1 to 31. This parameter is optional. date An integer from 0 (midnight) to 23 (11 p.m.). hour An integer from 0 to 59. This parameter is optional. minute An integer from 0 to 59. This parameter is optional. second An integer from 0 to 999.
  • Page 353 Date.getDay() Availability Flash Player 5. Usage my_date.getDay() Parameters None. Returns An integer. Description Method; returns the day of the week (0 for Sunday, 1 for Monday, and so on) of the specified Date object according to local time. Local time is determined by the operating system on which Flash Player is running.
  • Page 354 Date.getHours() Availability Flash Player 5. Usage my_date.getHours() Parameters None. Returns An integer. Description Method; returns the hour (an integer from 0 to 23) of the specified Date object, according to local time. Local time is determined by the operating system on which Flash Player is running. Date.getMilliseconds() Availability Flash Player 5.
  • Page 355 Returns An integer. Description Method; returns the minutes (an integer from 0 to 59) of the specified Date object, according to local time. Local time is determined by the operating system on which Flash Player is running. Date.getMonth() Availability Flash Player 5. Usage my_date.getMonth() Parameters...
  • Page 356 Date.getTime() Availability Flash Player 5. Usage my_date.getTime() Parameters None. Returns An integer. Description Method; returns the number of milliseconds since midnight January 1, 1970, universal time, for the specified Date object. Use this method to represent a specific instant in time when comparing two or more Date objects.
  • Page 357 Date.getUTCDate() Availability Flash Player 5. Usage my_date.getUTCDate() Parameters None. Returns An integer. Description Method; returns the day of the month (an integer from 1 to 31) in the specified Date object, according to universal time. Date.getUTCDay() Availability Flash Player 5. Usage my_date.getUTCDay() Parameters...
  • Page 358 Date.getUTCFullYear() Availability Flash Player 5. Usage my_date.getUTCFullYear() Parameters None. Returns An integer. Description Method; returns the four-digit year of the specified Date object, according to universal time. Date.getUTCHours() Availability Flash Player 5. Usage my_date.getUTCHours() Parameters None. Returns An integer. Description Method;...
  • Page 359 Date.getUTCMilliseconds() Availability Flash Player 5. Usage my_date.getUTCMilliseconds() Parameters None. Returns An integer. Description Method; returns the milliseconds of the specified Date object, according to universal time. Date.getUTCMinutes() Availability Flash Player 5. Usage my_date.getUTCMinutes() Parameters None. Returns An integer. Description Method; returns the minutes of the specified Date object, according to universal time. Date.getUTCMinutes()
  • Page 360 Date.getUTCMonth() Availability Flash Player 5. Usage my_date.getUTCMonth() Parameters None. Returns An integer. Description Method; returns the month (0 for January, 1 for February, and so on) of the specified Date object, according to universal time. Date.getUTCSeconds() Availability Flash Player 5. Usage my_date.getUTCSeconds() Parameters...
  • Page 361 Description Method; returns the year of the specified Date object, according to local time. Local time is determined by the operating system on which Flash Player is running. The year is the full year minus 1900. For example, the year 2000 is represented as 100. See also Date.getFullYear() Date.setDate()
  • Page 362 Description Method; sets the year of the specified Date object, according to local time, and returns the new time in milliseconds. If the parameters are specified, they are also set to local month date time. Local time is determined by the operating system on which Flash Player is running. Calling this method does not modify the other fields of the specified Date object but may report a new value if the day of the week changes Date.getUTCDay()
  • Page 363 Date.setMinutes() Availability Flash Player 5. Usage my_date.setMinutes(minute) Parameters An integer from 0 to 59. minute Returns An integer. Description Method; sets the minutes for a specified Date object according to local time, and returns the new time in milliseconds. Local time is determined by the operating system on which Flash Player is running.
  • Page 364 Date.setSeconds() Availability Flash Player 5. Usage my_date.setSeconds(second) Parameters An integer from 0 to 59. second Returns An integer. Description Method; sets the seconds for the specified Date object in local time, and returns the new time in milliseconds. Local time is determined by the operating system on which Flash Player is running.
  • Page 365 Date.setUTCDate() Availability Flash Player 5. Usage my_date.setUTCDate(date) Parameters An integer from 1 to 31. date Returns An integer. Description Method; sets the date for the specified Date object in universal time, and returns the new time in milliseconds. Calling this method does not modify the other fields of the specified Date object, may report a new value if the day of the week Date.getUTCDay() Date.getDay()
  • Page 366 Date.setUTCHours() Availability Flash Player 5. Usage my_date.setUTCHours(hour [, minute [, second [, millisecond]]]) Parameters An integer from 0 (midnight) to 23 (11 p.m.). hour An integer from 0 to 59. This parameter is optional. minute An integer from 0 to 59. This parameter is optional. second An integer from 0 to 999.
  • Page 367 Date.setUTCMinutes() Availability Flash Player 5. Usage my_date.setUTCMinutes(minute [, second [, millisecond]]) Parameters An integer from 0 to 59. minute An integer from 0 to 59. This parameter is optional. second An integer from 0 to 999. This parameter is optional. millisecond Returns An integer.
  • Page 368 Date.setUTCSeconds() Availability Flash Player 5. Usage my_date.setUTCSeconds(second [, millisecond])) Parameters An integer from 0 to 59. second An integer from 0 to 999. This parameter is optional. millisecond Returns An integer. Description Method; sets the seconds for the specified Date object in universal time, and returns the new time in milliseconds.
  • Page 369 Date.toString() Availability Flash Player 5. Usage my_date.toString() Parameters None. Returns A string. Description Method; returns a string value for the specified date object in a readable format, and returns the new time in milliseconds. Example The following example returns the information in the Date object as a string.
  • Page 370 Description Method; returns the number of milliseconds between midnight on January 1, 1970, universal time, and the time specified in the parameters. This is a static method that is invoked through the Date object constructor, not through a specific Date object. This method lets you create a Date object that assumes universal time, whereas the Date constructor assumes local time.
  • Page 371 delete Availability Flash Player 5. Usage delete reference Parameters The name of the variable or object to eliminate. reference Returns A Boolean value. Description Operator; destroys the object or variable specified by the parameter, and returns reference true if the object was successfully deleted; otherwise returns a value of .
  • Page 372 delete array[2]; trace(my_array.length); Usage 4: The following example illustrates the behavior of on object references. delete // create a new object, and assign the variable ref1 // to refer to the object ref1 = new Object(); ref1.name = "Jody"; // copy the reference variable into a new variable // and delete ref1 ref2 = ref1;...
  • Page 373 duplicateMovieClip() Availability Flash Player 4. Usage duplicateMovieClip(target, newname, depth) Parameters The target path of the movie clip to duplicate. target A unique identifier for the duplicated movie clip. newname A unique depth level for the duplicated movie clip. The depth level is a stacking order for depth duplicated movie clips.
  • Page 374 Description Keyword; specifies that objects based on the specified class can add and access dynamic properties at runtime. Type checking on dynamic classes is less strict than type-checking on nondynamic classes, because members accessed inside the class definition and on class instances are not compared to those defined in the class scope.
  • Page 375 else Availability Flash Player 4. Usage if (condition){ statement(s); } else (condition){ statement(s); Parameters An expression that evaluates to condition true false An alternative series of statements to run if the condition specified in the statement(s) statement is false Returns Nothing.
  • Page 376 Description Statement; evaluates a condition and specifies the statements to run if the condition in the initial statement returns . If the condition returns , the Flash interpreter runs the false else if true statements that follow the condition inside curly braces ( ).
  • Page 377: Error Class

    See also #initclip eq (equal — string specific) Availability Flash Player 4. This operator was deprecated in Flash 5 in favor of the operator. == (equality) Usage expression1 eq expression2 Parameters Numbers, strings, or variables. expression1, expression2 Returns Nothing. Description Comparison operator;...
  • Page 378 Constructor for the Error class Availability Flash Player 7. Usage new Error([message]) Parameters A string associated with the Error object; this parameter is optional. message Returns Nothing. Description Constructor; creates a new Error object. If is specified, its value is assigned to the object’s message property.
  • Page 379 Error.name Availability Flash Player 7. Usage myError.name Description Property; contains the name of the Error object. By default, the value of this property is "Error" See also throw try..catch..finally Error.toString() Availability Flash Player 7. Usage my_err.toString() Returns A string. Description Method;...
  • Page 380 Example Running the following code gives the result, Hello%7B%5BWorld%5D%7D " escape("Hello{[World]} See also unescape eval() Availability Flash Player 5 or later for full functionality. You can use the function when exporting to eval() Flash Player 4, but you must use slash notation, and can only access variables, not properties or objects.
  • Page 381 Example The following example uses to determine the value of the expression eval() "piece" + x Because the result is a variable name, returns the value of the variable and assigns piece3 eval() it to piece3 = "dangerous"; x = 3; y = eval("piece"...
  • Page 382 Example In class B as defined below, a call to class A’s constructor will automatically be inserted as the first statement of B’s constructor function, because a call does not already exist there. (That is, it is commented out in the example.) class B extends class A function B() { // this is the constructor super();...
  • Page 383 Availability Flash Player 5. Usage for(init; condition; next) { statement(s); Parameters An expression to evaluate before beginning the looping sequence, typically an assignment init expression. A statement is also permitted for this parameter. An expression that evaluates to . The condition is evaluated before condition true false...
  • Page 384 The following is an example of using to perform the same action repeatedly. In the following code, the loop adds the numbers from 1 to 100: var sum = 0; for (var i=1; i<=100; i++) { sum = sum + i; See also ++ (increment) ––...
  • Page 385 Function; allows the SWF file to communicate with either Flash Player or the program hosting Flash Player, such as a web browser. You can also use the action to pass messages to fscommand Macromedia Director, or to Visual Basic, Visual C++, and other programs that can host ActiveX controls. fscommand()
  • Page 386 Usage 3: The action can send messages to Macromedia Director that are interpreted fscommand by Lingo as strings, events, or executable Lingo code. If the message is a string or an event, you must write the Lingo code to receive the message from the...
  • Page 387 Example Usage 1: In the following example, the action sets the Flash Player to scale the SWF fscommand file to the full monitor screen size when the button is released. on(release){ fscommand("fullscreen", true); Usage 2: The following example uses the action applied to a button in Flash to open a fscommand JavaScript message box in an HTML page.
  • Page 388 function Availability Flash Player 5. Usage function functionname ([parameter0, parameter1,...parameterN]){ statement(s) function ([parameter0, parameter1,...parameterN]){ statement(s) Parameters The name of the new function. functionname An identifier that represents a parameter to pass to the function. These parameters parameter are optional. Any ActionScript instruction you have defined for the body of the statement(s) function Returns...
  • Page 389: Function Class

    Usage 2: The following function defines a Circle object: function Circle(radius) { this.radius = radius; The following statement defines an anonymous function that calculates the area of a circle and attaches it to the object as a method: Circle Circle.prototype.area = function () {return Math.PI * this.radius * this.radius} Function class Availability...
  • Page 390 Example The following function invocations are equivalent: Math.atan2(1, 0) Math.atan2.apply(null, [1, 0]) You could construct a SWF file that contains input entry fields that permit the user to enter the name of a function to invoke, and zero or more parameters to pass to the function. Pressing a “Call”...
  • Page 391 In almost all cases, the function call operator ( ) can be used instead of this method. The function call operator produces code that is concise and readable. This method is primarily useful when the parameter of the function invocation needs to be explicitly controlled. Normally, this if a function is invoked as a method of an object, within the body of the function, is set to...
  • Page 392 ge (greater than or equal to — string specific) Availability Flash Player 4. This operator was deprecated in Flash 5 in favor of the >= (greater than or equal operator. Usage expression1 ge expression2 Parameters Numbers, strings, or variables. expression1 expression2 Returns Nothing.
  • Page 393 See also Object.addProperty(), getProperty Availability Flash Player 4. Usage getProperty(my_mc, property) Parameters The instance name of a movie clip for which the property is being retrieved. my_mc A property of a movie clip. property Returns The value of the specified property. Description Function;...
  • Page 394 getURL() Availability Flash 2. The options are only available to Flash Player 4 and later versions of POST the player. Usage getURL(url [, window [, "variables"]]) Parameters The URL from which to obtain the document. An optional parameter specifying the window or HTML frame that the document window should load into.
  • Page 395 getVersion Availability Flash Player 5. Usage getVersion() Parameters None. Returns A string containing Flash Player version and platform information. Description Function; returns a string containing Flash Player version and platform information. function only returns information for Flash Player 5 or later versions of getVersion the Player.
  • Page 396 Description Identifier; creates global variables, objects, or classes. For example, you could create a library that is exposed as a global ActionScript object, much like the Math or Date object. Unlike Timeline- declared or locally declared variables and functions, global variables and functions are visible to every Timeline and scope in the SWF file, provided they are not obscured by identifiers with the same names in inner scopes.
  • Page 397 gotoAndStop() Availability Flash 2. Usage gotoAndStop([scene,] frame) Parameters An optional string specifying the name of the scene to which the playhead is sent. scene A number representing the frame number, or a string representing the label of the frame, frame to which the playhead is sent.
  • Page 398 _highquality Availability Flash Player 4; deprecated in favor of _quality Usage _highquality Description Deprecated property (global); specifies the level of anti-aliasing applied to the current SWF file. Specify 2 (best quality) to apply high quality with bitmap smoothing always on. Specify 1 (high quality) to apply anti-aliasing;...
  • Page 399 // how far they travelled with it xInc = xTravel/2; yInc = yTravel/2; timePressed = 0; See also else ifFrameLoaded Availability Flash Player 3. The action was deprecated in Flash 5; Macromedia recommends ifFrameLoaded using the property. MovieClip._framesloaded Usage ifFrameLoaded([scene,] frame) { statement(s); Parameters An optional string specifying the name of the scene that must be loaded.
  • Page 400 Description Deprecated action; checks whether the contents of a specific frame are available locally. Use to start playing a simple animation while the rest of the SWF file downloads to ifFrameLoaded the local computer. The difference between using is that _framesloaded ifFrameLoaded allows you to add your own...
  • Page 401 Description Keyword; lets you access classes without specifying their fully qualified names. For example, if you want to use the class macr.util.users.UserClass.as in a script, you must either refer to it by its fully qualified name or import it; if you import it, you can then refer to it by the class name: // before importing var myUser:UserClass = new macr.util.users.UserClass();...
  • Page 402 Description Compiler directive: includes the contents of the specified file, as if the commands in the file were part of the calling script itself. The directive is invoked at compile time. Therefore, if #include you make any changes to an external file, you must save the file and recompile any FLA files that use it.
  • Page 403 Infinity Availability Flash Player 5. Usage Infinity Description Constant; specifies the IEEE-754 value representing positive infinity. The value of this constant is the same as Number.POSITIVE_INFINITY -Infinity Availability Flash Player 5. Usage -Infinity Description Constant; specifies the IEEE-754 value representing negative infinity. The value of this constant is the same as Number.NEGATIVE_INFINITY #initclip...
  • Page 404 instanceof Availability Flash Player 6. Usage object instanceof class Parameters An ActionScript object. object A reference to an ActionScript constructor function, such as String or Date. class Returns is an instance of returns ; otherwise, returns object class instanceof true instanceof .
  • Page 405 See also Math.floor() interface Availability Flash Player 6. Usage interface InterfaceName {} interface InterfaceName [extends InterfaceName [, InterfaceName ...] {} Note: To use this keyword, you must specify ActionScript 2.0 and Flash Player 6 or later in the Flash tab of your FLA file’s Publish Settings dialog box. This keyword is supported only when used in external script files, not in scripts written in the Actions panel.
  • Page 406 } // error: class must implement all interface methods // filename Ib.as interface Ib function o():Void; class D implements Ia, Ib function k():Number {return 15;} function n(x:Number):Number {return x*x;} function o():Void {trace("o");} // external script or Actions panel mvar = new D(); trace(D.k());...
  • Page 407 Example The following are examples of return values for isFinite isFinite(56) // returns true isFinite(Number.POSITIVE_INFINITY) // returns false isNaN() Availability Flash Player 5. Usage isNaN(expression) Parameters A Boolean, variable, or other expression to be evaluated. expression Returns A Boolean value. Description Function;...
  • Page 408: Key Class

    Key class Availability Flash Player 6. Description The Key class is a top-level class whose methods and properties you can use without using a constructor. Use the methods of the Key class to build an interface that can be controlled by a user with a standard keyboard.
  • Page 409 Property Description Constant associated with the key code value for the Right Arrow key (39). Key.RIGHT Constant associated with the key code value for the Shift key (16). Key.SHIFT Constant associated with the key code value for the Spacebar (32). Key.SPACE Constant associated with the key code value for the Tab key (9).
  • Page 410 The following example assigns the keyboard shortcut Control+7 to a button with an instance name of myButton, and makes information about the shortcut available to screen readers (see _accProps). In this example, when you press Control+7 the function displays the text myOnPress "hello"...
  • Page 411 Key.CONTROL Availability Flash Player 5. Usage Key.CONTROL Description Property; constant associated with the key code value for the Control key (17). Key.DELETEKEY Availability Flash Player 5. Usage Key.DELETEKEY Description Property; constant associated with the key code value for the Delete key (46). Key.DOWN Availability Flash Player 5.
  • Page 412 Key.ENTER Availability Flash Player 5. Usage Key.ENTER Description Property; constant associated with the key code value for the Enter key (13). Key.ESCAPE Availability Flash Player 5. Usage Key.ESCAPE Description Property; constant associated with the key code value for the Escape key (27). Key.getAscii() Availability Flash Player 5.
  • Page 413 Key.getCode() Availability Flash Player 5. Usage Key.getCode(); Parameters None. Returns An integer that represents the key code of the last key pressed. Description Method; returns the key code value of the last key pressed. To match the returned key code value with the key on a standard keyboard, see Appendix C, “Keyboard Keys and Key Code Values,”...
  • Page 414 Key.isDown() Availability Flash Player 5. Usage Key.isDown(keycode) Parameters The key code value assigned to a specific key, or a Key class property associated with a keycode specific key. To match the returned key code value with the key on a standard keyboard, see Appendix C, “Keyboard Keys and Key Code Values,”...
  • Page 415 Key.LEFT Availability Flash Player 5. Usage Key.LEFT Description Property; constant associated with the key code value for the Left Arrow key (37). Key.onKeyDown Availability Flash Player 6. Usage someListener.onKeyDown Description Listener; notified when a key is pressed. To use you must create a listener object. You onKeyDown can then define a function for and use...
  • Page 416 Listeners enable different pieces of code to cooperate because multiple listeners can receive notification about a single event. See also Key.addListener() Key.PGDN Availability Flash Player 5. Usage Key.PGDN Description Property; constant associated with the key code value for the Page Down key (34). Key.PGUP Availability Flash Player 5.
  • Page 417 Key.RIGHT Availability Flash Player 5. Usage Key.RIGHT Description Property; constant associated with the key code value for the Right Arrow key (39). Key.SHIFT Availability Flash Player 5. Usage Key.SHIFT Description Property; constant associated with the key code value for the Shift key (16). Key.SPACE Availability Flash Player 5.
  • Page 418 <= (less than or equal to) length Availability Flash Player 4. This function, along with all of the string functions, was deprecated in Flash 5. Macromedia recommends using the methods of the String class and the property String.length to perform the same operations.
  • Page 419 Returns The length of the specified string or variable name. Description String function; returns the length of the specified string or variable name. Example The following example returns the value of the string "Hello" length("Hello"); The result is 5. See also String class, "...
  • Page 420 loadMovie() Availability Flash Player 3. Usage loadMovie("url",target [, method]) Parameters The absolute or relative URL of the SWF file or JPEG file to be loaded. A relative path must be relative to the SWF file at level 0. Absolute URLs must include the protocol reference, such as http:// or file:///.
  • Page 421 Example The following statement is attached to a navigation button labeled Products. There loadMovie() is an invisible movie clip on the Stage with the instance name . The dropZone loadMovie() function uses this movie clip as the target parameter to load the products in the SWF file into the correct position on the Stage.
  • Page 422 If you want to specify a target instead of a level, use instead of loadMovie() loadMovieNum() Flash Player has a stacking order of levels starting with level 0. These levels are like layers of acetate; they are transparent except for the objects on each level. When you use loadMovieNum() you must specify a level in Flash Player into which the SWF file will load.
  • Page 423 (a standard format used by CGI scripts). Any number of variables can be specified. For example, the following phrase defines several variables: company=Macromedia&address=600+Townsend&city=San+Francisco&zip=94103 In SWF files running in a version of the player earlier than Flash Player 7, must be in the same superdomain as the SWF file that is issuing this call.
  • Page 424 (a standard format used by CGI scripts). Any number of variables can be specified. For example, the following phrase defines several variables: company=Macromedia&address=600+Townsend&city=San+Francisco&zip=94103 In SWF files running in a version of the player earlier than Flash Player 7, must be in the same superdomain as the SWF file that is issuing this call.
  • Page 425: Loadvars Class

    LoadVars class Availability Flash Player 6. Description The LoadVars class is an alternative to the function for transferring variables loadVariables() between a Flash application and a server. You can use the LoadVars class to obtain verification of successful data loading, progress indications, and stream data while it downloads.
  • Page 426 Constructor for the LoadVars class Availability Flash Player 6. Usage new LoadVars() Parameters None. Returns Nothing. Description Constructor; creates a LoadVars object. You can then use the methods of that LoadVars object to send and load data. Example The following example creates a LoadVars object called my_lv var my_lv = new LoadVars();...
  • Page 427 The following standard HTTP headers cannot be added or changed with this method: Accept- Ranges Allow Allowed Connection Content-Length Content-Location Content- Range ETag Host Last-Modified Locations Max-Forwards Proxy-Authenticate Proxy- Authorization Public Range Retry-After Server Trailer Transfer-Encoding , and Upgrade Vary Warning WWW-Authenticate Example...
  • Page 428 LoadVars.getBytesLoaded() Availability Flash Player 6. Usage my_lv.getBytesLoaded() Parameters None. Returns An integer. Description Method; returns the number of bytes downloaded by LoadVars.load() . This method returns if no load operation is in progress, LoadVars.sendAndLoad() undefined or if a load operation has not yet begun. LoadVars.getBytesTotal() Availability Flash Player 6.
  • Page 429 LoadVars.load() Availability Flash Player 6; behavior changed in Flash Player 7. Usage my_lv.load(url) Parameters The URL from which to download the variables. If the SWF file issuing this call is running in a web browser, must be in the same domain as the SWF file; for details, see “Description,”...
  • Page 430 LoadVars.loaded Availability Flash Player 6. Usage my_lv.loaded Description Property; undefined by default. When a LoadVars.load() LoadVars.sendAndLoad() operation is started, the property is set to ; when the operation completes, the loaded false property is set to . If the operation has not yet completed or has failed with an error, loaded true property remains set to...
  • Page 431 LoadVars.onLoad Availability Flash Player 6. Usage my_lv.onLoad = function(success) { // your statements here Parameters The parameter indicates whether the load operation ended in success ( ) or success true failure ( false Returns A Boolean value. Description Event handler; invoked when a operation has LoadVars.load() LoadVars.sendAndLoad()
  • Page 432 LoadVars.send() Availability Flash Player 6. Usage my_lv.send(url [,target method]) Parameters The URL to upload variables to. The browser frame window in which any response will be displayed. target method of the HTTP protocol. method POST Returns A string. Description Method; sends the variables in the object to the specified URL.
  • Page 433 Description Method; posts variables in the object to the specified URL. The server response my_lv is downloaded, parsed as variable data, and the resulting variables are placed in the object. targetObject Variables are posted in the same manner as . Variables are downloaded into LoadVars.send() in the same manner as targetObject...
  • Page 434: Localconnection Class

    LocalConnection class Availability Flash Player 6. Description The LocalConnection class lets you develop SWF files that can send instructions to each other without the use of or JavaScript. LocalConnection objects can communicate only fscommand() between SWF files that are running on the same client machine, but they can be running in two different applications—for example, a SWF file running in a browser and a SWF file running in a projector.
  • Page 435 Event handler summary for the LocalConnection class Event handler Description Invoked whenever the current (receiving) LocalConnection.allowDomain LocalConnection object receives a request to invoke a method from a sending LocalConnection object. Invoked whenever the current (receiving) LocalConnection.allowInsecureDomain LocalConnection object, which is in a SWF file hosted at a domain using a secure protocol (HTTPS), receives a request to invoke a method from a sending LocalConnection object that is in a SWF file that is...
  • Page 436 LocalConnection.allowDomain Availability Flash Player 6; behavior changed in Flash Player 7. Usage receiving_lc.allowDomain = function([sendingDomain]) { // Your statements here return true or false Parameters An optional parameter specifying the domain of the SWF file containing the sendingDomain sending LocalConnection object. Returns Nothing.
  • Page 437 Example The following example shows how a LocalConnection object in a receiving SWF file can permit SWF files from any domain to invoke its methods. Compare this to the example in , in which only SWF files from the same domain can invoke the LocalConnection.connect() method in the receiving SWF file.
  • Page 438 Description Event handler; invoked whenever , which is in a SWF file hosted at a domain receiving_lc using a secure protocol (HTTPS), receives a request to invoke a method from a sending LocalConnection object that is in a SWF file that is hosted at a nonsecure protocol. Flash expects the code you implement in this handler to return a Boolean value of .
  • Page 439 LocalConnection.connect() Availability Flash Player 6. Usage receiving_lc.connect(connectionName) Parameters A string that corresponds to the connection name specified in the connectionName command that wants to communicate with LocalConnection.send() receiving_lc Returns A Boolean value of if no other process running on the same client machine has already true issued this command using the same value for the parameter,...
  • Page 440 Example The following example shows how a SWF file in a particular domain can invoke a method named in a receiving SWF file in the same domain. The receiving SWF file functions as a trace Trace window for the sending SWF file; it contains two methods that other SWF files can call— .
  • Page 441 Method; returns a string representing the domain of the location of the current SWF file. In SWF files published for Flash Player 6, the returned string is the superdomain of the current SWF file. For example, if the SWF file is located at www.macromedia.com, this command returns "macromedia.com"...
  • Page 442 Line numbers are included for reference purposes. The sequence of events is as follows: • The receiving SWF file prepares to receive commands on a connection named (line 11). "sum" The Flash Player resolves the name of this connection to (see "mydomain.com:sum"...
  • Page 443 LocalConnection.onStatus Availability Flash Player 6. Usage sending_lc.onStatus = function(infoObject) { // your statements here Parameters A parameter defined according to the status message. For details about this infoObject parameter, see “Description,” below. Returns Nothing. Description Event handler; invoked after a sending LocalConnection object tries to send a command to a receiving LocalConnection object.
  • Page 444 See also System.onStatus LocalConnection.send() LocalConnection.send() Availability Flash Player 6. Usage sending_lc.send (connectionName, method [, p1,...,pN]) Parameters A string that corresponds to the connection name specified in the connectionName command that wants to communicate with LocalConnection.connect() sending_lc A string specifying the name of the method to be invoked in the receiving method LocalConnection object.
  • Page 445: Math Class

    • Include the superdomain in in the sending LocalConnection object—for connectionName example, . In the receiving object, use myDomain.com:myConnectionName to specify that connections from the specified superdomain LocalConnection.allowDomain will be accepted (in this case, myDomain.com), or that connections from any domain will be accepted.
  • Page 446 Use the methods and properties of this class to access and manipulate mathematical constants and functions. All of the properties and methods of the Math class are static, and must be called using the syntax . In ActionScript, constants are defined Math.method(parameter) Math.constant with the maximum precision of double-precision IEEE-754 floating-point numbers.
  • Page 447 Property summary for the Math class All of the properties for the Math class are constants. Property Description Euler's constant and the base of natural logarithms (approximately 2.718). Math.E The natural logarithm of 2 (approximately 0.693). Math.LN2 The base 2 logarithm of e (approximately 1.442). Math.LOG2E The natural logarithm of 10 (approximately 2.302).
  • Page 448 Returns Nothing. Description Method; computes and returns the arc cosine of the number specified in the parameter in radians. Math.asin() Availability Flash Player 5. In Flash Player 4, the methods and properties of the Math class are emulated using approximations and may not be as accurate as the non-emulated math functions supported by Flash Player 5.
  • Page 449 Math.atan2() Availability Flash Player 5. In Flash Player 4, the methods and properties of the Math class are emulated using approximations and may not be as accurate as the non-emulated math functions supported by Flash Player 5. Usage Math.atan2(y, x) Parameters A number specifying the x coordinate of the point.
  • Page 450 Math.cos() Availability Flash Player 5. In Flash Player 4, the methods and properties of the Math class are emulated using approximations and may not be as accurate as the non-emulated math functions supported by Flash Player 5. Usage Math.cos(x) Parameters An angle measured in radians.
  • Page 451 Math.exp() Availability Flash Player 5. In Flash Player 4, the methods and properties of the Math class are emulated using approximations and may not be as accurate as the non-emulated math functions supported by Flash Player 5. Usage Math.exp(x) Parameters The exponent;...
  • Page 452 Math.log() Availability Flash Player 5. In Flash Player 4, the methods and properties of the Math class are emulated using approximations and may not be as accurate as the non-emulated math functions supported by Flash Player 5. Usage Math.log(x) Parameters A number or expression with a value greater than 0.
  • Page 453 Math.LN10 Availability Flash Player 5. In Flash Player 4, the methods and properties of the Math class are emulated using approximations and may not be as accurate as the non-emulated math functions supported by Flash Player 5. Usage Math.LN10 Parameters None.
  • Page 454 Math.LOG10E Availability Flash Player 5. In Flash Player 4, the methods and properties of the Math class are emulated using approximations and may not be as accurate as the non-emulated math functions supported by Flash Player 5. Usage Math.LOG10E Parameters None.
  • Page 455 Math.min() Availability Flash Player 5. In Flash Player 4, the methods and properties of the Math class are emulated using approximations and may not be as accurate as the non-emulated math functions supported by Flash Player 5. Usage Math.min(x , y) Parameters A number or expression.
  • Page 456 Math.pow() Availability Flash Player 5. In Flash Player 4, the methods and properties of the Math class are emulated using approximations and may not be as accurate as the non-emulated math functions supported by Flash Player 5. Usage Math.pow(x , y) Parameters A number to be raised to a power.
  • Page 457 Math.round() Availability Flash Player 5. In Flash Player 4, the methods and properties of the Math class are emulated using approximations and may not be as accurate as the non-emulated math functions supported by Flash Player 5. Usage Math.round(x) Parameters A number.
  • Page 458 Parameters A number or expression greater than or equal to 0. Returns A number. Description Method; computes and returns the square root of the specified number. Math.SQRT1_2 Availability Flash Player 5. In Flash Player 4, the methods and properties of the Math class are emulated using approximations and may not be as accurate as the non-emulated math functions supported by Flash Player 5.
  • Page 459 Math.tan() Availability Flash Player 5. In Flash Player 4, the methods and properties of the Math class are emulated using approximations and may not be as accurate as the non-emulated math functions supported by Flash Player 5. Usage Math.tan(x) Parameters An angle measured in radians.
  • Page 460 Returns A string. Description String function; converts an ASCII code number to a multibyte character. See also String.fromCharCode() mblength Availability Flash Player 4. This function has been deprecated in favor of the String class. Usage mblength(string) Parameters A string. string Returns A number.
  • Page 461: Microphone Class

    mbsubstring Availability Flash Player 4. This function was deprecated in Flash 5 in favor of String.substr() Usage mbsubstring(value, index, count) Parameters The multibyte string from which to extract a new multibyte string. value The number of the first character to extract. index The number of characters to include in the extracted string, not including the count...
  • Page 462 Method Description Specifies the amount of sound required to activate Microphone.setSilenceLevel() the microphone. Specifies whether to use the echo suppression feature of Microphone.setUseEchoSuppression() the audio codec. Property summary for the Microphone class Property (read-only) Description The amount of sound the microphone is detecting. Microphone.activityLevel The amount by which the microphone boosts the signal Microphone.gain...
  • Page 463 Microphone.activityLevel Availability Flash Player 6. Usage activeMicrophone.activityLevel Description Read-only property; a numeric value that specifies the amount of sound the microphone is detecting. Values range from 0 (no sound is being detected) to 100 (very loud sound is being detected). The value of this property can help you determine a good value to pass to method.
  • Page 464 top = this._y; bottom = top; on (press) { startDrag(this, false, left, top, right, bottom); this._xscale = 100; this._yscale = 100; on (release, releaseOutside) { stopDrag(); g = (this._x-50)*2; _root.myMic.setGain(g); _root.txt_micgain = g; this._xscale = 100; this._yscale = 100; See also Microphone.setGain() Microphone.get() Availability...
  • Page 465 In general, you shouldn’t pass a value for ; simply use the method to index Microphone.get() return a reference to the default microphone. By means of the Microphone settings panel (discussed later in this section), the user can specify the default microphone Flash should use. If you pass a value for , you might be trying to reference a microphone other than the one the index...
  • Page 466 Example The following example lets the user specify the default microphone, then captures audio and plays it back locally. To avoid feedback, you may want to test this code while wearing headphones. System.showSettings(2); myMic = Microphone.get(); _root.attachAudio(myMic); See also Microphone.index Microphone.muted Microphone.names Microphone.onStatus...
  • Page 467 // Publish the microphone data by calling // the root function pubLive(). _root.pubLive(); // Play what is being published by calling // the root function playLive(). _root.playLive(); See also Microphone.get() Microphone.onStatus Microphone.name Availability Flash Player 6. Usage activeMicrophone.name Description Read-only property; a string that specifies the name of the current sound capture device, as returned by the sound capture hardware.
  • Page 468 Calling requires an extensive examination of the hardware, and it may take Microphone.names several seconds to build the array. In most cases, you can just use the default microphone. Example The following code returns information on the array of audio devices. allMicNames_array = Microphone.names;...
  • Page 469 trace(mode); See also Microphone.onActivity Microphone.setSilenceLevel() Microphone.onStatus Availability Flash Player 6. Usage activeMicrophone.onStatus = function(infoObject) { // your statements here Parameters A parameter defined according to the status message. infoObject Returns Nothing. Description Event handler; invoked when the user allows or denies access to the microphone. If you want to respond to this event handler, you must create a function to process the information object generated by the microphone.
  • Page 470 Microphone.rate Availability Flash Player 6. Usage activeMicrophone.rate Description Read-only property; the rate at which the microphone is capturing sound, in kHz. The default value is 8 kHz if your sound capture device supports this value. Otherwise, the default value is the next available capture level above 8 kHz that your sound capture device supports, usually 11 kHz.
  • Page 471 var myMic = Microphone.get(); if (myMic.gain > 55){ myMic.setGain(55); See also Microphone.gain Microphone.setUseEchoSuppression() Microphone.setRate() Availability Flash Player 6. Usage activeMicrophone.setRate(kHz) Parameters The rate at which the microphone should capture sound, in kHz. Acceptable values are 5, 8, 11, 22, and 44. The default value is 8 kHz if your sound capture device supports this value. Otherwise, the default value is the next available capture level above 8 kHz that your sound capture device supports, usually 11 kHz.
  • Page 472 Microphone.setSilenceLevel() Availability Flash Player 6. Usage activeMicrophone.setSilenceLevel(level [, timeout]) Parameters An integer that specifies the amount of sound required to activate the microphone and level invoke . Acceptable values range from 0 to 100. The default Microphone.onActivity(true) value is 10. An optional integer parameter that specifies how many milliseconds must elapse timeout without activity before Flash considers sound to have stopped and invokes...
  • Page 473 Example The following example changes the silence level based on the user’s input. The button has the following code attached: on (press) this.makeSilenceLevel(this.silenceLevel); function called by the button continues: makeSilenceLevel() function makeSilenceLevel(s) this.obj.setSilenceLevel(s); this.SyncMode(); this.silenceLevel= s; For more information, see the example for Camera.setMotionLevel() See also Microphone.activityLevel...
  • Page 474 Example The following example turns on echo suppression. my_mic.setUseEchoSuppression(true); See also Microphone.setGain() Microphone.useEchoSuppression() Microphone.silenceLevel() Availability Flash Player 6. Usage activeMicrophone.silenceLevel Description Read-only property; an integer that specifies the amount of sound required to activate the microphone and invoke . The default value is 10. Microphone.onActivity(true) Example See the example for...
  • Page 475 Microphone.useEchoSuppression() Availability Flash Player 6. Usage activeMicrophone.useEchoSuppression Description Read-only property; a Boolean value of if echo suppression is enabled, otherwise. The true false default value is unless the user has selected Reduce Echo in the Flash Player Microphone false Settings panel. Example The following example checks for echo suppression and turns it on if it is off.
  • Page 476: Mouse Class

    Frame 1 of your file, the command executes when the SWF file MMExecute() is loaded. For more information on the JSAPI, see www.macromedia.com/go/jsapi_info_en. Example The following command returns an array of objects in the library: var libe:Array = MMExecute("fl.getDocumentDOM().library.items;");...
  • Page 477 Mouse.addListener() Availability Flash Player 6. Usage Mouse.addListener (newListener) Parameters An object. newListener Returns Nothing. Description Method; registers an object to receive notifications of the , and onMouseDown onMouseMove listeners. onMouseUp parameter should contain an object with defined methods for the newListener , and listeners.
  • Page 478 Example The following code, attached to a movie clip on the main Timeline, hides the standard pointer, and sets the x and y positions of the movie clip instance to the x and y mouse customPointer_mc positions in the main Timeline. onClipEvent(enterFrame){ Mouse.hide();...
  • Page 479 Mouse.onMouseMove Availability Flash Player 6. Usage someListener.onMouseMove Parameters None. Returns Nothing. Description Listener; notified when the mouse moves. To use the listener, you must create a onMouseMove listener object. You can then define a function for and use onMouseMove addListener() register the listener with the Mouse object, as in the following code: someListener = new Object();...
  • Page 480 Listeners enable different pieces of code to cooperate because multiple listeners can receive notification about a single event. See also Mouse.addListener() Mouse.onMouseWheel Availability Flash Player 7 (Windows only). Usage someListener.onMouseWheel = function ( [ delta , scrollTarget ]) { // your statements here Parameters An optional number indicating how many lines should be scrolled for each notch the delta...
  • Page 481 Mouse.removeListener() Availability Flash Player 6. Usage Mouse.removeListener (listener) Parameters An object. listener Returns If the object was successfully removed, the method returns ; if the listener true listener not successfully removed (for example, if the was not on the Mouse object’s listener listener list), the method returns false...
  • Page 482: Movieclip Class

    MovieClip class Availability Flash Player 3. Description The methods for the MovieClip class provide the same functionality as actions that target movie clips. There are also additional methods that do not have equivalent actions in the Actions toolbox in the Actions panel. You do not need to use a constructor method to call the methods of the MovieClip class;...
  • Page 483 Method Description MovieClip.gotoAndPlay() Sends the playhead to a specific frame in the movie clip and plays the SWF file. Sends the playhead to a specific frame in the movie clip and MovieClip.gotoAndStop() stops the SWF file. Returns if bounding box of the specified movie clip MovieClip.hitTest() true intersects the bounding box of the target movie clip.
  • Page 484 Drawing method summary for the MovieClip class Method Description Begins drawing a fill on the Stage. MovieClip.beginFill() Begins drawing a gradient fill on the Stage. MovieClip.beginGradientFill() Removes all the drawing commands associated with a movie MovieClip.clear() clip instance. Draws a curve using the latest line style. MovieClip.curveTo() Ends the fill specified by MovieClip.endFill()
  • Page 485 Property Description Indicates whether a movie clip is included in tab ordering. MovieClip.tabEnabled Indicates the tab order of an object. MovieClip.tabIndex The target path of a movie clip instance. MovieClip._target The total number of frames in a movie clip instance. MovieClip._totalframes Indicates whether other buttons can receive mouse MovieClip.trackAsMenu...
  • Page 486 Event handler summary for the MovieClip class Event handler Description Invoked when all the data is loaded into a movie clip. MovieClip.onData Invoked while the pointer is outside the button; the mouse MovieClip.onDragOut button is pressed inside, and then rolls outside the button area. Invoked while the pointer is over the button;...
  • Page 487 MovieClip._alpha Availability Flash Player 4. Usage my_mc._alpha Description Property; the alpha transparency value of the movie clip specified by . Valid values are 0 my_mc (fully transparent) to 100 (fully opaque). The default value is 100. Objects in a movie clip with set to 0 are active, even though they are invisible.
  • Page 488 Example The following code attaches a microphone to a movie clip. my_mic = Microphone.get(); this.attachAudio(my_mic); The following example shows how you can use a Sound object to control the sound associated with an FLV file. // Clip is the instance name of the movie clip // that contains the video object "my_video".
  • Page 489 Example The following example attaches the symbol with the linkage identifier “circle” to the movie clip instance, which is on the Stage in the SWF file. on (release) { thing.attachMovie( "circle", "circle1", 2 ); See also , Object.registerClass(), MovieClip.removeMovieClip() MovieClip.unloadMovie() removeMovieClip() MovieClip.beginFill() Availability...
  • Page 490 MovieClip.beginGradientFill() Availability Flash Player 6. Usage my_mc.beginGradientFill(fillType, colors, alphas, ratios, matrix) Parameter Either the string or the string fillType "linear" "radial" An array of RGB hex color values to be used in the gradient (for example, red is colors 0xFF0000, blue is 0x0000FF, and so on). An array of alpha values for the corresponding colors in the array;...
  • Page 491 If a property does not exist then the remaining parameters are all required; the matrixType function fails if any of them are missing. This matrix scales, translates, rotates, and skews the unit gradient, which is defined at (-1,-1) and (1,1). •...
  • Page 492 Returns Nothing. Description Method; indicates the beginning of a new drawing path. If the first parameter is or if undefined, no parameters are passed, the path has no fill. If an open path exists (that is if the current drawing position does not equal the previous position specified in a method), and it has a fill moveTo()
  • Page 493 See also MovieClip.beginFill() MovieClip.endFill() MovieClip.lineStyle() MovieClip.lineTo() MovieClip.moveTo() MovieClip.clear() Availability Flash Player 6. Usage my_mc.clear() Parameters None. Returns Nothing. Description Method; removes all the graphics created during runtime using the movie clip draw methods, including line styles specified with . Shapes and lines that are manually MovieClip.lineStyle() drawn during authoring time (with the Flash drawing tools) are unaffected.
  • Page 494 MovieClip.createEmptyMovieClip() Availability Flash Player 6. Usage my_mc.createEmptyMovieClip(instanceName, depth) Parameters A string that identifies the instance name of the new movie clip. instanceName An integer that specifies the depth of the new movie clip. depth Returns A reference to the newly created movie clip. Description Method;...
  • Page 495 Description Method; creates a new, empty text field as a child of the movie clip specified by . You can my_mc to create text fields while a SWF file plays. The text field is positioned at createTextField() ) with dimensions .
  • Page 496 MovieClip._currentframe Availability Flash Player 4. Usage my_mc._currentframe Description Property (read-only); returns the number of the frame in which the playhead is located in the Timeline specified by my_mc Example The following example uses the property to direct the playhead of the movie clip _currentframe to advance five frames ahead of its current location.
  • Page 497 Example The following example draws a circle with a hairline point, solid blue line, and a solid red fill. _root.createEmptyMovieClip( "circle", 1 ); with ( _root.circle ) lineStyle( 0, 0x0000FF, 100 ); beginFill( 0xFF0000 ); moveTo( 500, 500 ); curveTo( 600, 500, 600, 400 ); curveTo( 600, 300, 500, 300 );...
  • Page 498 See also startDrag() MovieClip.duplicateMovieClip() Availability Flash Player 5. Usage my_mc.duplicateMovieClip(newname, depth [,initObject]) Parameters A unique identifier for the duplicate movie clip. newname A unique number specifying the depth at which the SWF file specified is to be placed. depth (Supported for Flash Player 6 and later.) An object containing properties with initObject which to populate the duplicated movie clip.
  • Page 499 MovieClip.enabled Availability Flash Player 6. Usage my_mc.enabled Description Property; a Boolean value that indicates whether a button movie clip is enabled. The default value . If is set to , the button movie clip’s callback methods and enabled true enabled false event handlers are no longer invoked, and the Over, Down, and Up frames are disabled.
  • Page 500 MovieClip.focusEnabled Availability Flash Player 6. Usage my_mc.focusEnabled Description Property; if the value is , a movie clip cannot receive input focus unless it is a undefined false button movie clip. If the property value is , a movie clip can receive input focusEnabled true focus even if it is not a button movie clip.
  • Page 501 Example The following example uses the property to start a SWF file when all the frames _framesloaded are loaded. If all the frames aren’t loaded, the property of the movie clip instance _xscale loader is increased proportionally to create a progress bar. if (_framesloaded >= _totalframes) { gotoAndPlay ("Scene 1", "start");...
  • Page 502 MovieClip.getBytesLoaded() Availability Flash Player 5. Usage my_mc.getBytesLoaded() Parameters None. Returns An integer indicating the number of bytes loaded. Description Method; returns the number of bytes that have already loaded (streamed) for the movie clip specified by . You can compare this value with the value returned by my_mc to determine what percentage of a movie clip has loaded.
  • Page 503 MovieClip.getDepth() Availability Flash Player 6. Usage my_mc.getDepth() Parameters None. Returns An integer. Description Method; returns the depth of a movie clip instance. For more information, see “Managing movie clip depths” on page 129. See also MovieClip.getInstanceAtDepth() MovieClip.getNextHighestDepth() MovieClip.swapDepths() MovieClip.getInstanceAtDepth() Availability Flash Player 7.
  • Page 504 MovieClip.getNextHighestDepth() Availability Flash Player 7. Usage my_mc.getNextHighestDepth() Parameters None. Returns An integer that reflects the next available depth index that would render above all other objects on the same level and layer within my_mc Description Method; lets you determine a depth value that you can pass to MovieClip.attachMovie() , or to ensure that...
  • Page 505 Note: You can’t specify a tab index value for static text in Flash. However, other products may do so; for example, Macromedia FlashPaper. The contents of the TextSnapshot object aren’t dynamic; that is, if the movie clip moves to a different frame, or is altered in some way (for example, objects in the movie clip are added or removed), the TextSnapshot object might not represent the current text in the movie clip.
  • Page 506 MovieClip.getURL() Availability Flash Player 5. Usage my_mc.getURL(URL [,window, variables]) Parameters The URL from which to obtain the document. An optional parameter specifying the name, frame, or expression that specifies the window window or HTML frame that the document is loaded into. You can also use one of the following reserved target names: specifies the current frame in the current window, specifies a...
  • Page 507 Description Method; converts the object from Stage (global) coordinates to the movie clip’s point (local) coordinates. Example The following example converts the global x and y coordinates of the object to the local point coordinates of the movie clip. onClipEvent(mouseMove) { point = new object();...
  • Page 508 Returns Nothing. Description Method; brings the playhead to the specified frame of this movie clip and stops it there. See also gotoAndStop() MovieClip._height Availability Flash Player 4. Usage my_mc._height Description Property; the height of the movie clip, in pixels. Example The following code example sets the height and width of a movie clip when the user clicks the mouse button.
  • Page 509 MovieClip.hitArea Availability Flash Player 6. Usage my_mc.hitArea Returns A reference to a movie clip. Description Property; designates another movie clip to serve as the hit area for a button movie clip. If the property does not exist or is , the button movie clip itself is used as hitArea null undefined...
  • Page 510 Usage 1: Compares the coordinates to the shape or bounding box of the specified instance, according to the setting. If is set to , only the area actually shapeFlag shapeFlag true occupied by the instance on the Stage is evaluated, and if overlap at any point, a value of is returned.
  • Page 511 Description Method; specifies a line style that Flash uses for subsequent calls to lineTo() curveTo() until you call with different parameters. You can call in the middle of lineStyle() lineStyle() drawing a path to specify different styles for different line segments within a path. Note: Calls to reset back to...
  • Page 512 Example The following example draws a triangle with no lines and a partially transparent blue fill. _root.createEmptyMovieClip ("triangle", 1); with (_root.triangle){ beginFill (0x0000FF, 50); lineStyle (5, 0xFF00FF, 100); moveTo (200, 200); lineTo (300, 300); lineTo (100, 300); lineTo (200, 200); endFill();...
  • Page 513 Use the method to remove SWF files or images loaded with the unloadMovie() loadMovie() method. Use the method to keep the active SWF file, and update the variables loadVariables() with new values. See also loadMovie() loadMovieNum() MovieClip.loadVariables() MovieClip.unloadMovie() unloadMovie() unloadMovieNum() MovieClip.loadVariables() Availability Flash Player 5;...
  • Page 514 See also loadMovie() loadVariables() loadVariablesNum() MovieClip.unloadMovie() MovieClip.localToGlobal() Availability Flash Player 5. Usage my_mc.localToGlobal(point) Parameters The name or identifier of an object created with the Object class, specifying the x and y point coordinates as properties. Returns Nothing. Description Method; converts the object from the movie clip’s (local) coordinates to the Stage point (global) coordinates.
  • Page 515 MovieClip._lockroot Availability Flash Player 7. Usage my_mc._lockroot Description Property; specifies what refers to when a SWF file is loaded into a movie clip. The _root property is by default. You can set this property within the SWF file that _lockroot undefined is being loaded or in the handler that is loading the movie clip.
  • Page 516 MovieClip.menu Availability Flash Player 7. Usage my_mc.menu = contextMenu Parameters A ContextMenu object. contextMenu Description Property; associates the specified ContextMenu object with the movie clip . The my_mc ContextMenu class lets you modify the context menu that appears when the user right-clicks (Windows) or Control-clicks (Macintosh) in Flash Player.
  • Page 517 Description Method; moves the current drawing position to ( ). If any of the parameters are missing, this method fails and the current drawing position is not changed. Example This example draws a triangle with 5-point, solid magenta lines and no fill. The first line creates an empty movie clip to draw with.
  • Page 518 MovieClip.onData Availability Flash Player 6. Usage my_mc.onData = function() { // your statements here Parameters None. Returns Nothing. Description Event handler; invoked when a movie clip receives data from a loadVariables() call. You must define a function that executes when the event handler is invoked. loadMovie() This handler can be used only with movie clips for which you have a symbol in the library that is associated with a class.
  • Page 519 See also onClipEvent() MovieClip.onDragOut Availability Flash Player 6. Usage my_mc.onDragOut = function() { // your statements here Parameters None. Returns Nothing. Description Event handler; invoked when the mouse button is pressed and the pointer rolls outside the object. You must define a function that executes when the event handler is invoked. Example The following example defines a function for the method that sends a...
  • Page 520 Description Event handler; invoked when the pointer is dragged outside and then over the movie clip. You must define a function that executes when the event handler is invoked. Example The following example defines a function for the method that sends a onDragOver trace() action to the Output panel.
  • Page 521 MovieClip.onKeyDown Availability Flash Player 6. Usage my_mc.onKeyDown = function() { // your statements here Parameters None. Returns Nothing. Description Event handler; invoked when a movie clip has input focus and a key is pressed. The onKeyDown event handler is invoked with no parameters. You can use the Key.getAscii() methods to determine which key was pressed.
  • Page 522 MovieClip.onKeyUp Availability Flash Player 6. Usage my_mc.onKeyUp = function() { // your statements here Parameters None. Returns Nothing. Description Event handler; invoked when a key is released. The event handler is invoked with no onKeyUp parameters. You can use the methods to determine which Key.getAscii() Key.getCode()
  • Page 523 MovieClip.onKillFocus Availability Flash Player 6. Usage my_mc.onKillFocus = function (newFocus) { // your statements here Parameters The object that is receiving the keyboard focus. newFocus Returns Nothing. Description Event handler; invoked when a movie clip loses keyboard focus. The method onKillFocus receives one parameter, , which is an object representing the new object receiving the...
  • Page 524 Example The following example illustrates the correct use of MovieClip.onLoad() onClipEvent(load) // symbol_mc is a movie clip symbol in the library. // It is linked to the MovieClip class. // The following function is triggered for each instance of symbol_mc as it is instantiated and appears on the Timeline.
  • Page 525 Example The following example defines a function for the method that sends a onMouseDown trace() action to the Output panel. my_mc.onMouseDown = function () { trace ("onMouseDown called"); MovieClip.onMouseMove Availability Flash Player 6. Usage my_mc.onMouseMove = function() { // your statements here Parameters None.
  • Page 526 MovieClip.onMouseUp Availability Flash Player 6. Usage my_mc.onMouseUp = function() { // your statements here Parameters None. Returns Nothing. Description Event handler; invoked when the mouse button is released. You must define a function that executes when the event handler is invoked. Example The following example defines a function for the method that sends a...
  • Page 527 Example The following example defines a function for the method that sends a action to onPress trace() the Output panel. my_mc.onPress = function () { trace ("onPress called"); MovieClip.onRelease Availability Flash Player 6. Usage my_mc.onRelease = function() { // your statements here Parameters None.
  • Page 528 Description Event handler; invoked when the mouse is released while the pointer is outside the movie clip after the mouse button is pressed inside the movie clip. You must define a function that executes when the event handler is invoked. Example The following example defines a function for the method that sends a...
  • Page 529 MovieClip.onRollOver Availability Flash Player 6. Usage my_mc.onRollOver = function() { // your statements here Parameters None. Returns Nothing. Description Event handler; invoked when the pointer moves over a movie clip area. You must define a function that executes when the event handler is invoked. Example The following example defines a function for the method that sends a...
  • Page 530 MovieClip.onUnload Availability Flash Player 6. Usage my_mc.onUnload = function() { // your statements here Parameters None. Returns Nothing. Description Event handler; invoked in the first frame after the movie clip is removed from the Timeline. Flash processes the actions associated with the event handler before attaching any actions to onUnload the affected frame.
  • Page 531 MovieClip.play() Availability Flash Player 5. Usage my_mc.play() Parameters None. Returns Nothing. Description Method; moves the playhead in the Timeline of the movie clip. See also play() MovieClip.prevFrame() Availability Flash Player 5. Usage my_mc.prevFrame() Parameters None. Returns Nothing. Description Method; sends the playhead to the previous frame and stops it. See also prevFrame() MovieClip.prevFrame()
  • Page 532 MovieClip.removeMovieClip() Availability Flash Player 5. Usage my_mc.removeMovieClip() Parameters None. Returns Nothing. Description Method; removes a movie clip instance created with duplicateMovieClip() MovieClip.duplicateMovieClip(), MovieClip.attachMovie() MovieClip._rotation Availability Flash Player 4. Usage my_mc._rotation Description Property; the rotation of the movie clip, in degrees, from its original orientation. Values from 0 to 180 represent clockwise rotation;...
  • Page 533 MovieClip.setMask() Availability Flash Player 6. Usage my_mc.setMask(mask_mc) Parameters The instance name of a movie clip to be masked. my_mc The instance name of a movie clip to be a mask. mask_mc Returns Nothing. Description Method; makes the movie clip in the parameter a mask that reveals the movie clip mask_mc specified by the...
  • Page 534 MovieClip.startDrag() Availability Flash Player 5. Usage my_mc.startDrag([lock, [left, top, right, bottom]]) Parameters A Boolean value specifying whether the draggable movie clip is locked to the center of the lock mouse position ( ), or locked to the point where the user first clicked on the movie clip true ).
  • Page 535 MovieClip.stopDrag() Availability Flash Player 5. Usage my_mc.stopDrag() Parameters None. Returns Nothing. Description Method; ends a method. A movie clip that was made draggable with MovieClip.startDrag() that method remains draggable until a method is added, or until another movie clip stopDrag() becomes draggable.
  • Page 536 See also _level MovieClip.getDepth() MovieClip.getInstanceAtDepth() MovieClip.getNextHighestDepth() MovieClip.tabChildren Availability Flash Player 6. Usage my_mc.tabChildren Description Property; by default. If , the children of a movie undefined tabChildren undefined true clip are included in automatic tab ordering. If the value of , the children of tabChildren false a movie clip are not included in automatic tab ordering.
  • Page 537 See also Button.tabEnabled MovieClip.tabChildren MovieClip.tabIndex TextField.tabEnabled MovieClip.tabIndex Availability Flash Player 6. Usage my_mc.tabIndex Description Property; lets you customize the tab ordering of objects in a movie. The property is tabIndex by default. You can set on a button, movie clip, or text field instance. undefined tabIndex If an object in a SWF file contains a...
  • Page 538 MovieClip._totalframes Availability Flash Player 4. Usage my_mc._totalframes Description Property (read-only); returns the total number of frames in the movie clip instance specified in parameter. MovieClip MovieClip.trackAsMenu Availability Flash Player 6. Usage my_mc.trackAsMenu Description Property; a Boolean property that indicates whether or not other buttons or movie clips can receive mouse release events.
  • Page 539 Description Method; removes the contents of a movie clip instance. The instance properties and clip handlers remain. To remove the instance, including its properties and clip handlers, use MovieClip.removeMovieClip() See also MovieClip.attachMovie() MovieClip.loadMovie() unloadMovie() unloadMovieNum() MovieClip._url Availability Flash Player 4. Usage my_mc _url...
  • Page 540 MovieClip._visible Availability Flash Player 4. Usage my_mc._visible Description Property; a Boolean value that indicates whether the movie clip specified by is visible. my_mc Movie clips that are not visible ( property set to ) are disabled. For example, a _visible false button in a movie clip with set to...
  • Page 541 MovieClip._x Availability Flash Player 3. Usage my_mc._x Description Property; an integer that sets the x coordinate of a movie clip relative to the local coordinates of the parent movie clip. If a movie clip is in the main Timeline, then its coordinate system refers to the upper left corner of the Stage as (0, 0).
  • Page 542 MovieClip._xscale Availability Flash Player 4. Usage my_mc._xscale Description Property; determines the horizontal scale ( ) of the movie clip as applied from the percentage registration point of the movie clip. The default registration point is (0,0). Scaling the local coordinate system affects the property settings, which are defined in whole pixels.
  • Page 543 MovieClip._ymouse Availability Flash Player 5. Usage my_mc._ymouse Description Property (read-only); indicates the y coordinate of the mouse position. See also Mouse class, MovieClip._xmouse MovieClip._yscale Availability Flash Player 4. Usage my_mc._yscale Description Property; sets the vertical scale ( ) of the movie clip as applied from the registration percentage point of the movie clip.
  • Page 544: Moviecliploader Class

    MovieClipLoader class Availability Flash Player 7. Description This class lets you implement listener callbacks that provide status information while SWF or JPEG files are being loaded (downloaded) into movie clips. To use MovieClipLoader features, use MovieClipLoader.loadClip() instead of to load loadMovie() MovieClip.loadMovie() SWF files.
  • Page 545 Listener summary for the MovieClipLoader class Listener Description MovieClipLoader.onLoadComplete() Invoked when a file loaded with has completely MovieClipLoader.loadClip() downloaded. MovieClipLoader.onLoadError() Invoked when a file loaded with has failed to load. MovieClipLoader.loadClip() MovieClipLoader.onLoadInit() Invoked when the actions on the first frame of the loaded clip have been executed.
  • Page 546 MovieClipLoader.addListener() Availability Flash Player 7. Usage my_mcl.addListener(listenerObject) Parameters An object that listens for a callback notification from the MovieClipLoader listenerObject event handlers. Returns Nothing. Description Method; registers an object to receive notification when a MovieClipLoader event handler is invoked. Example See MovieClipLoader.loadClip().
  • Page 547 Example See MovieClipLoader.loadClip(). See also MovieClipLoader.onLoadProgress() MovieClipLoader.loadClip() Availability Flash Player 7. Usage my_mcl.loadMovie("url", target ) Parameters The absolute or relative URL of the SWF file or JPEG file to be loaded. A relative path must be relative to the SWF file at level 0. Absolute URLs must include the protocol reference, such as http:// or file:///.
  • Page 548 Example The following example illustrates the use of many of the MovieClipLoader methods and listeners. // first set of listeners var my_mcl = new MovieClipLoader(); myListener = new Object(); myListener.onLoadStart = function (target_mc) myTrace ("*********First my_mcl instance*********"); myTrace ("Your load has begun on movie clip . = " + target_mc); var loadProgress = my_mcl.getProgress(target_mc);...
  • Page 549 //Second set of listeners var another_mcl = new MovieClipLoader(); myListener2 = new Object(); myListener2.onLoadStart = function (target_mc) myTrace("*********Second my_mcl instance*********"); myTrace ("Your load has begun on movie clip22 . = " + target_mc); var loadProgress = my_mcl.getProgress(target_mc); myTrace(loadProgress.bytesLoaded + " = bytes loaded at start" ); myTrace(loadProgress.bytesTotal + "...
  • Page 550 MovieClipLoader.onLoadComplete() Availability Flash Player 7. Usage listenerObject.onLoadComplete() = function(target_mc) { // your statements here Parameters A listener object that was added using MovieClipLoader.addListener(). listenerObject The movie clip loaded by a MovieClipLoader.loadClip() method. target_mc Returns Nothing. Description Listener; invoked when a file loaded with MovieClipLoader.loadClip() completely downloaded.
  • Page 551 The string “URLNotFound” is returned if neither the MovieClipLoader.onLoadStart() MovieClipLoader.onLoadComplete() listener has been called. For example, if a server is down or the file is not found, these listeners are not called. The string “LoadNeverCompleted” is returned if was called MovieClipLoader.onLoadStart() was not called.
  • Page 552 MovieClipLoader.onLoadProgress() Availability Flash Player 7. Usage listenerObject.onLoadProgress() = function(target_mc [, loadedBytes [, totalBytes ] ] ) { // your statements here Parameters A listener object that was added using MovieClipLoader.addListener(). listenerObject The movie clip loaded by a MovieClipLoader.loadClip() method. target_mc The number of bytes that had been loaded when the listener was invoked.
  • Page 553 Description Listener; invoked when a call to MovieClipLoader.loadClip() has successfully begun to download a file. Example See MovieClipLoader.loadClip(). See also MovieClipLoader.onLoadError(), MovieClipLoader.onLoadInit(), MovieClipLoader.onLoadComplete() MovieClipLoader.removeListener() Availability Flash Player 7. Usage my_mcl.removeListener(listenerObject) Parameters A listener object that was added using MovieClipLoader.addListener(). listenerObject Returns Nothing.
  • Page 554 Description Method; removes a movie clip that was loaded by means of MovieClipLoader.loadClip(). If you issue this command while a movie is loading, MovieClipLoader.onLoadError() is invoked. See also MovieClipLoader.loadClip() Availability Flash Player 5. Usage Description Variable; a predefined variable with the IEEE-754 value for (Not a Number).
  • Page 555: Netconnection Class

    NetConnection class Availability Flash Player 7. Note: This class is also supported in Flash Player 6 when used with Flash Communication Server. For more information, see your Flash Communication Server documentation. Description The NetConnection class provides the means to play back streaming FLV files from a local drive or HTTP address.
  • Page 556: Netstream Class

    NetConnection.connect() Flash Player 7. Note: This method is also supported in Flash Player 6 when used with Flash Communication Server. For more information, see your Flash Communication Server documentation. Usage my_nc.connect(null); Parameters None (you must pass null Returns Nothing. Description Constructor;...
  • Page 557 Method summary for the NetStream class The following methods and properties of the NetConnection and NetStream classes are used to control FLV playback. Method Purpose Closes the stream but does not clear the video object. NetStream.close() Pauses or resumes playback of a stream. NetStream.pause() NetStream.play() Begins playback of an external video (FLV) file.
  • Page 558 Constructor for the NetStream class Availability Flash Player 7. Note: This class is also supported in Flash Player 6 when used with Flash Communication Server. For more information, see your Flash Communication Server documentation. Usage new NetStream(my_nc) Parameters A NetConnection object. my_nc Returns Nothing.
  • Page 559 NetStream.bufferTime Availability Flash Player 7. Note: This property is also supported in Flash Player 6 when used with Flash Communication Server. For more information, see your Flash Communication Server documentation. Usage myStream.bufferTime Description Read-only property; the number of seconds assigned to the buffer by .
  • Page 560 NetStream.close() Availability Flash Player 7. Note: This method is also supported in Flash Player 6 when used with Flash Communication Server. For more information, see your Flash Communication Server documentation. Usage my_ns.close() Parameters None. Returns Nothing. Description Method; stops playing all data on the stream, sets the NetStream.time property to 0, and makes the stream available for another use.
  • Page 561 NetStream.onStatus Availability Flash Player 7. Note: This handler is also supported in Flash Player 6 when used with Flash Communication Server. For more information, see your Flash Communication Server documentation. Usage my_ns.onStatus = function(infoObject) { // Your code here Parameters A parameter defined according to the status or error message.
  • Page 562 Example The following example writes data about the stream to a log file. my_ns.onStatus = function(info) _root.log_stream += "Stream status.\n"; _root.log_stream += "Event: " + info.code + "\n"; _root.log_stream += "Type: " + info.level + "\n"; See also System.onStatus NetStream.pause() Availability Flash Player 7.
  • Page 563 NetStream.play() Availability Flash Player 7. Note: This method is also supported in Flash Player 6 when used with Flash Communication Server. For more information, see your Flash Communication Server documentation. Usage my_ns.play("fileName"); Parameters The name of an FLV file to play, in quotation marks. Both http:// and file:// formats fileName are supported;...
  • Page 564 NetStream.seek() Availability Flash Player 7. Note: This method is also supported in Flash Player 6 when used with Flash Communication Server. For more information, see your Flash Communication Server documentation. Usage my_ns.seek(numberOfSeconds) Parameters The approximate time value, in seconds, to move to in an FLV file. The numberOfSeconds playhead moves to the keyframe closest to numberOfSeconds...
  • Page 565 NetStream.setBufferTime() Availability Flash Player 7. Note: This method is also supported in Flash Player 6 when used with Flash Communication Server. For more information, see your Flash Communication Server documentation. Usage my_ns.setBufferTime(numberOfSeconds) Parameters The number of seconds of data to be buffered before Flash begins displaying numberOfSeconds data.
  • Page 566 Availability Flash Player 5. Usage new constructor() Parameters A function followed by any optional parameters in parentheses. The function is constructor usually the name of the object type (for example, Array, Number, or Object) to be constructed. Returns Nothing. Description Operator;...
  • Page 567 newline Availability Flash Player 4. Usage newline Parameters None. Returns Nothing. Description Constant; inserts a carriage return character ( ) that generates a blank line in text output generated by your code. Use to make space for information that is retrieved by a newline function or action in your code.
  • Page 568 nextScene() Availability Flash 2. Usage nextScene() Parameters None. Returns Nothing. Description Function; sends the playhead to Frame 1 of the next scene and stops it. Example In this example, when a user releases the button, the playhead is sent to Frame 1 of the next scene. on(release) { nextScene();...
  • Page 569: Number Class

    null Availability Flash Player 5. Usage null Parameters None. Returns Nothing. Description Constant; a special value that can be assigned to variables, or returned by a function if no data was provided. You can use to represent values that are missing or do not have a defined null data type.
  • Page 570 Method summary for the Number class Method Description Returns the string representation of a Number object. Number.toString() Number.valueOf() Returns the primitive value of a Number object. Property summary for the Number class Property Description Constant representing the largest representable number (double- Number.MAX_VALUE precision IEEE-754).
  • Page 571 Number.MAX_VALUE Availability Flash Player 5. Usage Number.MAX_VALUE Description Property; the largest representable number (double-precision IEEE-754). This number is approximately 1.79E+308. Number.MIN_VALUE Availability Flash Player 5. Usage Number.MIN_VALUE Description Property; the smallest representable number (double-precision IEEE-754). This number is approximately 5e-324. Number.NaN Availability Flash Player 5.
  • Page 572 Number.NEGATIVE_INFINITY Availability Flash Player 5. Usage Number.NEGATIVE_INFINITY Description Property; specifies the IEEE-754 value representing negative infinity. The value of this property is the same as that of the constant -Infinity Negative infinity is a special numeric value that is returned when a mathematical operation or function returns a negative value larger than can be represented.
  • Page 573 Description Method; returns the string representation of the specified Number object ( myNumber is undefined, the return value is as follows: myNumber • In files published for Flash Player 6 or earlier, the result is 0. • In files published for Flash Player 7 or later, the result is Example The following example uses 2 and 8 for the parameter and returns a string that contains...
  • Page 574: Object Class

    Description Function; converts the parameter to a number and returns a value as follows: expression • is a number, the return value is expression expression • is a Boolean value, the return value is 1 if , 0 if expression expression true expression...
  • Page 575 Constructor for the Object class Availability Flash Player 5. Usage new Object([value]) Parameters A number, Boolean value, or string to be converted to an object. This parameter value is optional. If you do not specify , the constructor creates a new object with no value defined properties.
  • Page 576 You can add getter/setter properties to prototype objects. If you add a getter/setter property to a prototype object, all object instances that inherit the prototype object inherit the getter/setter property. This makes it possible to add a getter/setter property in one location, the prototype object, and have it propagate to all instances of a class (much like adding methods to prototype objects).
  • Page 577 Usage 2: The above example of works, but the properties bookcount bookname bookcount are added to every instance of the object. That means that the cost of having bookname Book the properties is two property slots for every instance of the object. If there are many properties like in a class, they could consume a great deal of memory.
  • Page 578 Object.__proto__ Availability Flash Player 5. Usage myObject.__proto__ Parameters None. Description Property; refers to the property of the constructor function that created prototype myObject property is automatically assigned to all objects when they are created. The __proto__ ActionScript interpreter uses the property to access the property of __proto__...
  • Page 579 If a symbol is already registered to a class, this method replaces it with the new registration. When a movie clip instance is placed by the Timeline or created using attachMovie() , ActionScript invokes the constructor for the appropriate class with the duplicateMovieClip() keyword pointing to the object.
  • Page 580 Object.unwatch() Availability Flash Player 6. Usage myObject.unwatch (prop) Parameters The name of the object property that should no longer be watched, as a string. prop Returns A Boolean value. Description Method; removes a watchpoint that created. This method returns a value of Object.watch() if the watchpoint was successfully removed;...
  • Page 581 Object.watch() Availability Flash Player 6. Usage myObject.watch( prop, callback [, userData] ) Parameters A string indicating the name of the object property to watch. prop The function to invoke when the watched property changes. This parameter is a callback function object, not a function name as a string. The form of callback callback(prop, oldval, newval, userData)
  • Page 582 Example This example shows a CheckBox component with methods that set the label or value of each check box instance: myCheckBox1.setValue(true); myCheckBox1.setLabel("new label"); It’s convenient to think of the value and label of a check box as properties. It’s possible to use to make accessing the value and label look like property access rather than Object.watch() method invocation, as in the following:...
  • Page 583 on() Availability Flash 2. Not all events are supported in Flash 2. Usage on(mouseEvent) { // your statements here Parameters The instructions to execute when the takes place. statement(s) mouseEvent is a trigger called an “event.” When the event takes place, the statements mouseEvent following it within curly braces execute.
  • Page 584 onClipEvent() Availability Flash Player 5. Usage onClipEvent(movieEvent){ // your statements here Parameters is a trigger called an event. When the event takes place, the statements following it movieEvent within curly braces are executed. Any of the following values can be specified for the movieEvent parameter: •...
  • Page 585 The following example uses with the movie event. The movie onClipEvent() keyDown keyDown event is usually used in conjunction with one or more methods and properties of the Key object. The following script uses to find out which key the user has pressed; if the Key.getCode() pressed key matches the property, the movie is sent to the next frame;...
  • Page 586 Example function gives the Live Preview movie an opportunity to update its visual onUpdate appearance to match the new values of the component parameters. When the user changes a parameter value in the components Property inspector or Component Parameters panel, is invoked.
  • Page 587 Availability Flash Player 4. This function has been deprecated in favor of the methods and properties of the String class. Usage ord(character) Parameters The character to convert to an ASCII code number. character Returns Nothing. Description String function; converts characters to ASCII code numbers. See also String class _parent...
  • Page 588 parseFloat() Availability Flash Player 5. Usage parseFloat(string) Parameters The string to read and convert to a floating-point number. string Returns A number or Description Function; converts a string to a floating-point number. The function reads, or “parses,” and returns the numbers in a string until it reaches a character that is not a part of the initial number. If the string does not begin with a number that can be parsed, returns .
  • Page 589 parseInt Availability Flash Player 5. Usage parseInt(expression [, radix]) Parameters A string to convert to a integer. expression Optional; an integer representing the radix (base) of the number to parse. Legal values radix are from 2 to 36. Returns A number or Description Function;...
  • Page 590 play() Availability Flash 2. Usage play() Parameters None. Returns Nothing. Description Function; moves the playhead forward in the Timeline. Example The following code uses an statement to check the value of a name the user enters. If the user enters , the action is called and the playhead moves forward in the Timeline.
  • Page 591 Example When the user clicks a button that has the following handler attached to it, the playhead is sent to the previous frame. on(release) { prevFrame(); See also MovieClip.prevFrame() prevScene() Availability Flash 2. Usage prevScene() Parameters None. Returns Nothing. Description Function;...
  • Page 592 • Designates the bounding box of a specific frame in a movie as the print area for all bmovie printable frames in the movie. Assign a frame label to the frame whose bounding box you want to use as the print area. •...
  • Page 593 If your movie does not contain alpha transparencies or color effects, Macromedia recommends that you use for better quality results. print()
  • Page 594 printAsBitmapNum() Availability Flash Player 5. Note: If you are authoring for Flash Player 7 or later, you can create a PrintJob object, which gives you (and the user) more control over the printing process. For more information, see the PrintJob class entry.
  • Page 595: Printjob Class

    PrintJob class Availability Flash Player 7. Description The PrintJob class lets you create content and print it to one or more pages. This class, in addition to offering improvements to print functionality provided by the method, lets you render print() dynamic content offscreen, prompt users with a single print dialog box, and print an unscaled document with proportions that map to the proportions of the content.
  • Page 596 Description Constructor; creates a PrintJob object that you can use to print one or more pages. To implement a print job, use these methods in the sequence shown: // create PrintJob object my_pj = new PrintJob(); // instantiate object // display print dialog box my_pj.start();...
  • Page 597 The coordinates you specify for represent screen pixels relative to the registration printArea point of the movie (if = 0) or of the level or movie clip specified by . You _root target target must provide all four coordinates. The width ( ) and height ( ) must each be xMax-xMin...
  • Page 598 If this method returns (for example, if you haven’t called or the user false PrintJob.start() canceled the print job), any subsequent calls to will fail. However, if prior PrintJob.addPage() calls to were successful, the concluding command PrintJob.addPage() PrintJob.send() sends the successfully spooled pages to the printer. If you passed a value for , the coordinates map to the upper left corner...
  • Page 599 // Starting at 0,0, print an area 400 pixels wide // and 400 pixels high of frame 3 of the "dance_mc" movie clip // in bitmap format if (my_pj.addPage("dance_mc", {xMin:0,xMax:400,yMin:0,yMax:400},{printAsBitmap:true}, 3)) pageCount++; // Starting at 0,0, print an area 400 pixels wide // and 600 pixels high of frame 3 of the "dance_mc"...
  • Page 600 Description Method; is used following to send spooled pages PrintJob.start() PrintJob.addPage() to the printer. Example PrintJob.addPage() See also PrintJob.addPage() PrintJob.start() PrintJob.start() Availability Flash Player 7. Usage my_pj.start() Parameters None. Returns A Boolean value of if the user clicks OK when the print dialog boxes appear, or if the true false...
  • Page 601 If this method returns (for example, if the user clicks Cancel instead of OK), any false subsequent calls to will fail. However, if you test PrintJob.addPage() PrintJob.send() for this return value and don’t send commands as a result, you should still PrintJob.addPage() delete the PrintJob object to make sure the print spooler is cleared, as shown below.
  • Page 602 Description Function; prints the level in Flash Player according to the boundaries specified in the Bounding parameter ( ). If you want to print specific frames in the target "bmovie" "bmax" "bframe" movie, attach a frame label to those frames. Although using results in higher printNum() quality prints than using...
  • Page 603 public Flash Player 6. Usage class someClassName{ public var name; public function name() { // your statements here Note: To use this keyword, you must specify ActionScript 2.0 and Flash Player 6 or later in the Flash tab of your FLA file’s Publish Settings dialog box. This keyword is supported only when used in external script files, not in scripts written in the Actions panel.
  • Page 604 property can be set to the following values: _quality • Low rendering quality. Graphics are not anti-aliased, bitmaps are not smoothed. "LOW" • Medium rendering quality. Graphics are anti-aliased using a 2 x 2 grid, in pixels, "MEDIUM" but bitmaps are not smoothed. Suitable for movies that do not contain text. •...
  • Page 605 removeMovieClip() Availability Flash Player 4. Usage removeMovieClip(target) Parameters The target path of a movie clip instance created with , or the target duplicateMovieClip() instance name of a movie clip created with MovieClip.attachMovie() MovieClip.duplicateMovieClip() Returns None. Description Function; deletes the specified movie clip. See also duplicateMovieClip() MovieClip.duplicateMovieClip()
  • Page 606 Example The following example uses the action inside the body of the function to return return sum() the added value of the three parameters. The next line of code calls and assigns the sum() returned value to the variable newValue function sum(a, b, c){ return a + b + c;...
  • Page 607: Selection Class

    scroll Availability Flash Player 4. Usage textFieldVariableName.scroll = x Description Property; a deprecated property that controls the display of information in a text field associated with a variable. The property defines where the text field begins displaying content; after scroll you set it, Flash Player updates it as the user scrolls through the text field.
  • Page 608 Method summary for the Selection class Method Description Registers an object to receive notification when Selection.addListener() onSetFocus invoked. Returns the index at the beginning of the selection span. Returns -1 if Selection.getBeginIndex() there is no index or currently selected field. Selection.getCaretIndex() Returns the current caret (insertion point) position in the currently focused selection span.
  • Page 609 Selection.getBeginIndex() Availability Flash Player 5. Usage Selection.getBeginIndex() Parameters None. Returns An integer. Description Method; returns the index at the beginning of the selection span. If no index exists or no text field currently has focus, the method returns -1. Selection span indexes are zero-based (for example, the first position is 0, the second position is 1, and so on).
  • Page 610 Selection.getEndIndex() Availability Flash Player 5. Usage Selection.getEndIndex() Parameters None. Returns An integer. Description Method; returns the ending index of the currently focused selection span. If no index exists, or if there is no currently focused selection span, the method returns -1. Selection span indexes are zero-based (for example, the first position is 0, the second position is 1, and so on).
  • Page 611 Selection.onSetFocus Availability Flash Player 6. Usage someListener.onSetFocus = function(oldFocus, newFocus){ statements; Description Listener; notified when the input focus changes. To use , you must create a listener onSetFocus object. You can then define a function for and use to register the onSetFocus addListener() listener with the Selection object, as in the following:...
  • Page 612 Selection.setFocus() Availability Flash Player 5. Instance names for buttons and movie clips work only in Flash Player 6 and later. Usage Selection.setFocus("instanceName") Parameters A string specifying the path to the instance name of a button, movie clip, or instanceName text field. Returns An event.
  • Page 613 Returns Nothing. Description Method; sets the selection span of the currently focused text field. The new selection span will begin at the index specified in the parameter, and end at the index specified in the start parameter. Selection span indexes are zero-based (for example, the first position is 0, the second position is 1, and so on).
  • Page 614 set variable Availability Flash Player 4. Usage set(variable, expression) Parameters An identifier to hold the value of the parameter. variable expression A value assigned to the variable. expression Returns Nothing. Description Statement; assigns a value to a variable. A variable is a container that holds data. The container itself is always the same, but the contents can change.
  • Page 615 setInterval() Availability Flash Player 6. Usage setInterval(functionName, interval [, param1, param2, ..., paramN]) Parameters A function name or a reference to an anonymous function. functionName The time in milliseconds between calls to the parameter. interval functionName Optional parameters passed to the param1, param2, ..., paramN function parameter.
  • Page 616 Usage 3: This example uses a method of an object. You must use this syntax when you want to call a method that is defined for an object. obj = new Object(); obj.interval = function() { trace("interval function called"); setInterval( obj, "interval", 1000 ); obj2 = new Object();...
  • Page 617: Sharedobject Class

    SharedObject class Availability Flash Player 6. Description Shared objects are quite powerful: they offer real-time data sharing between objects that are persistent on the user’s computer. You can think of local shared objects as “cookies.” You can use local shared objects to maintain local persistence. This is the simplest way to use a shared object.
  • Page 618 The following list summarizes how the user’s disk space choices interact with shared objects: • If the user selects Never, objects are never saved locally, and all SharedObject.flush() commands issued for the object return false • If the user selects Unlimited (moves the slider all the way to the right), objects are saved locally up to available disk space.
  • Page 619 Constructor for the SharedObject class For information on creating local shared objects, see SharedObject.getLocal() SharedObject.clear() Availability Flash Player 7. Usage my_so.clear() Parameters None. Returns Nothing. Description Method; purges all of the data from the shared object and deletes the shared object from the disk. The reference to is still active, and is now empty.
  • Page 620 To create “private” values for a shared object—values that are available only to the client instance while the object is in use and are not stored with the object when it is closed—create properties that are not named to store them, as shown in the following example. data so.favoriteColor = "blue";...
  • Page 621 If this method returns , the Flash Player displays a dialog box asking the user to "pending" increase the amount of disk space available to objects from this domain. To allow space for the shared object to “grow” when it is saved in the future, thus avoiding return values of "pending"...
  • Page 622 SharedObject.getLocal() Availability Flash Player 6. Usage SharedObject.getLocal(objectName [, localPath]) Note: The correct syntax is . To assign the object to a variable, use syntax like SharedObject.getLocal myLocalSO = SharedObject.getLocal Parameters The name of the object. The name can include forward slashes ( );...
  • Page 623 SharedObject.getSize() Availability Flash Player 6. Usage myLocalSharedObject.getSize() Parameters None. Returns A numeric value specifying the size of the shared object, in bytes. Description Method; gets the current size of the shared object, in bytes. Flash calculates the size of a shared object by stepping through each of its data properties; the more data properties the object has, the longer it takes to estimate its size.
  • Page 624: Sound Class

    In addition to this handler, Flash also provides a “super” function called onStatus System.onStatus. If is invoked for a particular object and there is no function assigned onStatus to respond to it, Flash processes a function assigned to if it exists. System.onStatus The following events notify you when certain SharedObject activities occur.
  • Page 625 Method Description Sets the amount of each channel, left and right, to be played in Sound.setTransform() each speaker. Sets the volume level for a sound. Sound.setVolume() Starts playing a sound from the beginning or, optionally, from an offset Sound.start() point set in the parameter. Stops the specified sound or all sounds currently playing.
  • Page 626 Example The following example creates a new Sound object called . The second line calls global_sound and adjusts the volume on all sounds in the movie to 50%. setVolume() global_sound = new Sound(); global_sound.setVolume(50); The following example creates a new Sound object, passes it the target movie clip , and calls my_mc method, which starts any sound in...
  • Page 627 Sound.getBytesLoaded() Availability Flash Player 6. Usage my_sound.getBytesLoaded() Parameters None. Returns An integer indicating the number of bytes loaded. Description Method; returns the number of bytes loaded (streamed) for the specified Sound object. You can compare the value of with the value of to determine what getBytesLoaded() getBytesTotal()
  • Page 628 Sound.getPan() Availability Flash Player 5. Usage my_sound.getPan(); Parameters None. Returns An integer. Description Method; returns the pan level set in the last call as an integer from -100 (left) to 100 setPan() (right). (0 sets the left and right channels equally.) The pan setting controls the left-right balance of the current and future sounds in a SWF file.
  • Page 629 Sound.getVolume() Availability Flash Player 5. Usage my_sound.getVolume() Parameters None. Returns An integer. Description Method; returns the sound volume level as an integer from 0 to 100, where 0 is off and 100 is full volume. The default setting is 100. See also Sound.setVolume() Sound.ID3...
  • Page 630 Property Description TCOM Composer Content type TCON Copyright message TCOP TDAT Date TDLY Playlist delay Encoded by TENC Lyricist/text writer TEXT TFLT File type Time TIME Content group description TIT1 Title/song name/content description TIT2 TIT3 Subtitle/description refinement Initial key TKEY Languages TLAN TLEN...
  • Page 631 Property Description TSRC ISRC (international standard recording code) Software/hardware and settings used for encoding TSSE Year TYER WXXX URL link frame Flash Player 6 supported several ID31.0 tags. If these tags are in not in the MP3 file, but corresponding ID3 2.0 tags are, the ID3 2.0 tags are copied into the ID3 1.0 properties, as shown in the following table.
  • Page 632 Description Method; loads an MP3 file into a Sound object. You can use the parameter to isStreaming indicate whether the sound is an event or a streaming sound. Event sounds are completely loaded before they play. They are managed by the ActionScript Sound class and respond to all methods and properties of this class.
  • Page 633 Example The following example traces the ID3 properties of song.mp3 to the Output panel. my_sound = new Sound(); my_sound.onID3 = function(){ for( var prop in my_sound.ID3 ){ trace( prop + " : "+ my_sound.ID3[prop] ); my_sound.loadSound("song.mp3", false); See also Sound.attachSound() Sound.ID3 Sound.loadSound() Sound.onLoad...
  • Page 634 Sound.onSoundComplete Availability Flash Player 6. Usage my_sound.onSoundComplete = function(){ // your statements here Parameters None. Returns Nothing. Description Event handler; invoked automatically when a sound finishes playing. You can use this handler to trigger events in a SWF file when a sound finishes playing. You must create a function that executes when this handler is invoked.
  • Page 635 Sound.position Availability Flash Player 6. Usage my_sound.position Description Property (read-only); the number of milliseconds a sound has been playing. If the sound is looped, the position will be reset to 0 at the beginning of each loop. Sound.setPan() Availability Flash Player 5. Usage my_sound.setPan(pan);...
  • Page 636 Sound.setTransform() Availability Flash Player 5. Usage my_sound.setTransform(soundTransformObject) Parameters An object created with the constructor for the generic Object class. soundTransformObject Returns Nothing. Description Method; sets the sound transform (or balance) information, for a Sound object. parameter is an object that you create using the constructor soundTransformObject method of the generic Object class with parameters specifying how the sound is distributed to the left and right channels (speakers).
  • Page 637 Mono sounds play all sound input in the left speaker and have the following transform settings by default: ll = 100 lr = 100 rr = 0 rl = 0 Example The following example illustrates a setting that can be achieved by using , but setTransform() cannot be achieved by using...
  • Page 638 Sound.setVolume() Availability Flash Player 5. Usage my_sound.setVolume(volume) Parameters A number from 0 to 100 representing a volume level. 100 is full volume and 0 is no volume volume. The default setting is 100. Returns Nothing. Description Method; sets the volume for the Sound object. Example The following example sets volume to 50% and transfers the sound over time from the left speaker to the right speaker:...
  • Page 639 Returns Nothing. Description Method; starts playing the last attached sound from the beginning if no parameter is specified, or starting at the point in the sound specified by the parameter. secondOffset See also Sound.stop() Sound.stop() Availability Flash Player 5. Usage my_sound.stop(["idName"]) Parameters An optional parameter specifying a specific sound to stop playing.
  • Page 640: Stage Class

    Stage class Availability Flash Player 6. Description The Stage class is a top-level class whose methods, properties, and handlers you can access without using a constructor. Use the methods and properties of this class to access and manipulate information about the boundaries of a SWF file.
  • Page 641 Stage.addListener() Availability Flash Player 6. Usage Stage.addListener(myListener) Parameters An object that listens for a callback notification from the event. myListener Stage.onResize Returns Nothing. Description Method; detects when a SWF file is resized (but only if ). The Stage.scaleMode = "noScale" method doesn’t work with the default movie scaling setting ( ) or addListener()
  • Page 642 The following table lists the values for the property. Any value not listed here centers the align SWF file in the player or browser area. Value Vertical Horizontal center "T" bottom center "B" center left "L" "R" center right left "TL"...
  • Page 643 Returns Nothing. Description Event handler; invoked when is set to and the SWF file is resized. Stage.scaleMode "noScale" You can use this event handler to write a function that lays out the objects on the Stage when a SWF file is resized. Example The following example displays a message in the Output panel when the Stage is resized.
  • Page 644 Stage.scaleMode Availability Flash Player 6. Usage Stage.scaleMode = "value" Description Property; indicates the current scaling of the SWF file within the Stage. The property scaleMode forces the SWF file into a specific scaling mode. By default, the SWF file uses the HTML parameters set in the Publish Settings dialog box.
  • Page 645 startDrag() Availability Flash Player 4. Usage startDrag(target,[lock, left, top, right, bottom]) Parameters The target path of the movie clip to drag. target A Boolean value specifying whether the draggable movie clip is locked to the center of the lock mouse position ( ), or locked to the point where the user first clicked on the movie clip true ).
  • Page 646 static Availability Flash Player 6. Usage class someClassName{ static var name; static function name() { // your statements here Note: To use this keyword, you must specify ActionScript 2.0 and Flash Player 6 or later in the Flash tab of your FLA file’s Publish Settings dialog box. This keyword is supported only when used in external script files, not in scripts written in the Actions panel.
  • Page 647 stopAllSounds() Availability Flash Player 3. Usage stopAllSounds() Parameters None. Returns Nothing. Description Function; stops all sounds currently playing in a SWF file without stopping the playhead. Sounds set to stream will resume playing as the playhead moves over the frames they are in. Example The following code could be applied to a button that, when clicked, stops all sounds in the SWF file.
  • Page 648 Example This code stops the drag action on the instance when the user releases the mouse button: my_mc on(press) { startDrag("my_mc"); on(release) { stopdrag(); See also MovieClip._droptarget MovieClip.stopDrag() startDrag() " " (string delimiter) Availability Flash Player 4. Usage "text" Parameters A character.
  • Page 649: String Class

    String class Availability Flash Player 5 (became a native object in Flash Player 6, which improved performance significantly). Description The String class is a wrapper for the string primitive data type, and provides methods and properties that let you manipulate primitive string value types. You can convert the value of any object into a string using the function.
  • Page 650 Method Description String.toLowerCase() Converts the string to lowercase and returns the result; does not change the contents of the original object. Converts the string to uppercase and returns the result; does not change String.toUpperCase() the contents of the original object. Property summary for the String class Property Description...
  • Page 651 Description Method; returns the character in the position specified by the parameter . If is not a index index number from 0 to - 1, an empty string is returned. string.length This method is similar to except that the returned value is a character, not String.charCodeAt() a 16-bit integer character code.
  • Page 652 String.concat() Availability Flash Player 5. Usage my_str.concat(value1,...valueN) Parameters Zero or more values to be concatenated. value1,...valueN Returns A string. Description Method; combines the value of the String object with the parameters and returns the newly formed string; the original value, , is unchanged.
  • Page 653 String.indexOf() Availability Flash Player 5. Usage my_str.indexOf(substring, [startIndex]) Parameters An integer or string specifying the substring to be searched for within substring my_str An optional integer specifying the starting point in to search for startIndex my_str the substring. Returns The position of the first occurrence of the specified substring, or -1. Description Method;...
  • Page 654 String.length Availability Flash Player 5. Usage my_str.length Description Property; a nonzero-based integer specifying the number of characters in the specified String object. Because all string indexes are zero-based, the index of the last character for any string x.length - 1 String.slice() Availability Flash Player 5.
  • Page 655 See also String.substr() String.substring() String.split() Availability Flash Player 5. Usage my_str.split("delimiter", [limit]) Parameters The character or string at which splits. delimiter my_str The number of items to place into the array. This parameter is optional. limit Returns An array containing the substrings of my_str Description Method;...
  • Page 656 String.substr() Availability Flash Player 5. Usage my_str.substr(start, [length]) Parameters An integer that indicates the position of the first character in to be used to create start my_str the substring. If is a negative number, the starting position is determined from the end of start the string, where the -1 is the last character.
  • Page 657 String.toLowerCase() Availability Flash Player 5. Usage my_str.toLowerCase() Parameters None. Returns A string. Description Method; returns a copy of the String object, with all of the uppercase characters converted to lowercase. The original value is unchanged. String.toUpperCase() Availability Flash Player 5. Usage my_str.toUpperCase() Parameters...
  • Page 658 Description Function; returns a string representation of the specified parameter as follows: is a number, the return string is a text representation of the number. expression is a string, the return string is expression expression is an object, the return value is a string representation of the object generated expression by calling the string property for the object, or by calling if no such...
  • Page 659 super Availability Flash Player 6. Usage super.method([arg1, ..., argN]) super([arg1, ..., argN]) Parameters The method to invoke in the superclass. method Optional parameters that are passed to the superclass version of the method (syntax 1) or arg1 to the constructor function of the superclass (syntax 2). Returns Both forms invoke a function.
  • Page 660 Description Statement; creates a branching structure for ActionScript statements. Like the action, the action tests a condition and executes statements if the condition returns a value of switch true Example In the following example, if the parameter evaluates to 1, the action that follows number trace()
  • Page 661: System Class

    System class Availability Flash Player 6. Description This is a top-level class that contains the capabilities object (see System.capabilities object), the security object (see System.security object), and the methods, properties, and event handlers listed below. Method summary for the System class Method Description System.setClipboard()
  • Page 662 System.exactSettings Availability Authoring: Flash MX 2004. Playback: SWF files published for Flash Player 6 or later, playing in Flash Player 7 or later. Usage System.exactSettings Description Property; specifies whether to use superdomain or exact-domain matching rules when accessing local settings (such as camera or microphone access permissions) or locally persistent data (shared objects).
  • Page 663 System.onStatus Availability Flash Player 6. Description Event handler: provides a “super” event handler for certain objects. The LocalConnection, NetStream, and SharedObject objects provide an event handler onStatus that uses an information object for providing information, status, or error messages. To respond to this event handler, you must create a function to process the information object, and you must know the format and contents of the information object returned.
  • Page 664 System.setClipboard() Availability Authoring: Flash MX 2004. Playback: SWF files published for Flash Player 6 or later, playing in Flash Player 7 or later. Usage System.setClipboard(string) Parameters A plain-text string of characters to place on the system clipboard, replacing its current string contents (if any).
  • Page 665 Description Method; displays the specified Flash Player Settings panel, which lets users do any of the following: • Allow or deny access to the camera and microphone • Specify the local disk space available for shared objects • Select a default camera and microphone •...
  • Page 666: System.capabilities Object

    HTTP method. The following is an POST example of a server string for a device that does not have MP3 support and has a 400 x 200 pixel, 8 x 4 centimeter screen: "A=t&SA=t&SV=t&EV=t&MP3=t&AE=t&VE=t&ACC=f&PR=t&SP=t&SB=f&DEB=t&V=WIN%207%2C0%2 C0%2C226&M=Macromedia%20Windows&R=1152x864&DP=72&COL=color&AR=1.0&OS=Window s%20XP&L=en&PT=External&AVD=f&LFD=f" Property summary for the System.capabilities object Property Description...
  • Page 667 Property Description Server string Indicates whether the player is running on a System.capabilities.hasMP3 system that has an MP3 decoder. Indicates whether the player is running on a System.capabilities.hasPrinting system that supports printing. Indicates whether the player supports the System.capabilities.hasScreenBroadcast development of screen broadcast applications to be run through the Flash Communication Server.
  • Page 668 Property Description Server string A URL-encoded string that specifies values System.capabilities.serverString for each System.capabilities property. A string containing Flash Player version and System.capabilities.version platform information. System.capabilities.avHardwareDisable Availability Flash Player 7. Usage System.capabilities.avHardwareDisable Description Read-only property; a Boolean value that specifies whether the user’s camera and microphone are enabled or disabled.
  • Page 669 System.capabilities.hasAudioEncoder Availability Flash Player 6. Usage System.capabilities.hasAudioEncoder Description Property; a Boolean value that indicates whether the player can encode an audio stream, such as that coming from a microphone. The server string is System.capabilities.hasEmbeddedVideo Availability Flash Player 6. Usage System.capabilities.hasEmbeddedVideo Description Property;...
  • Page 670 System.capabilities.hasScreenBroadcast Availability Flash Player 6. Usage System.capabilities.hasScreenBroadcast Description Property; a Boolean value that indicates whether the player supports the development of screen broadcast applications to be run through the Flash Communication Server. The server string System.capabilities.hasScreenPlayback Availability Flash Player 6. Usage System.capabilities.hasScreenPlayback Description...
  • Page 671 System.capabilities.hasVideoEncoder Availability Flash Player 6. Usage System.capabilities.hasVideoEncoder Description Property; a Boolean value that indicates whether the player can encode a video stream, such as that coming from a web camera. The server string is System.capabilities.isDebugger Availability Flash Player 6. Usage System.capabilities.isDebugger Description Property;...
  • Page 672 Availability Flash Player 6. Usage System.capabilities.manufacturer Description Property; a string that indicates the manufacturer of Flash Player, in the format could be , or "Macromedia OSName" OSName "Windows" "Macintosh" "Linux" "Other OS ). The server string is Name" Chapter 12: ActionScript Dictionary...
  • Page 673 System.capabilities.os Availability Flash Player 6. Usage System.capabilities.os Description Property; a string that indicates the current operating system. The property can return the following strings: "Windows XP" "Windows 2000" "Windows NT" "Windows 98/ME" "Windows (available only in Flash Player SDK, not in the desktop version), , and 95"...
  • Page 674 System.capabilities.screenDPI Availability Flash Player 6. Usage System.capabilities.screenDPI Description Property; indicates the dots-per-inch (dpi) resolution of the screen, in pixels. The server string System.capabilities.screenResolutionX Availability Flash Player 6. Usage System.capabilities.screenResolutionX Description Property; an integer that indicates the maximum horizontal resolution of the screen. The server string is (which returns both the width and height of the screen).
  • Page 675: System.security Object

    Usage System.capabilities.serverString Description Property; a URL-encoded string that specifies values for each property, as System.capabilities in this example: A=t&SA=t&SV=t&EV=t&MP3=t&AE=t&VE=t&ACC=f&PR=t&SP=t&SB=f&DEB=t&V=WIN%207%2C0%2C 0%2C226&M=Macromedia%20Windows&R=1152x864&DP=72&COL=color&AR=1.0&OS=Windows%20 XP&L=en&PT=External&AVD=f&LFD=f System.capabilities.version Availability Flash Player 6. Usage System.capabilities.version Description Property; a string containing the Flash Player platform and version information, for example, .
  • Page 676 (HTTPS) to permit access from SWF files hosted in nonsecure protocols; you must use System.security.allowInsecureDomain() instead. Example The SWF file located at www.macromedia.com/MovieA.swf contains the following lines. System.security.allowDomain("www.shockwave.com"); loadMovie("http://www.shockwave.com/MovieB.swf", _root.my_mc); Because MovieA contains the command, MovieB can access the objects and allowDomain() variables in MovieA.
  • Page 677 HTTPS protocol. This implementation maintains the integrity provided by the HTTPS protocol. Macromedia does not recommend using this method to override the default behavior because it compromises HTTPS security. However, you may need to do so, for example, if you must permit access to HTTPS files published for Flash Player 7 or later from HTTP files published for Flash Player 6.
  • Page 678 targetPath Availability Flash Player 5. Usage targetpath(movieClipObject) Parameters Reference (for example, ) to the movie clip for which the movieClipObject _root _parent target path is being retrieved. Returns A string containing the target path of the specified movie clip. Description Function;...
  • Page 679 Description Deprecated action; applies the instructions specified in the parameter to the statements Timeline specified in the parameter. The action is useful for navigation target tellTarget controls. Assign to buttons that stop or start movie clips elsewhere on the Stage. You tellTarget can also make movie clips go to a particular frame in that clip.
  • Page 680: Textfield Class

    TextField class Availability Flash Player 6. Description All dynamic and input text fields in a SWF file are instances of the TextField class. You can give a text field an instance name in the Property inspector and use the methods and properties of the TextField class to manipulate it with ActionScript.
  • Page 681 Property Description TextField.bottomScroll The bottommost visible line in a text field. Read-only. TextField.embedFonts Indicates whether the text field uses embedded font outlines or device fonts. TextField._height The height of a text field instance in pixels. This only affects the bounding box of the text field, it does not affect the border thickness or text font size.
  • Page 682 Property Description TextField.textHeight The height of the text field’s bounding box. The width of the text field’s bounding box. TextField.textWidth Indicates whether a text field is an input text field or dynamic TextField.type text field. The URL of the SWF file that created the text field instance. TextField._url Read-only.
  • Page 683 TextField.addListener() Availability Flash Player 6. Usage my_txt.addListener(listener) Parameters An object with an event handler. listener onChanged onScroller Returns Nothing. Description Method; registers an object to receive notification when the event onChanged onScroller handlers have been invoked. When a text field changes or is scrolled, the TextField.onChanged event handlers are invoked, followed by the TextField.onScroller...
  • Page 684 TextField._alpha Availability Flash Player 6. Usage my_txt._alpha Description Property; sets or retrieves the alpha transparency value of the text field specified by . Valid my_txt values are 0 (fully transparent) to 100 (fully opaque). The default value is 100. Example The following code sets the property of a text field named to 30% when the...
  • Page 685 Example The following sets the property of the text field autosize my_txt "center" my_txt.autosize = "center"; TextField.background Availability Flash Player 6. Usage my_txt.background Description Property; if , the text field has a background fill. If , the text field has no true false background fill.
  • Page 686 TextField.borderColor Availability Flash Player 6. Usage my_txt.borderColor Description Property; the color of the text field border, the Default is (black). This property may be 0x000000 retrieved or set, even if there is currently no border. See also TextField.border TextField.bottomScroll Availability Flash Player 6.
  • Page 687 TextField.embedFonts Availability Flash Player 6. Usage my_txt.embedFonts Description Property; a Boolean value that, when , renders the text field using embedded font outlines. If true , it renders the text field using device fonts. false TextField.getDepth() Availability Flash Player 6. Usage my_txt.getDepth() Parameters...
  • Page 688 Example The following code displays a font list returned by getFontList() font_array = TextField.getFontList(); for( i in font_array){ trace(font_array[i]); TextField.getNewTextFormat() Availability Flash Player 6. Usage my_txt.getNewTextFormat() Parameters None. Returns A TextFormat object. Description Method; returns a TextFormat object containing a copy of the text field’s text format object. The text format object is the format that newly inserted text, such as text inserted with the method or text entered by a user, receives.
  • Page 689 Description Method; Usage 1: returns a TextFormat object containing formatting information for all text in a text field. Only properties that are common to all text in the text field are set in the resulting TextFormat object. Any property which is mixed, meaning that it has different values at different points in the text, has its value set to null Usage 2: Returns a TextFormat object containing a copy of the text field’s text format at...
  • Page 690 TextField.hscroll Availability Flash Player 6. Usage my_txt.hscroll Returns An integer. Description Property; indicates the current horizontal scrolling position. If the property is 0, the text hscroll is not horizontally scrolled. For more information on scrolling text, see “Creating scrolling text” on page 153.
  • Page 691 TextField.htmlText Availability Flash Player 6. Usage my_txt.htmlText Description Property; if the text field is an HTML text field, this property contains the HTML representation of the text field’s contents. If the text field is not an HTML text field, it behaves identically to the property.
  • Page 692 TextField.maxChars Availability Flash Player 6. Usage my_txt.maxChars Description Property; indicates the maximum number of characters that the text field can contain. A script may insert more text than allows; the property only indicates how much text maxChars maxChars a user can enter. If the value of this property is , there is no limit on the amount of text a user null can enter.
  • Page 693 Description Property; associates the ContextMenu object with the text field . The contextMenu my_txt ContextMenu class lets you modify the context menu that appears when the user right-clicks (Windows) or Control-clicks (Macintosh) in Flash Player. This property works only with selectable (editable) text fields; it has no affect on nonselectable text fields.
  • Page 694 TextField._name Availability Flash Player 6. Usage my_txt _name Description Property; the instance name of the text field specified by my_txt TextField.onChanged Availability Flash Player 6. Usage my_txt.onChanged = function(){ // your statements here Parameters None. Returns The instance name of the text field. Description Event handler;...
  • Page 695 TextField.onKillFocus Availability Flash Player 6. Usage my_txt.onKillFocus = function(newFocus){ // your statements here Parameters The object that is receiving the focus. newFocus Returns Nothing. Description Event handler; invoked when a text field loses keyboard focus. The method receives onKillFocus one parameter, , which is an object representing the new object receiving the focus.
  • Page 696 TextField.onSetFocus Availability Flash Player 6. Usage my_txt.onSetFocus = function(oldFocus){ // your statements here Parameters The object to lose focus. oldFocus Returns Nothing. Description Event handler; invoked when a text field receives keyboard focus. The parameter is the oldFocus object that loses the focus. For example, if the user presses the Tab key to move the input focus from a button to a text field, contains the text field instance.
  • Page 697 TextField.password Availability Flash Player 6. Usage my_txt.password Description Property; if the value of , the text field is a password text field and hides the password true input characters. If , the text field is not a password text field. false TextField._quality Availability...
  • Page 698 TextField.removeTextField() Availability Flash Player 6. Usage my_txt.removeTextField() Description Method; removes the text field specified by . This operation can only be performed on a my_txt text field that was created with . When you call this method, the MovieClip.createTextField() text field is removed. This method is similar to MovieClip.removeMovieClip() TextField.replaceSel() Availability...
  • Page 699 TextField.replaceText() Availability Flash Player 7. Usage my_txt.replaceText(beginIndex, endIndex, text) Description Method; replaces a range of characters, specified by the parameters, in beginIndex endIndex the specified text field with the contents of the parameter. text TextField.restrict Availability Flash Player 6. Usage my_txt.restrict Description Property;...
  • Page 700 The ^ may be used anywhere in the string to toggle between including characters and excluding characters. The following code includes only uppercase letters, but excludes the uppercase letter Q: my_txt.restrict = "A-Z^Q"; You can use the escape sequence to construct strings.
  • Page 701 TextField.selectable Availability Flash Player 6. Usage my_txt.selectable Description Property; a Boolean value that indicates whether the text field is selectable (editable). The value indicates that the text is selectable. true TextField.setNewTextFormat() Availability Flash Player 6. Usage my_txt.setNewTextFormat(textFormat) Parameters A TextFormat object. textFormat Returns Nothing.
  • Page 702 TextField.setTextFormat() Availability Flash Player 6. Usage my_txt.setTextFormat (textFormat) my_txt.setTextFormat (index, textFormat) my_txt.setTextFormat (beginIndex, endIndex, textFormat) Parameters A TextFormat object, which contains character and paragraph formatting textFormat information. An integer that specifies a character within index my_txt An integer. beginIndex An integer that specifies the first character after the desired text span. endIndex Returns Nothing.
  • Page 703: Textfield.stylesheet Class

    See also TextField.setNewTextFormat() TextFormat class TextField._soundbuftime Availability Flash Player 6. Usage my_txt._soundbuftime Description Property (global); an integer that specifies the number of seconds a sound prebuffers before it starts to stream. TextField.StyleSheet class Availability Flash Player 7. Description The TextField.StyleSheet class lets you create a style sheet object that contains text formatting rules such as font size, color, and other formatting styles.
  • Page 704 Event handler summary for the TextField.StyleSheet class Method Description Callback handler invoked when a TextField.StyleSheet.onLoad TextField.StyleSheet.load() operation has completed. Constructor for the TextField.StyleSheet class Availability Flash Player 7. Usage new TextField.StyleSheet() Returns Nothing. Description Constructor; creates a TextField.StyleSheet object. TextField.StyleSheet.getStyle() Availability Flash Player 7.
  • Page 705 The following code loads the styles from the CSS file, and then displays each property name and its value in the Output panel. var styleSheet = new TextField.styleSheet(); styleSheet.load("styles.css"); var sectionStyle = styleSheet.getStyle("heading"); for(property in sectionStyle) { var propName = property; var propValue = sectionStyle[property];...
  • Page 706 The following is displayed in the Output panel: bodyText heading See also TextField.StyleSheet.getStyle() TextField.StyleSheet.load() Availability Flash Player 7. Usage styleSheet.load(url) Parameters The URL of a CSS file to load. The URL must be in the same domain as the URL where the SWF file currently resides.
  • Page 707 TextField.StyleSheet.onLoad Availability Flash Player 7. Usage styleSheet.onLoad = function (success) {} Parameters A Boolean value indicating whether the CSS file was successfully loaded. success Returns Nothing. Description Callback handler; invoked when a TextField.StyleSheet.load() operation has completed. If the style sheet loaded successfully, the parameter is .
  • Page 708 Description Method; parses the CSS in and loads the style sheet with it. If a style in cssText cssText already in , the properties in are retained, and only the ones in styleSheet styleSheet cssText are added or changed in styleSheet To extend the native CSS parsing capability, you can override this method by creating a subclass of the TextField.StyleSheet class.
  • Page 709 TextField.styleSheet Availability Flash Player 7. Usage my_txt.styleSheet = TextField StyleSheet Description Property; attaches a style sheet to the text field specified by . For information on creating my_txt style sheets, see the TextField.StyleSheet class entry and “Formatting text with Cascading Style Sheets”...
  • Page 710 Description Property; lets you customize the tab ordering of objects in a SWF file. You can set the tabIndex property on a button, movie clip, or text field instance; it is by default. undefined If any currently displayed object in the SWF file contains a property, automatic tab tabIndex ordering is disabled, and the tab ordering is calculated from the...
  • Page 711 TextField.textColor Availability Flash Player 6. Usage my_txt.textColor Description Property; indicates the color of the text in a text field. TextField.textHeight Availability Flash Player 6. Usage my_txt.textHeight Description Property; indicates the height of the text. TextField.textWidth Availability Flash Player 6. Usage my_txt.textWidth Description Property;...
  • Page 712 TextField._url Availability Flash Player 6. Usage my_txt _url Description Property (read only); retrieves the URL of the SWF file that created the text field. TextField.variable Availability Flash Player 6. Usage my_txt variable Description Property; The name of the variable that the text field is associated with. The type of this property is String.
  • Page 713 Example The following example sets the height and width properties of a text field: my_txt._width=200; my_txt._height=200; See also MovieClip._height TextField.wordWrap Availability Flash Player 6. Usage my_txt.wordWrap Description Property; a Boolean value that indicates if the text field has word wrap. If the value of wordWrap , the text field has word wrap;...
  • Page 714 TextField._xmouse Availability Flash Player 6. Usage my_txt._xmouse Description Property (read-only); returns the x coordinate of the mouse position relative to the text field. See also TextField._ymouse TextField._xscale Availability Flash Player 6. Usage my_txt._xscale Description Property; determines the horizontal scale of the text field as applied from the registration point of the text field, expressed as a percentage.
  • Page 715: Textformat Class

    TextField._ymouse Availability Flash Player 6. Usage my_txt._ymouse Description Property (read-only); indicates the y coordinate of the mouse position relative to the text field. See also TextField._xmouse TextField._yscale Availability Flash Player 6. Usage my_txt._yscale Description Property; the vertical scale of the text field as applied from the registration point of the text field, expressed as a percentage.
  • Page 716 The code only changes the property of the text field’s my_txt.setTextFormat(my_fmt) bold default text format, because the property is the only one defined in . All other aspects bold my_fmt of the text field’s default text format remain unchanged. When is invoked, a TextFormat object is returned with all of its TextField.getTextFormat() properties defined;...
  • Page 717 Constructor for the TextFormat class Availability Flash Player 6. Usage new TextFormat([font, [size, [color, [bold, [italic, [underline, [url, [target, [align, [leftMargin, [rightMargin, [indent, [leading]]]]]]]]]]]]]) Parameters The name of a font for text as a string. font An integer that indicates the point size. size The color of text using this text format.
  • Page 718 TextFormat.align Availability Flash Player 6. Usage my_fmt.align Description Property; indicates the alignment of the paragraph, represented as a string. The alignment of the paragraph, represented as a string. If , the paragraph is left-aligned. If , the "left" "center" paragraph is centered. If , the paragraph is right-aligned.
  • Page 719 TextFormat.bullet Availability Flash Player 6. Usage my_fmt.bullet Description Property; a Boolean value that indicates that the text is part of a bulleted list. In a bulleted list, each paragraph of text is indented. To the left of the first line of each paragraph, a bullet symbol is displayed.
  • Page 720 Parameters A string. text An optional number that represents the width, in pixels, at which the specified text width should wrap. Returns An object with the properties width height ascent descent textFieldHeight textFieldWidth Description Method; returns text measurement information for the text string in the format specified by text .
  • Page 721 = "Arial"; txt_fmt.bold = true; txt_fmt.leading = 4; // The string of text to be displayed var textToDisplay:String = "Macromedia Flash 7, now with improved text metrics."; // Obtain text measurement information for the string, // wrapped at 100 pixels.
  • Page 722 TextFormat.indent Availability Flash Player 6. Usage my_fmt.indent Description Property; an integer that indicates the indentation from the left margin to the first character in the paragraph. The default value is , which indicates that the property is undefined. null See also TextFormat.blockIndent TextFormat.italic Availability...
  • Page 723 TextFormat.leftMargin Availability Flash Player 6. Usage my_fmt.leftMargin Description Property; the left margin of the paragraph, in points. The default value is , which indicates null that the property is undefined. TextFormat.rightMargin Availability Flash Player 6. Usage my_fmt.rightMargin Description Property; the right margin of the paragraph, in points. The default value is , which indicates null that the property is undefined.
  • Page 724 TextFormat.target Availability Flash Player 6. Usage my_fmt.target Description Property; indicates the target window where the hyperlink is displayed. If the target window is an empty string, the text is displayed in the default target window . If the _self TextFormat.url property is an empty string or , you can get or set this property, but the property will have null...
  • Page 725: Textsnapshot Object

    TextSnapshot object Availability Authoring: Flash MX 2004. Playback: SWF files published for Flash Player 6 or later, playing in Flash Player 7 or later. Description TextSnapshot objects let you work with static text in a movie clip. You can use them, for example, to lay out text with greater precision than that allowed by dynamic text, but still access the text in a read-only way.
  • Page 726 TextSnapshot.findText() Availability Authoring: Flash MX 2004. Playback: SWF files published for Flash Player 6 or later, playing in Flash Player 7 or later. Usage my_snap.findText( startIndex, textToFind, caseSensitive ) Parameters An integer specifying the starting point in to search for the specified text. startIndex my_snap A string specifying the text to search for.
  • Page 727 TextSnapshot.getSelected() Availability Authoring: Flash MX 2004. Playback: SWF files published for Flash Player 6 or later, playing in Flash Player 7 or later. Usage my_snap.getSelected(from, to) Parameters An integer that indicates the position of the first character of to be examined. from my_snap Valid values for...
  • Page 728 Description Method; returns a string that contains all the characters specified by the corresponding TextSnapshot.setSelected() command. If no characters are selected, an empty string is returned. If you pass a value of , newline characters are inserted in the string true includeLineEndings returned where deemed appropriate.
  • Page 729 TextSnapshot.hitTestTextNearPos() Availability Authoring: Flash MX 2004. Playback: SWF files published for Flash Player 6 or later, playing in Flash Player 7 or later. Usage my_snap.hitTestTextNearPos(x, y [, maxDistance] ) Parameters A number that represents the coordinate of the movie clip containing the text in my_snap A number that represents the coordinate of the movie clip containing the text in...
  • Page 730 Description Method; specifies the color to use when highlighting characters that have been selected with the TextSnapshot.setSelected() command. The color is always opaque; you can’t specify a transparency value. TextSnapshot.setSelected() Availability Authoring: Flash MX 2004. Playback: SWF files published for Flash Player 6 or later, playing in Flash Player 7 or later. Usage mySnapshot.setSelected(from, to, select) Parameters...
  • Page 731 this Availability Flash Player 5. Usage this Description Identifier; references an object or movie clip instance. When a script executes, references the this movie clip instance that contains the script. When a method is called, contains a reference this to the object that contains the called method. Inside an event handler action attached to a button, refers to the Timeline that contains...
  • Page 732 // statements in FLA file import simple; var obj:simple = new simple(); obj.num = 0; obj.func = function():Boolean{ return true; obj.callfunc(); // syntax error with incorrect version of simple.as Example In the following example, the keyword references the Circle object. this function Circle(radius) { this.radius = radius;...
  • Page 733 Example In this example, a function named checks whether the string that is passed to it is checkEmail() a properly formatted e-mail address. If the string does not contain an @ symbol, the function throws an error. function checkEmail(email:String) { if (email.indexOf("@") == -1) { throw new Error("Invalid email address");...
  • Page 734 toggleHighQuality() Availability Flash 2; deprecated in favor of _quality Usage toggleHighQuality() Parameters None. Returns Nothing. Description Deprecated function; turns anti-aliasing on and off in Flash Player. Anti-aliasing smooths the edges of objects and slows down SWF playback. This action affects all SWF files in Flash Player. Example The following code could be applied to a button that, when clicked, would toggle anti-aliasing on and off:...
  • Page 735 Description Statement; evaluates the expression and displays the result in the Output panel in test mode. Use this action to record programming notes or to display messages in the Output panel while testing a movie. Use the parameter to check if a condition exists, or to display values expression in the Output panel.
  • Page 736 try..catch..finally Availability Flash Player 7. Usage try { // ... try block ... } finally { // ... finally block ... try { // ... try block ... } catch(error[:ErrorType1]) { // ... catch block ... } [catch(error[:ErrorTypeN]) { // ... catch block ... }] [finally { // ...
  • Page 737 Example The following example shows how to create a statement. Because code in the try..finally block is guaranteed to execute, it is typically used to perform any necessary “clean-up” finally code after a block executes. In this example, the block is used to delete an finally ActionScript object, regardless of whether an error occurred.
  • Page 738 Within the RecordSet class’s method, one of these previously defined error objects sortRows() are thrown depending on the type of exception that occurred. The following code snippet shows how this code might look. // Within RecordSet.as class file... function sortRows() { if(recordSetErrorCondition) { throw new RecordSetException();...
  • Page 739 typeof Availability Flash Player 5. Usage typeof(expression) Parameters A string, movie clip, button, object, or function. expression Description Operator; a unary operator placed before a single parameter. The operator causes the typeof Flash interpreter to evaluate ; the result is a string specifying whether the expression is expression a string, movie clip, object, function, number, or Boolean value.
  • Page 740 undefined Availability Flash Player 5. Usage undefined Parameters None. Returns Nothing. Description A special value, usually used to indicate that a variable has not yet been assigned a value. A reference to an undefined value returns the special value . The ActionScript code undefined returns the string .
  • Page 741 unescape Availability Flash Player 5. Usage unescape(x) Parameters A string with hexadecimal sequences to escape. Returns A string decoded from a URL-encoded parameter. Description Function; evaluates the parameter as a string, decodes the string from URL-encoded format (converting all hexadecimal sequences to ASCII characters), and returns the string. Example The following example illustrates the escape-to-unescape conversion process.
  • Page 742 Example The following example unloads the movie clip on the main Timeline, and loads draggable_mc into level 4. movie.swf on (press) { unloadMovie ("_root.draggable_mc"); loadMovieNum ("movie.swf", 4); The following example unloads the movie loaded into level 4. on (press) { unloadMovieNum (4);...
  • Page 743 updateAfterEvent() Availability Flash Player 5. Usage updateAfterEvent() Parameters None. Returns Nothing. Description Function; updates the display (independent of the frames per second set for the movie) when you call it within an handler or as part of a function or method that you pass to onClipEvent() .
  • Page 744: Video Class

    You cannot declare a variable scoped to another object as a local variable: my_array.length = 25; // ok var my_array.length = 25; // syntax error When you use , you can strictly type the variable; see “Strict data typing” on page 38 Note: Classes defined in external scripts also support public, private, and static variable scopes.
  • Page 745 Property Description Specifies whether the video should be smoothed (interpolated) when it Video.smoothing is scaled. Read-only; the width of the video stream, in pixels. Video.width Video.attachVideo() Availability Flash Player 6; the ability to work with Flash Video (FLV) files was added in Flash Player 7. Usage my_video.attachVideo(source) Parameters...
  • Page 746 Video.clear() Availability Flash Player 6. Usage my_video.clear() Parameters None. Returns Nothing. Description Method; clears the image currently displayed in the Video object. This is useful when, for example, you want to display standby information without having to hide the Video object. See also Video.attachVideo() Video.deblocking...
  • Page 747 Video.height Availability Flash Player 6. Usage my_video.height Description Read-only property; an integer specifying the height of the video stream, in pixels. For live streams, this value is the same as the property of the Camera object that is Camera.height capturing the video stream. For FLV files, this value is the height of the file that was exported as FLV.
  • Page 748 Video.width Availability Flash Player 6. Usage my_video.width Description Read-only property; an integer specifying the width of the video stream, in pixels. For live streams, this value is the same as the property of the Camera object that is Camera.width capturing the video stream. For FLV files, this value is the width of the file that was exported as an FLV file.
  • Page 749 Description Statement; tests an expression and runs a statement or series of statements repeatedly in a loop as long as the expression is true Before the statement block is run, the is tested; if the test returns , the statement condition true block is run.
  • Page 750 parameter becomes the context in which the properties, variables, and functions in object parameter are read. For example, if , and two of the statement(s) object my_array properties specified are , those properties are automatically read as length concat . In another example, if my_array length my_array.concat...
  • Page 751: Xml Class

    You could also write this code using the action. However, if were not tellTarget someOther_mc a movie clip, but an object, you could not use the action. with tellTarget ("someOther_mc") { _x = 50; _y = 100; gotoAndStop(3); action is useful for accessing multiple items in a scope chain list simultaneously. In the with following example, the built-in object is placed at the front of the scope chain.
  • Page 752 Method summary for the XML class Method Description Adds or changes HTTP headers for operations. XML.addRequestHeader() POST Appends a node to the end of the specified object’s child list. XML.appendChild() Clones the specified node and, optionally, recursively clones all children. XML.cloneNode() Creates a new XML element.
  • Page 753 Property Description Read-only; references the previous sibling in the parent node’s child list. XML.previousSibling A numeric status code indicating the success or failure of an XML XML.status document parsing operation. Specifies information about a document’s XML declaration. XML.xmlDecl Collections summary for the XML class Method Description Returns an associative array containing all of the attributes of the...
  • Page 754 Example Usage 1: The following example creates an new, empty XML object. my_xml = new XML(); Usage 2: The following example creates an XML object by parsing the XML text specified in the parameter, and populates the newly created XML object with the resulting XML source document tree.
  • Page 755 Example This example adds a custom HTTP header named with a value of to an XML SOAPAction object named my_xml my_xml.addRequestHeader("SOAPAction", "'Foo'"); This next example creates an array named that contains two alternating HTTP headers headers and their associated values. The array is passed as a parameter to the addRequestHeader() method.
  • Page 756 XML.attributes Availability Flash Player 5. Usage my_xml.attributes Parameters None. Returns An array. Description Property; an associative array containing all attributes of the specified XML object. Example The following example writes the names of the XML attributes to the Output window. str = "<mytag name=\"Val\">...
  • Page 757 XML.childNodes Availability Flash Player 5. Usage my_xml.childNodes Parameters None. Returns An array. Description Property (read-only); an array of the specified XML object’s children. Each element in the array is a reference to an XML object that represents a child node. This is a read-only property and cannot be used to manipulate child nodes.
  • Page 758 XML.contentType Availability Flash Player 6. Usage my_xml.contentType Description Property; the MIME type that is sent to the server when you call the XML.send() method. The default is application/x-www-form-urlencoded. XML.sendAndLoad() See also XML.send() XML.sendAndLoad() XML.createElement() Availability Flash Player 5. Usage my_xml.createElement(name) Parameters The tag name of the XML element being created.
  • Page 759 XML.createTextNode() Availability Flash Player 5. Usage my_xml.createTextNode(text) Parameters The text used to create the new text node. text Returns Nothing. Description Method; creates a new XML text node with the specified text. The new node initially has no parent, and text nodes cannot have children or siblings. This method returns a reference to the XML object representing the new text node.
  • Page 760 XML.firstChild Availability Flash Player 5. Usage my_xml.firstChild Description Property (read-only); evaluates the specified XML object and references the first child in the parent node’s children list. This property is if the node does not have children. This null property is undefined if the node is a text node. This is a read-only property and cannot be used to manipulate child nodes;...
  • Page 761 XML.getBytesTotal() Availability Flash Player 6. Usage XML.getBytesTotal() Parameters None. Returns An integer. Description Method; returns the size, in bytes, of the XML document. See also XML.getBytesLoaded() XML.hasChildNodes() Availability Flash Player 5. Usage my_xml.hasChildNodes() Parameters None. Returns A Boolean value. Description Method;...
  • Page 762 XML.ignoreWhite Availability Flash Player 5. Usage my_xml.ignoreWhite = boolean XML.prototype.ignoreWhite = boolean Parameters A Boolean ( ) value. boolean true false Description Property; default setting is . When set to , text nodes that contain only white space are false true discarded during the parsing process.
  • Page 763 XML.lastChild Availability Flash Player 5. Usage my_xml.lastChild Description Property (read-only); evaluates the XML object and references the last child in the parent node’s child list. This method returns if the node does not have children. This is a read-only null property and cannot be used to manipulate child nodes;...
  • Page 764 When is executed, the XML object property is set to . When the XML data load() loaded false finishes downloading, the property is set to , and the method is invoked. loaded true onLoad() The XML data is not parsed until it is completely downloaded. If the XML object previously contained any XML trees, they are discarded.
  • Page 765 XML.nodeName Availability Flash Player 5. Usage my_xml.nodeName Description Property; the node name of the XML object. If the XML object is an XML element == 1), is the name of the tag representing the node in the XML file. For nodeType nodeName example,...
  • Page 766 XML.onData Availability Flash Player 5 Usage my_xml.onData = function(src) { // your statements here Parameters The raw data, usually in XML format, that is sent by the server. Returns Nothing. Description Event handler; invoked when XML text has been completely downloaded from the server, or when an error occurs downloading XML text from a server.
  • Page 767 XML.onLoad() Availability Flash Player 5. Usage my_xml.onLoad = function (success) { //your statements here Parameters A Boolean value indicating whether the XML object was successfully loaded with a success operation. XML.load() XML.sendAndLoad() Returns Nothing. Description Event handler; invoked by Flash Player when an XML document is received from the server. If the XML document is received successfully, the parameter is .
  • Page 768 XML.parentNode Availability Flash Player 5. Usage my_xml.parentNode Description Property (read-only); references the parent node of the specified XML object, or returns null the node has no parent. This is a read-only property and cannot be used to manipulate child nodes; use , and to manipulate children.
  • Page 769 XML.removeNode() Availability Flash Player 5. Usage my_xml.removeNode() Parameters None. Returns Nothing. Description Method; removes the specified XML object from its parent. All descendants of the node are also deleted. XML.send() Availability Flash Player 5. Usage my_xml.send(url, [window]) Parameters The destination URL for the specified XML object. The browser window to display data returned by the server: specifies the current window...
  • Page 770 XML.sendAndLoad() Availability Flash Player 5; behavior changed in Flash Player 7. Usage my_xml.sendAndLoad(url, targetXMLobject) Parameters The destination URL for the specified XML object. If the SWF file issuing this call is running in a web browser, must be in the same domain as the SWF file; for details, see “Description,”...
  • Page 771 XML.status Availability Flash Player 5. Usage my_xml.status Description Property; automatically sets and returns a numeric value indicating whether an XML document was successfully parsed into an XML object. The numeric status codes and a description of each are listed as follows: •...
  • Page 772 Example The following code is an example of that sends to the XML.toString() <h1>test</h1> Output panel. node = new XML("<h1>test</h1>"); trace(node.toString()); See also XML.docTypeDecl XML.xmlDecl XML.xmlDecl Availability Flash Player 5. Usage my_xml.xmlDecl Description Property; specifies information about a document’s XML declaration. After the XML document is parsed into an XML object, this property is set to the text of the document’s XML declaration.
  • Page 773: Xmlnode Class

    XMLNode class Availability Flash Player 5. Description The XMLnode class supports the following properties, methods, and collections; for information on their usage, see the corresponding XML class entries. Property, method, or collection Corresponding XML class entry appendChild() XML.appendChild() attributes XML.attributes childNodes XML.childNodes cloneNode()
  • Page 774: Xmlsocket Class

    XMLSocket class Availability Flash Player 5. Description The XMLSocket class implements client sockets that allow the computer running Flash Player to communicate with a server computer identified by an IP address or domain name. The XMLSocket class is useful for client-server applications that require low latency, such as real-time chat systems.
  • Page 775 Method summary for the XMLSocket class Method Description Closes an open socket connection. XMLSocket.close() Establishes a connection to the specified server. XMLSocket.connect() Sends an XML object to the server. XMLSocket.send() Event handler summary for the XMLSocket class Event handler Description An event handler that is invoked when an XMLSocket connection XMLSocket.onClose() is closed.
  • Page 776 XMLSocket.close() Availability Flash Player 5. Usage myXMLSocket.close() Parameters None. Returns Nothing. Description Method; closes the connection specified by XMLSocket object. See also XMLSocket.connect() XMLSocket.connect() Availability Flash Player 5; behavior changed in Flash Player 7. Usage myXMLSocket.connect(host, port) Parameters A fully qualified DNS domain name, or an IP address in the form aaa.bbb.ccc.ddd. You host can also specify to connect to the host server on which the SWF file resides.
  • Page 777 In SWF files running in a version of the player earlier than Flash Player 7, must be in the same superdomain as the SWF file that is issuing this call. For example, a SWF file at www.someDomain.com can load variables from a SWF file at store.someDomain.com, because both files are in the same superdomain of someDomain.com.
  • Page 778 XMLSocket.onClose() Availability Flash Player 5. Usage myXMLSocket.onClose() = function() { // your statements here Parameters None. Returns Nothing. Description Event handler; invoked only when an open connection is closed by the server. The default implementation of this method performs no actions. To override the default implementation, you must assign a function containing your own actions.
  • Page 779 Example The following example illustrates the process of specifying a replacement function for the method in a simple chat application. onConnect The function controls which screen users are taken to, depending on whether a connection is successfully established. If the connection is successfully made, users are taken to the main chat screen on the frame labeled .
  • Page 780 Description Event handler; invoked when a message has been downloaded from the server, terminated by a zero byte. You can override to intercept the data sent by the server without XMLSocket.onData parsing it as XML. This is a useful if you’re transmitting arbitrarily formatted data packets, and you’d prefer to manipulate the data directly when it arrives, rather than have Flash Player parse the data as XML.
  • Page 781 handler must first be installed in the XMLSocket object as follows: onXML socket.onXML = myOnXML; The function is assumed to be a user-defined function that displays the displayMessage() message received by the user. function myOnXML(doc) { var e = doc.firstChild; if (e != null &&...
  • Page 782 Chapter 12: ActionScript Dictionary...
  • Page 783: Appendix A Error Messages

    APPENDIX A Error Messages Macromedia Flash MX 2004 and Macromedia Flash MX Professional 2004 provide enhanced compile-time error reporting if you specify ActionScript 2.0 (the default) when you publish a file. The following table contains a list of error messages that the Flash compiler can generate.
  • Page 784 Error number Message text 1114 There is no interface defined with this name. 1115 A class may not extend an interface. 1116 An interface may not extend a class. 1117 An interface name is expected after the ‘implements’ keyword. 1118 A class may not implement a class, only interfaces.
  • Page 785 Error number Message text 1146 The property being referenced does not have the static attribute. 1147 This call to super does not match the superconstructor. 1148 Only the public attribute is allowed for interface methods. 1149 The import keyword cannot be used as a directive. 1150 You must export your movie as Flash 7 to use this action.
  • Page 786 Error number Message text 1178 Instance variables and functions may not be used to initialize static variables. 1179 Runtime circularities were discovered between the following classes:%1 1180 The currently targeted Flash Player does not support Debugging. 1181 The currently targeted Flash Player does not support the releaseOutside event. 1182 The currently targeted Flash Player does not support the dragOver event.
  • Page 787: Appendix B: Operator Precedence And Associativity

    APPENDIX B Operator Precedence and Associativity This table lists all of the ActionScript operators and their associativity, from highest to lowest precedence. Operator Description Associativity Highest precedence Unary plus Right to left Unary minus Right to left Bitwise NOT Right to left Logical NOT Right to left Logical NOT (Flash 4 style)
  • Page 788 Operator Description Associativity String concatenation (formerly &) Left to right Subtract Left to right << Bitwise left shift Left to right >> Bitwise right shift Left to right >>> Bitwise right shift (unsigned) Left to right < Less than Left to right <= Less than or equal to Left to right...
  • Page 789: Appendix C: Keyboard Keys And Key Code Values

    APPENDIX C Keyboard Keys and Key Code Values The following tables list all of the keys on a standard keyboard and the corresponding ASCII key code values that are used to identify the keys in ActionScript. For more information, see the class entry in Chapter 12, “ActionScript Dictionary,”...
  • Page 790: Keys On The Numeric Keypad

    Letter or number key Key code Keys on the numeric keypad The following table lists the keys on a numeric keypad, with the corresponding ASCII key code values that are used to identify the keys in ActionScript. Numeric keypad key Key code Numbpad 0 Numbpad 1...
  • Page 791: Function Keys

    Numeric keypad key Key code Numbpad 9 Multiply Enter Subtract Decimal Divide Function keys The following table lists the function keys on a standard keyboard, with the corresponding ASCII key code values that are used to identify the keys in ActionScript. Function key Key code Function keys...
  • Page 792: Other Keys

    Other keys The following table lists keys on a standard keyboard other than letters, numbers, numeric keypad keys, or function keys, with the corresponding ASCII key code values that are used to identify the keys in ActionScript. Key code Backspace Clear Enter Shift...
  • Page 793 Key code " ' Other keys...
  • Page 794 Appendix C: Keyboard Keys and Key Code Values...
  • Page 795: Appendix D: Writing Scripts For Earlier Versions Of Flash Player

    ActionScript has changed considerably with the release of Macromedia Flash MX 2004 and Macromedia Flash MX Professional 2004. When you create content for Flash Player 7, you’ll take advantage of the full power of ActionScript. You can still use Flash MX 2004 to create content for earlier versions of Flash Player, but you won’t be able to use every ActionScript element.
  • Page 796: Using Flash Mx 2004 To Create Content For Flash Player 4

    Using Flash MX 2004 to create content for Flash Player 4 To use Flash MX 2004 to create content for Flash Player 4, specify Flash Player 4 in the Flash tab of the Publish Settings dialog box (File > Publish Settings). Flash Player 4 ActionScript has only one basic primitive data type, which is used for both numeric and string manipulation.
  • Page 797 • In Flash 4, the escape sequence generated a carriage return character (ASCII 13). In Flash 5 and later, to comply with the ECMA-262 standard, generates a line-feed character (ASCII 10). An sequence in Flash 4 FLA files is automatically converted to •...
  • Page 798 Appendix D: Writing Scripts for Earlier Versions of Flash Player...
  • Page 799: Appendix E: Object-Oriented Programming With Actionscript 1

    APPENDIX E Object-Oriented Programming with ActionScript 1 The information in this appendix was excerpted from the Macromedia Flash MX documentation and provides information on using the ActionScript 1 object model to write scripts. It is included here for the following reasons: •...
  • Page 800 Objects in ActionScript can be pure containers for data, or they can be graphically represented on the Stage as movie clips, buttons, or text fields. All movie clips are instances of the built-in class MovieClip, and all buttons are instances of the built-in class Button. Each movie clip instance contains all the properties (for example, ) and all the _height...
  • Page 801 After you define the constructor function you must create an instance of the object. Use the operator before the name of the constructor function and assign the new instance a variable name. For example, the following code uses the operator to create a Circle object with a radius of 5, and assigns it to the variable myCircle myCircle = new Circle(5);...
  • Page 802 Defining event handler methods in ActionScript 1 You can create an ActionScript class for movie clips and define the event handler methods in the prototype object of that new class. Defining the methods in the prototype object makes all the instances of this symbol respond the same way to these events.
  • Page 803 function myClipClass(){} myClipClass.prototype = new MovieClip(); myClipClass.prototype.onLoad = function(){ trace("movie clip loaded"); myClipClass.prototype.onPress = function(){ trace("pressed"); myClipClass.prototype.onEnterFrame = function(){ trace("movie clip entered frame"); myClipClass.prototype.myfunction = function(){ trace("myfunction called"); Object.registerClass("myclipID",myClipClass); _root.attachMovie("myclipID","ablue2",3); Creating inheritance in ActionScript 1 Inheritance is a means of organizing, extending, and reusing functionality. Subclasses inherit properties and methods from superclasses and add their own specialized properties and methods.
  • Page 804 Instead of adding to the MountainBike class and the Tricycle class, you can create the roll() MountainBike class with Bike as its superclass: MountainBike.prototype = new Bike(); Now you can call the method of MountainBike, as shown in the following: roll() MountainBike.roll();...
  • Page 805 Invoking a function using the Function.call() method in ActionScript 1 method invokes the function represented by a Function object. Function.call() In almost all cases, the function call operator ( ) can be used instead of the method. The call() function call operator creates code that is concise and readable. The method is primarily call() useful when the...
  • Page 806 Appendix E: Object-Oriented Programming with ActionScript 1...
  • Page 807: Index

    INDEX accessing object properties 49 balance (sound), controlling 104 actions bitwise operators 47 defined 26 Boolean values 35 repeating 56 comparing 47 Actions panel 58 defined 26 Actions toolbox 58 braces. See curly braces yellow items in 61 brackets. See array access operators ActionScript breakpoints ActionScript 2.0 compiler error messages 783...
  • Page 808 child node 181 code hints 61 class files, creating 157 manually displaying 65 class members 114 not being displayed 65 and subclasses 167 specifying settings for 64 created once per class 165 triggering 62, 63 creating 165 using 63 example of using 166 collisions, detecting 105 classes between movie clip and Stage point 106...
  • Page 809 strictly typing 38 drawing String 34 lines and fills 107 undefined 36 shapes 131 data, external 177 duplicating, movie clips 126 access between cross-domain SWFs 189 dynamic classes 173 and LoadVars object 180 and messages 185 and server-side scripts 179 ECMA-262 and XML 181 compliance 15...
  • Page 810 external class files passing parameters to 52 creating 157 returning values 53 using classpaths to locate 169 sample 28 external media 193–201 loading MP3 files 195 loading SWF files and JPEG files 194 get/set methods of classes 172 overview of loading 193 getAscii() method 96 playing FLV files 197 getting information from remote files 177...
  • Page 811 186 actions 57 JPEG files embedding in text fields 152 loading into movie clips 124, 194 Macromedia Director, communicating with 187 preloading 199 manipulating numbers 35 jumping to a URL 93 masks 132 and device fonts 132...
  • Page 812 movie clips MP3 files activating with keyboard 98 and ID3 tags 196 adding parameters 128 loading into movie clips 195 adjusting color 100 preloading 201 and _root property 123 multidimensional arrays 50 and with statement 122 multiple inheritance, not allowed 163 assigning button states to 88 multiple languages, using in scripts 26 attaching on() and onClipEvent() handlers 87...
  • Page 813 associativity 45, 787 initializing at runtime 134 bitwise 47 of movie clips 125 combining with values 45 of objects, accessing 114 comparison 46 Properties tab, Debugger 74 dot 49 public attribute for class members 164 equality 47 punctuation balance, checking for 67 logical 47 numeric 45 precedence 787...
  • Page 814 security 188–191 SWF files and policy files 190 controlling in Flash Player 187 and porting scripts to Flash Player 7 17, 19, 20 creating sound controls 101 data access across domains 189, 190 embedding in text fields 152 semicolon 31 jumping to frame or scene 92 sending information loading and unloading 123...
  • Page 815 text fields 135 determining data type 37 and HTML text 143 modifying in Debugger 72 applying cascading style sheets 142 naming 62 avoiding variable name conflicts 136 naming rules 41 creating and removing at runtime 137 passing content 43 default properties 138 referencing value 44 determining required size 139 scoping 41...
  • Page 816 Index...

Table of Contents