Flex ActionScript Language Reference
Trademarks ActiveEdit, ActiveTest, Add Life to the Web, Afterburner, Aftershock, Andromedia, Allaire, Animation PowerPack, Aria, Attain, Authorware, Authorware Star, Backstage, Blue Sky Software, Blue Sky, Breeze, Bright Tiger, Clustercats, ColdFusion, Contents Tab Composer, Contribute, Design In Motion, Director, Dream Templates, Dreamweaver, Drumbeat 2000, EDJE, EJIPT, Extreme 3D, Fireworks, Flash, FlashHelp, Flash Lite, FlashPaper, Flex, Flex Builder, Fontographer, FreeHand, Generator, Help To Source, Ho
CONTENTS INTRODUCTION: Getting Started with ActionScript ....................... 5 Intended audience . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Using the documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Typographical conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Terms used in this document. . . . . . . . . . . . . . . . . . . . . . . . . . . . .
CHAPTER 3: Working with External Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67 Sending and loading variables to and from a remote source . . . . . . . . . . . . . . . . . . 67 Sending messages to and from Flash Player . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72 PART II: Reference CHAPTER 4: About the ActionScript Language Reference . . . . . . . . . . . . . . . . . 77 Sample entry for most ActionScript elements . . . . . . . . . . . . . . . . . . . . . . . . .
INTRODUCTION Getting Started with ActionScript Macromedia Flex developers can use ActionScript to extend the functionality of their Flex applications. ActionScript is an ECMAScript-based language that provides support for objectoriented development. You are not required to use ActionScript to use Flex, but it provides flow control and object manipulation features that are not available in strict MXML. Intended audience This manual assumes that you already installed Macromedia Flex and know how to use it.
• Chapter 7, “ActionScript for Flash,” on page 490 describe functions, properties, and classes of Macromedia Flash Player that you can use in a Macromedia Flex application, if appropriate. • Appendix A, “Deprecated Flash 4 operators,” on page 809 lists all the ActionScript operators and their associativity. • Appendix B, “Keyboard Keys and Key Code Values,” on page 811 lists all the keys on a standard keyboard and the corresponding ASCII key code values that are used to identify the keys in ActionScript.
This part includes information on using the ActionScript language. For information on the classes and language elements you can use in your scripts, see Part II, “Reference.” Chapter 1: ActionScript Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 Chapter 2: Creating Custom Classes with ActionScript 2.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 Chapter 3: Working with External Data. . . . . . . . . . . . . . . . . . . . . . . . . . .
CHAPTER 1 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 general rules described in this section apply to all ActionScript. Most ActionScript terms also have individual requirements; for the rules for a specific term, see its entry in Part II, “Reference.
Differences between ActionScript and JavaScript ActionScript is similar to the core JavaScript programming language. You don’t need to know JavaScript to use and learn ActionScript; however, if you know JavaScript, ActionScript will seem familiar. This manual does not attempt to teach general programming. There are many resources that provide more information about general programming concepts and the JavaScript language.
Terminology As with all scripting languages, ActionScript uses its own terminology. The following list provides an introduction to important ActionScript terms: Boolean is a true or false value. Classes are data types that you can create to define a new type of object. To define a class, you use the class keyword in a script file. Constants are elements that don’t change. For example, the constant Key.TAB always has the same meaning: it indicates the Tab key on a keyboard.
Identifiers are names used to indicate a variable, property, object, function, or method. The first character must be a letter, underscore (_), or dollar sign ($). Each subsequent character must be a letter, number, underscore, or dollar sign. For example, firstName is the name of a variable. Instances are objects that contain all the properties and methods of a particular class.
Parameters (also called arguments) are placeholders that let you pass values to functions. For example, the following welcome() function uses two values it receives in the parameters firstName and hobby: function welcome(firstName:String, hobby:String):String { var welcomeText:String = "Hello, " + firstName + ". I see you enjoy " + hobby +".
• “Keywords and reserved words” on page 17 • “Constants” on page 18 Case sensitivity In a case-sensitive programming language, variable names that differ only in case (book and Book) are considered different from each other. Therefore, it’s good practice to follow consistent capitalization conventions, such as those used in this manual, to make it easy to identify names of functions and variables in ActionScript code. Keywords, class names, variables, method names, and so on are case sensitive.
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. The following examples show the opening brace on same line as the declaration: // Event handler my_btn.
Semicolons are required within for loops, as shown in the following example: //For loop that adds numbers 1-10 var sum:Number = 0; for (var i=1; i<=10; i++) { sum += i; } Parentheses When you define a function, place any parameters inside parentheses [()]: function myFunction (name:String, age:Number, reader:Boolean){ // your code here } When you call a function, include any parameters passed to the function in parentheses, as shown in the following example: myFunction ("Steve", 10, true); You can also u
Comments can be any length without affecting the size of the exported file, and they do not need to follow rules for ActionScript syntax or keywords. To create a comment block, place /* at the beginning of the commented lines and */ at the end. This technique lets you create lengthy comments without adding // at the beginning of each line. By placing large chunks of script in a comment block, called commenting out a portion of your script, you can test specific parts of a script.
Constants A constant is a property whose value never changes. ActionScript contains predefined constants. For example, the constants BACKSPACE, ENTER, SPACE, and TAB are properties of the Key object and refer to keyboard keys. To test whether the user is pressing the Enter key, you could use the following statement: if(Key.getCode() == Key.ENTER) { alert = "Are you ready to play?"; control_mc.gotoAndStop(5); } Flash does not enforce constants; that is, you can’t define your own constants.
String data type A string is a sequence of characters such as letters, numbers, and punctuation marks. You enter strings in an ActionScript statement by enclosing them in single (') or double (") quotation marks. A common way that you use the string type is to assign a string to a variable. For example, in the following statement, "L7" is a string assigned to the variable favoriteBand_str: var favoriteBand_str:String = "L7"; You can use the addition (+) operator to concatenate, or join, two strings.
You can also use methods of the built-in Math and Number classes to manipulate numbers. For more information on the methods and properties of these classes, see the “Math class” and “Number class” entries. The following example uses the sqrt() (square root) method of the Math class to return the square root of the number 100: Math.sqrt(100); The following example traces a random integer between 10 and 17 (inclusive): var bottles:Number = 0; bottles = 10 + Math.floor(Math.
Object data type An object is a collection of properties. Each property has a name and a value. The value of a property can be any Flash data type—even the object data type. This lets you arrange objects inside each other, or nest them. To specify objects and their properties, you use the dot (.) operator. For example, in the following code, hoursWorked is a property of weeklyStats, which is a property of employee: employee.weeklyStats.
Creating movie clips dynamically Using ActionScript to create movie clips dynamically is useful when you want to avoid manually creating movie clips on the Stage or attaching them from the library. For example, you might create an image gallery with a large number of thumbnails that you want to organize on the Stage. Using MovieClip.createEmptyMovieClip() lets you create an application entirely using ActionScript. To dynamically create a movie clip, use MovieClip.
Several methods and functions return null if no value has been set. The following example demonstrates how you can use null to test if form fields currently have form focus: if (Selection.getFocus() == null) { trace("no selection"); } Undefined data type The undefined data type has one value, undefined, and is automatically assigned to a variable to which a value hasn’t been assigned, either by your code or user interaction.
• “Casting objects” on page 25 • “Determining an item’s data type” on page 26 Automatic data typing If you do not explicitly define an item as holding either a number, a string, or another data type, Flash Player will, at runtime, try to determine the data type of an item when it is assigned.
function welcome(firstName:String, age:Number){ } // strict typing of parameter and return value function square(x:Number):Number { var squared:Number = x*x; return squared; } Because you must use the var keyword when strictly typing variable, you can’t strictly type a global variable (see “Scoping and declaring variables” on page 28). You can declare the data type of objects based on built-in classes (Button, Date, MovieClip, and so on) and on classes and interfaces that you create.
The syntax for casting is type(item), where you want the compiler to behave as if the data type of item is type. Casting is essentially a function call, and the function call returns null if the cast fails at runtime. If the cast succeeds, the function call returns the original object. However, the compiler cannot determine whether a cast will fail at runtime and won’t generate compile-time errors in those cases.
The following example shows how you can use these operators and the difference between them: //Create a new instance of LoadVars class var myLV:LoadVars = new LoadVars(); //instanceof operator specifies instance of what class if (myLV instanceof LoadVars) { trace("yes, it's a loadvars instance"); } //typeof operator does not specify class, only specifies that myLV is an object var typeResult:String = typeof(myLV); trace(typeResult); About variables A variable is a container that holds information.
You should not use any element in the ActionScript language as a variable name because it can cause syntax errors or unexpected results. In the following example, if you name a variable String and then try to create a String object using new String(), the new object is undefined: // This code works as expected var hello_str:String = new String(); trace(hello_str.length); // returns 0 // But if you give a variable the same name as a built-in class....
You can assign a data type to a local variable when you define it, which helps prevent you from assigning the wrong type of data to an existing variable. For more information, see “Strict data typing” on page 24. Global variables Global variables and functions are visible to every scope in your document. To create a variable with global scope, use the _global identifier before the variable name and do not use the var = syntax. For example, the following code creates the global variable myName: var _global.
var myWebSite = "http://www.macromedia.com"; getURL(myWebSite); // browser displays www.macromedia.com You can change the value of a variable in a script as many times as you want. The type of data that a variable contains affects how and when the variable’s value changes. Primitive data types, such as strings and numbers, are “passed by value”; this means that the current value of the variable is used, rather than a reference to that value.
In the following example, myArray contains an Array object, so it is passed to function zeroArray() by reference. The function zeroArray() accepts an Array object as a parameter and sets all the elements of that array to 0. It can modify the array because the array is passed by reference. function zeroArray (theArray:Array):Void { var i:Number; for (i=0; i < theArray.
Operator precedence and associativity When two or more operators are used in the same statement, some operators take precedence over others. ActionScript follows a precise hierarchy to determine which operators to execute first. For example, multiplication is always performed before addition; however, items in parentheses [()] take precedence over multiplication. So, without parentheses, ActionScript performs the multiplication in the following example first: total = 2 + 4 * 3; The result is 14.
Operator Description Associativity * Multiply Left to right / Divide Left to right % Modulo Left to right + Unary plus Right to left - Unary minus Right to left << Bitwise left shift Left to right >> Bitwise right shift Left to right >>> Bitwise right shift (unsigned) Left to right instanceof Instance of (finds the class of which the object is an Left to right instance) Requires Flash Player 6 or later < Less than Left to right <= Less than or equal to Left to right > Gre
This process is also known as a preincrement. In the following example, age is incremented after the test is performed: if (age++ >= 30) This process is also known as a postincrement.
The following table lists the ActionScript comparison operators: Operator Operation performed < Less than: Returns true if the left operand is mathematically smaller than the right operand. Returns true if the left operand alphabetically precedes the right operand (for example, a < b). > Greater than: Returns true if the left operand is mathematically larger than the right operand. Returns true if the left operand alphabetically follows the right operand (for example, b > a).
Logical operators Logical operators compare Boolean values (true and false) and return a third Boolean value. For example, if both operands evaluate to true, the logical AND (&&) operator returns true. If one or both of the operands evaluate to true, the logical OR (||) operator returns true. Logical operators are often used with comparison operators to determine the condition of an if statement.
Equality operators You can use the equality (==) operator to determine whether the values or references of two operands are equal. This comparison returns a Boolean (true or false) value. If the operands are strings, numbers, or Boolean values, they are compared by value. If the operands are objects or arrays, they are compared by reference. It is a common mistake to use the assignment operator to check for equality.
This code is equivalent to the following code, which is slightly easier to read: flavor = getIceCreamFlavor(); if (flavor != "vanilla") { trace ("Flavor was " + flavor + ", not vanilla.
Array access operator. You can use the array access operator to dynamically set and retrieve instance names and variables. For example, in the following code, the expression inside the array access operator is evaluated, and the result of the evaluation is used as the name of the variable to be retrieved from movie clip name: name["mc" + i] In ActionScript 2.
Checking conditions Statements that check whether a condition is true or false begin with the term if. If the condition evaluates to true, ActionScript executes the next statement. If the condition doesn’t exist, ActionScript skips to the next statement outside the block of code. To optimize your code’s performance, check for the most likely conditions first. The following statements test three conditions. The term else if specifies alternative tests to perform if previous conditions are false.
Children include other functions, objects, and variables.
A well-written function can be thought of as a “black box.” If it has carefully placed comments about its input, output, and purpose, a user of the function does not need to understand exactly how the function works internally.
The parameter initials in the function fillOutScorecard() is similar to a local variable; it exists while the function is called and ceases to exist when the function exits. If you omit parameters during a function call, the omitted parameters are passed as undefined. If you provide extra parameters in a function call that are not required by the function declaration, they are ignored. Using variables in a function Local variables are valuable tools for organizing code and making it easy to understand.
Calling a user-defined function To call a function, enter the target path to the name of the function, if necessary, and pass any required parameters inside parentheses. For example, the following statement invokes the function sqr() in the object mathLib, passes the parameter 3 to it, and stores the result in the variable temp: var temp:Number = mathLib.
CHAPTER 2 Creating Custom Classes with ActionScript 2.0 ActionScript 2.0 provides several powerful programming features found in other programming languages, such as Java. ActionScript 2.0 encourages program structures that are reusable, scalable, robust, and maintainable. It also decreases development time by providing users thorough coding assistance and debugging information. ActionScript 2.0 conforms more closely to the ECMA-262 Edition 3 standard (see www.ecma-international.
• “Encapsulation” on page 47 • “Polymorphism” on page 47 Objects Think of a real-world object, such as a cat. A cat could be said to have properties (or states), such as name, age, and color; a cat also has behaviors such as sleeping, eating, and purring. In the world of object-oriented programming, objects also have properties and behaviors. Using objectoriented techniques, you can model a real-world object (such as a cat) or a more abstract object (such as a chemical process).
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. For example, suppose you are working with a team of programmers, each of whom is working on a different part (class) of the same application.
For example, you might start with a class called Mammal that has play() and sleep() methods. You then create Cat, Monkey, and Dog subclasses to extend the Mammal class. The subclasses override the play() method from the Mammal class, to reflect the habits of those particular kinds of animals. Monkey implements the play() method to swing from trees; Cat implements the play() method to pounce at a ball of yarn; Dog implements the play() method to fetch a ball.
4. In your text editor, enter the following code (in this procedure, new code you type in each step is bold): class Person { } This is called the class declaration. In its most basic form, a class declaration consists of the class keyword, followed by the class name (Person, in this case), and then left and right curly braces ({}). Everything between the braces is called the class body and is where the class’s properties and methods are defined.
The Person() constructor function takes two parameters, myName and myAge, and assigns those parameters to the name and age properties. The two function parameters are strictly typed as String and Number, respectively. Unlike other functions, the constructor function should not declare its return type. For more information about constructor functions, see “Constructor functions” on page 52. If you don’t create a constructor function, an empty one is created automatically during compilation. 7.
This code invokes the Person class’s constructor function, passing as parameters the values "Nate" and 32. The newPerson variable is typed as a Person object. Typing your objects in this way enables the compiler to ensure that you don’t try to access properties or methods that aren’t defined in the class. See “Strict data typing” on page 24. (The exception is if you declare the class to be dynamic using the dynamic keyword. See “Creating dynamic classes” on page 56.
If you are creating multiple custom classes, use packages to organize your class files. A package is a directory that contains one or more class files and resides in a designated classpath directory. Class names must be fully qualified within the file in which it is declared—that is, it must reflect the directory (package) in which it is stored. For example, a class named myClasses.education.curriculum.RequiredClass is stored in the myClasses/education/curriculum package.
Creating properties and methods A class’s members consist of properties (variable declarations) and methods (function definitions). You must declare and define all properties and methods inside the class body (the curly braces [{}]); otherwise, an error will occur during compilation. Any variable declared within a class, but outside a function, is a property of the class.
Private members (properties and methods) are accessible only to the class that defines those members and to subclasses of that original class. Instances of the original class, or instances of subclasses of that class, cannot access privately declared properties and methods; that is, private members are accessible only within class definitions; not at the instance level. For example, you could create a subclass of LoginClass called NewLoginClass.
return "Hello world"; } } This rule applies only to instance variables (variables that are copied into each instance of a class), not class variables (variables that belong to the class). For more information about these kinds of variables, see “Instance and class members” on page 60.
Multiple inheritance, or inheriting from more than one class, is not allowed in ActionScript 2.0. However, classes can effectively inherit from multiple classes if you use individual extends statements, as shown in the following example: // not allowed class C extends A, B {} // allowed class B extends A {} class C extends B {} You can also use interfaces to provide a limited form of multiple inheritance. See “Interfaces” on page 47 and “Creating and using interfaces” on page 58.
Subclasses of dynamic classes are also dynamic, with one exception. Subclasses of the built-in MovieClip class are not dynamic by default, even though the MovieClip class itself is dynamic.
To reference a class that resides in a package directory, you can either specify its fully qualified class name or import the package by using the import statement (see the following section). Creating and using interfaces An interface in object-oriented programming is like a class whose methods have been declared, but otherwise don’t “do” anything. That is, an interface consists of “empty” methods. One use of interfaces is to enforce a protocol between otherwise unrelated classes.
Interfaces cannot contain any variable declarations or assignments. Functions declared in an interface cannot contain curly braces. For example, the following interface won’t compile: interface BadInterface{ // Compiler error. Variable declarations not allowed in interfaces. var illegalVar; // Compiler error. Function bodies not allowed in interfaces.
For example, the following code first checks if the object name newBox implements the Movable interface before calling the moveUp() method on the object: if (Movable(newBox) != null) { newBox.moveUp(); } For more information about casting, see “Casting objects” on page 25. Instance and class members In object-oriented programming, members (properties or methods) of a class can be instance members or class members.
Class members are declared with the static modifier. For example, you could declare the species class member with the following code: class Person { static var species:String = "Homo sapiens"; ... } You can also declare methods of a class to be static, as shown in the following code: static function functionName() { // function body } Class (static) methods can access only class (static) properties, not instance properties.
The Singleton object can then be accessed using Singleton.getInstance(); This also means that the Singleton object is not created until it is actually needed—that is, until some other code asks for it by calling the getInstance method. This is typically called lazy creation and can help code efficiency in many circumstances. Using class members: a simple example One use of class (static) members is to maintain state information about a class and its instances.
trace("Creating subwidget # "+Widget.widgetCount); } } The ActionScript 2.0 compiler can resolve static member references within class definitions. In the previous example, if you don't specify the class name for the Widget.widgetCount property, but instead refer only to widgetCount, the ActionScript 2.0 compiler ascertains that the reference is actually to Widget.widgetCount and correctly exports that property. Similarly, if you referred to the property as SubWidget.
However, if you want to use a more concise syntax, use implicit getter/setter methods. Implicit getter/setter methods let you access class properties in a direct manner, while maintaining good OOP practice. To define these methods, use the get and set method attributes. You create methods that get or set the value of a property, and add the keyword get or set before the method name, as shown in the following example: class LoginClass2 { private var userName:String; function LoginClass2(name:String) { this.
Importing classes To reference a class in another script, you must prefix the class name with the class’s package path. The combination of a class’s name and its package path is the class’s fully qualified class name. If a class resides in a top-level classpath directory—not in a subdirectory in the classpath directory— then its fully qualified class name is its class name. To specify package paths, use dot (.) notation to separate package directory names.
Chapter 2: Creating Custom Classes with ActionScript 2.
CHAPTER 3 Working with External Data In Macromedia Flex, you can use ActionScript to load data from external sources into a SWF file. You can also send data from a 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. Macromedia Flash Player can send and load data over HTTP or HTTPS or load from a local text file.
• The functions and MovieClip methods that use the HTTP or HTTPS protocol to send information in URL-encoded format are getURL(), loadVariables(), loadVariablesNum(), loadMovie(), and loadMovieNum(). • The LoadVars methods that use the HTTP or HTTPS protocol to send and load information in URL-encoded format are load(), send(), and sendAndLoad(). • The methods that use HTTP or HTTPS protocol to send and load information as XML are XML.send(), XML.load(), and XML.sendAndLoad().
Using HTTP to connect to server-side scripts The getURL() function and the MovieClip.loadVariables(), MovieClip.loadMovie(), and methods can communicate with server-side scripts using HTTP or HTTPS protocols. When used as a method of the MovieClip object, getURL() sends all the variables of the specified movie clip; each function (or method) handles its response as follows: MovieClip.getURL() • The getURL() function returns any information to a browser window, not to Flash Player.
The LoadVars class was introduced in Flash Player 6 to provide a cleaner, more object-oriented interface for the common task of exchanging CGI data with a web server. Advantages of the LoadVars class include the following: • You don’t need to create container movie clips for holding data or clutter existing movie clips with variables specific to client/server communication. • The class interface is similar to the XML object, which provides some consistency in ActionScript.
In the following example, is the parent node; it has no attributes and contains the child node , which has the attributes symbol, qty, price, and value: For more information on XML, see www.w3.org/XML.
When you invoke the connect() method, Flash Player opens a TCP/IP connection to the server and keeps that connection open until one of the following events happens: • • • • The close() method of the XMLSocket class is called. No more references to the XMLSocket object exist. Flash Player exits. The connection is broken (for example, the modem disconnects).
To control a SWF file in Flash Player from web browser scripting languages such as JavaScript, VBScript, and Microsoft JScript, you can use Flash Player methods—functions that send messages from a host environment to the SWF file. For more information, see Developing Flex Applications.
An fscommand() function invokes the JavaScript function moviename_DoFSCommand in the HTML page that embeds the SWF file, where moviename is the name of Flash Player as assigned by the name attribute of the embed tag or the id attribute of the object tag. If Flash Player is assigned the name myMovie, the JavaScript function invoked is myMovie_DoFSCommand.
This part 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. For an overview of how to use ActionScript, see “Part I, “Welcome to ActionScript.” Chapter 4: About the ActionScript Language Reference. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77 Chapter 5: ActionScript Core Language Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
CHAPTER 4 About the ActionScript Language Reference The next three chapters of this manual describe the syntax and use of ActionScript elements in Macromedia Flex. The chapters list all ActionScript elements that are common to Macromedia Flash and to Flex—operators, keywords, statements, actions, properties, functions, classes, and methods.
Usage This section provides correct syntax for using the ActionScript element in your code. The required portion of the syntax is in code font, and the code that you provide is in italicized code font. Brackets ([]) indicate optional parameters. Parameters This section describes any parameters listed in the syntax. Returns This section identifies what, if any, values the element returns.
Method, property, and event handler listings The methods, properties, and event handlers of a class are listed alphabetically after the class entry.
CHAPTER 5 ActionScript Core Language Elements This chapter documents all the elements of the ActionScript language that are not related to a particular class or to a particular Macromedia product. That is, all products that support ActionScript have access to any language element in this chapter. For information on the classes that all Macromedia products support, see Chapter 6, “ActionScript Core Classes,” on page 232.
CHAPTER 5 ActionScript Core Language Elements –– (decrement) Availability Flash Player 4. Usage ––expression expression–– Parameters expression A number or a variable that evaluates to a number. Returns A number. Description Operator (arithmetic); a pre-decrement and post-decrement unary operator that subtracts 1 from the expression. The expression can be a variable, element in an array, or property of an object.
++ (increment) Availability Flash Player 4. Usage ++expression expression++ Parameters expression A number or a variable that evaluates to a number. Returns A number. Description Operator (arithmetic); a pre-increment and post-increment unary operator that adds 1 to expression. The expression can be a variable, element in an array, or property of an object. The pre-increment form of the operator (++expression) adds 1 to expression and returns the result.
this is execution 5 */ The following example uses ++ as a pre-increment operator: var a:Array = []; // var a:Array = new Array(); var i:Number = 0; while (i<10) { a.push(++i); } trace(a.toString());//traces: 1,2,3,4,5,6,7,8,9,10 This example also uses ++ as a pre-increment operator. var a:Array = []; for (var i = 1; i<=10; ++i) { a.push(i); } trace(a.
Parameters expression An expression or a variable that evaluates to a Boolean value. Returns A Boolean value. Description Operator (logical); inverts the Boolean value of a variable or expression. If expression is a variable with the absolute or converted value true, the value of !expression is false. If the expression x && y evaluates to false, the expression !(x && y) evaluates to true.
Description Operator (inequality); tests for the exact opposite of the equality (==) operator. If expression1 is equal to expression2, the result is false. As with the equality (==) operator, the definition of equal depends on the data types being compared, as illustrated in the following list: • Numbers, strings, and Boolean values are compared by value. • Objects, arrays, and functions are compared by reference. • A variable is compared by value or by reference, depending on its type.
true foo foo false The following example illustrates comparison by reference with two arrays: var a:Array = [ var b:Array = [ trace(a); // 1, trace(b); // 1, trace(a!=b); // a = b; trace(a); // 1, trace(b); // 1, trace(a!=b); // 1, 2, 3 ]; 1, 2, 3 ]; 2, 3 2, 3 true 2, 3 2, 3 false // trace statement output: 1,2,3 1,2,3 true 1,2,3 1,2,3 false See also ! (logical NOT), !== (strict inequality), && (logical AND), || (logical OR), == (equality), === (strict equality) !== (strict inequality) Availability Fla
Description Operator; tests for the exact opposite of the strict equality (===) operator. The strict inequality operator performs the same as the inequality operator except that data types are not converted. For more information, see “Automatic data typing” on page 24. If expression1 is equal to expression2, and their data types are equal, the result is false.
Parameters None. Returns A number. Description Operator (arithmetic); calculates the remainder of expression1 divided by expression2. If either of the expression parameters are non-numeric, the modulo (%) operator attempts to convert them to numbers. The expression can be a number or string that converts to a numeric value. For more information, see “Automatic data typing” on page 24 and “Operator precedence and associativity” on page 32.
Example The following example assigns the value 4 to the variable x: var x:Number = 14; var y:Number = 5; trace(x%=y); // output: 4 See also % (modulo) & (bitwise AND) Availability Flash Player 5. Usage expression1 & expression2 Parameters None. Returns A 32-bit integer. Description Operator (bitwise); converts expression1 and expression2 to 32-bit unsigned integers, and performs a Boolean AND operation on each bit of the integer parameters.
In the numbers 13 and 11 the result is 9 because only the first and last positions in both numbers have the number 1.
Example The following example uses the logical AND (&&) operator to perform a test to determine if a player has won the game. The turns variable and the score variable are updated when a player takes a turn or scores points during the game. The script writes “You Win the Game!” to the log file when the player’s score reaches 75 or higher in 3 turns or less.
See also & (bitwise AND), ^ (bitwise XOR), ^= (bitwise XOR assignment), | (bitwise OR), |= (bitwise OR assignment), ~ (bitwise NOT) () (parentheses) Availability Flash Player 4. Usage (expression1 [, expression2]) (expression1, expression2) function(parameter1,..., parameterN) Parameters expression1, expression2 function Numbers, strings, variables, or text. The function to be performed on the contents of the parentheses. parameter1...
Usage 2: The following example evaluates the function foo(), and then the function bar(), and returns the result of the expression a + b: var a:Number = 1; var b:Number = 2; function foo() { a += b; } function bar() { b *= 10; } trace((foo(), bar(), a+b)); // outputs 23 Usage 3: The following example shows the use of parentheses with functions: var today:Date = new Date(); trace(today.
Example Usage 1: The following statement reverses the sign of the expression 2 + 3: trace(-(2+3));// output: -5 Usage 2: The following statement subtracts the integer 2 from the integer 5: trace(5-2);// output: 3 The result, 3, is an integer. Usage 3: The following statement subtracts the floating-point number 1.5 from the floating-point number 3.25: trace(3.25-1.5);// output: 1.75 The result, 1.75, is a floating-point number. * (multiplication) Availability Flash Player 4.
*= (multiplication assignment) Availability Flash Player 4. Usage expression1 *= expression2 Parameters None. Returns The value of expression1 * expression2. If an expression cannot be converted to a numeric value, it returns NaN (not a number). Description Operator (arithmetic compound assignment); assigns expression1 the value of expression1 * expression2.
Parameters None. Returns The value of expression1, expression2, and so on. Description Operator; evaluates expression1, then expression2, and so on. This operator is primarily used with the for loop statement and is often used with the parentheses () operator. For more information, see “Operator precedence and associativity” on page 32.
var z:Number = 0; v = (v + 4, z++, v + 6); trace(v); // output: 6 trace(z); // output: 1 See also () (parentheses) . (dot) Availability Flash Player 4. Usage object.property_or_method instancename.childinstance Parameters An instance of a class. The object can be an instance of any of the built-in ActionScript classes or a custom class. This parameter is always to the left of the dot (.) operator. object The name of a property or method associated with an object.
this.container_mc.createTextField("date_txt", this.getNextHighestDepth(), 0, 0, 100, 22); this.container_mc.date_txt.autoSize = true; this.container_mc.date_txt.text = new Date(); The dot (.) operator is used when targeting instances within the SWF file and when you need to set properties and values for those instances. : (type) Availability Flash Player 6. Usage [modifiers] var variableName:type function functionName():type { ... } function functionName(parameter1:type, ...
Usage 2: The following example shows how to specify a function’s parameter type by defining a function named randomInt() that takes a parameter named integer of type Number: function randomInt(integer:Number):Number { return Math.round(Math.
The following example shows a conditional statement written in shorthand: var timecode:String = (new Date().getHours()<11) ? "AM" : "PM"; trace(timecode); The same conditional statement could also be written in longhand, as shown in the following example: if (new Date().getHours()<11) { var timecode:String = "AM"; } else { var timecode:String = "PM"; } trace(timecode); / (division) Availability Flash Player 4.
// (comment delimiter) Availability Flash 1. Usage // comment Parameters comment Any characters. Returns Nothing. Description Comment; indicates the beginning of a script comment. Any characters that appear between the comment delimiter (//) and the end-of-line character are interpreted as a comment and ignored by the ActionScript interpreter.
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. Use the // (comment delimiter) to identify single-line comments. Use the /* comment delimiter to identify comments on multiple successive lines. Leaving off the closing tag (*/) when using this form of comment delimiter returns an error message.
Description Operator (arithmetic compound assignment); assigns expression1 the value of expression1 / expression2. For example, the following two statements are equivalent: x /= y x = x / y For more information, see “Operator precedence and associativity” on page 32.
Description Operator; initializes a new array or multidimensional array with the specified elements (a0, 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.
The following example creates an array called employee_array and uses the trace() statement to send the elements to the log file.
Positive integers are converted to an unsigned hex value with a maximum value of 4294967295 or 0xFFFFFFFF; values larger than the maximum have their most significant digits discarded when they are converted so the value is still 32-bit.
Example The following example shows a bitwise XOR assignment (^=) operation: // 15 decimal = 1111 binary var x:Number = 15; // 9 decimal = 1001 binary var y:Number = 9; trace(x ^= y); // returns 6 decimal (0110 binary) See also & (bitwise AND), &= (bitwise AND assignment), ^ (bitwise XOR), | (bitwise OR), |= (bitwise OR assignment), ~ (bitwise NOT) {} (object initializer) Availability Flash Player 5. Usage object = {name1: value1, name2: value2,...nameN: valueN} {expression1; [...
Example The first line of the following code creates an empty object using the object initializer ({}) operator; the second line creates a new object using a constructor function: var object:Object = {}; var object:Object = new Object(); The following example creates an object account and initializes the properties name, address, city, state, zip, and balance with accompanying values: var account:Object = {name:"Macromedia, Inc.
Returns A 32-bit integer. Description Operator (bitwise); converts expression1 and expression2 to 32-bit unsigned integers, and returns a 1 in each bit position where the corresponding bits of either expression1 or expression2 are 1. Floating-point numbers are converted to integers by discarding any digits after the decimal point. The result is a new 32-bit integer.
Returns A Boolean value. Description Operator (logical); evaluates expression1 (the expression on the left side of the operator) and returns true if the expression evaluates to true. If expression1 evaluates to false, expression2 (the expression on the right side of the operator) is evaluated. If expression2 evaluates to false, the final result is false; otherwise, it is true. If you use a function call as expression2, the function will not be executed by that call if evaluates to true.
See also ! (logical NOT), != (inequality), !== (strict inequality), && (logical AND), == (equality), === (strict equality) |= (bitwise OR assignment) Availability Flash Player 5. Usage expression1 |= expression2 Parameters expression1,expression2 A number or variable. Returns An integer. Description Operator (bitwise compound assignment); assigns expression1 the value of expression1 | For example, the following two statements are equivalent: expression2.
Parameters expression A number. Returns A 32-bit integer. Description Operator (bitwise); also known as the one’s complement operator or the bitwise complement operator. Converts the expression to a 32-bit signed integer, and then applies a bitwise one’s complement. That is, every bit that is a 0 is set to 1 in the result, and every bit that is a 1 is set to 0 in the result. The result is a signed 32-bit integer.
/* To clear the read-only flag in the flags variable, first construct a mask by using bitwise NOT on ReadOnlyFlag. In the mask, every bit is a 1 except for the read-only flag. Then, use bitwise AND with the mask to clear the readonly flag.
This statement adds the floating-point numbers 2.5 and 3.25 and writes the resulting floatingpoint number, 5.75, to the log file: trace(2.5+3.25); // output: 5.75 The following example shows how numeric sums to the right of a string expression are not calculated: var a:String trace(a); // var b:String trace(b); // = 3 + 10 + "asdf"; 13asdf = "asdf" + 3 + 10; asdf310 += (addition assignment) Availability Flash Player 4.
See also + (addition) < (less than) Availability Flash Player 5. Usage expression1 < expression2 Parameters expression1,expression2 A number or string. Returns A Boolean value. Description Operator (comparison); compares two expressions and determines whether expression1 is less than expression2; if so, the operator returns true. If expression1 is greater than or equal to expression2, the operator returns false.
Returns A 32-bit integer. Description Operator (bitwise); converts expression1 and expression2 to 32-bit integers, and shifts all the bits in expression1 to the left by the number of places specified by the integer resulting from the conversion of expression2. The bit positions that are emptied as a result of this operation are filled in with 0 and bits shifted off the left end are discarded. Shifting a value left by one position is the equivalent of multiplying it by 2.
<<= (bitwise left shift and assignment) Availability Flash Player 5. Usage expression1 <<= expression2 Parameters expression1 A number or expression to be shifted left. expression2 A number or expression that converts to an integer from 0 to 31. Returns A 32-bit integer. Description Operator (bitwise compound assignment); this operator performs a bitwise left shift (<<=) operation and stores the contents as a result in expression1.
Parameters expression1,expression2 A number or string. Returns A Boolean value. Description Operator (comparison); compares two expressions and determines whether expression1 is less than or equal to expression2; if it is, the operator returns true. If expression1 is greater than expression2, the operator returns false. String expressions are evaluated using alphabetical order; all capital letters come before lowercase letters.
Description Operator; assigns the value of expression2 (the parameter on the right) to the variable, array element, or property in expression1. Assignment can be either by value or by reference. Assignment by value copies the actual value of expression2 and stores it in expression1. Assignment by value is used when a variable is assigned a number or string literal. Assignment by reference stores a reference to expression2 in expression1. Assignment by reference is commonly used with the new operator.
-= (subtraction assignment) Availability Flash Player 4. Usage expression1 -= expression2 Parameters expression1,expression2 A number or expression that evaluates to a number. Returns A number. Description Operator (arithmetic compound assignment); assigns expression1 the value of expression1 expression2. For example, the following two statements are equivalent: x -= y; x = x - y; String expressions must be converted to numbers; otherwise, NaN (not a number) is returned.
Parameters expression1,expression2 A number, string, Boolean value, variable, object, array, or function. Returns A Boolean value. Description Operator (equality); tests two expressions for equality. The result is true if the expressions are equal. The definition of equal depends on the data type of the parameter: • Numbers and Boolean values are compared by value and are considered equal if they have the same value.
The following examples show comparison by reference. The first example compares two arrays with identical length and elements. The equality operator will return false for these two arrays. Although the arrays appear equal, comparison by reference requires that they both refer to the same array. The second example creates the thirdArray variable, which points to the same array as the variable firstArray.
Example The comments in the following code show the returned value of operations that use the equality and strict equality operators: // Both return true because no conversion is done var string1:String = "5"; var string2:String = "5"; trace(string1 == string2); // true trace(string1 === string2); // true // Automatic data typing in this example converts 5 to “5” var string1:String = "5"; var num:Number = 5; trace(string1 == num); // true trace(string1 === num); // false // Automatic data typing in this ex
> (greater than) Availability Flash Player 4. Usage expression1 >expression2 Parameters expression1,expression2 A number or string. Returns A Boolean value. Description Operator (comparison); compares two expressions and determines whether expression1 is greater than expression2; if it is, the operator returns true. If expression1 is less than or equal to expression2, the operator returns false.
For more information, see “Operator precedence and associativity” on page 32. Example In the following example, the greater than or equal to (>=) operator is used to determine whether the current hour is greater than or equal to 12: if (new Date().getHours()>=12) { trace("good afternoon"); } else { trace("good morning"); } >> (bitwise right shift) Availability Flash Player 5. Usage expression1 >> expression2 Parameters expression1 A number or expression to be shifted right.
Example The following example converts 65535 to a 32-bit integer and shifts it 8 bits to the right: var x:Number = 65535 >> 8; trace(x); // outputs 255 The following example shows the result of the previous example: var x:Number = 255 This is because 65535 decimal equals 1111111111111111 binary (sixteen 1’s), 1111111111111111 binary shifted right by 8 bits is 11111111 binary, and 11111111 binary is 255 decimal. The most significant bit is 0 because the integers are 32-bit, so the fill bit is 0.
The following two expressions are equivalent: A >>= B A = (A >> B) For more information, see “Operator precedence and associativity” on page 32. Example The following commented code uses the bitwise right shift and assignment (>>=) operator.
Floating-point numbers are converted to integers by discarding any digits after the decimal point. Positive integers are converted to an unsigned hex value with a maximum value of 4294967295 or 0xFFFFFFFF; values larger than the maximum have their most significant digits discarded when they are converted so the value is still 32-bit.
CHAPTER 5 ActionScript Core Language Elements Boolean() Availability Flash Player 5; behavior changed in Flash Player 7. Usage Boolean(expression) : Boolean Parameters expression An expression to convert to a Boolean value. Returns A Boolean value. Description Function; converts the parameter expression to a Boolean value and returns a value as described in the following list: • If expression is a Boolean value, the return value is expression.
// Variables representing Boolean values are compared by value var a:Boolean = Boolean("a"); // a is true var b:Boolean = Boolean(1); // b is true trace(a==b); // true // Variables representing Boolean objects are compared by reference var a:Boolean = new Boolean("a"); // a is true var b:Boolean = new Boolean(1); // b is true trace(a==b); // false See also Boolean class 130 Chapter 5: ActionScript Core Language Elements
CHAPTER 5 ActionScript Core Language Elements Array() Availability Flash Player 6. Usage Array() : Array Array(numElements:Number) : Array Array( [element0:Object [, element1 , element2,...elementN ] ]) : Array Parameters element One or more elements to place in the array. Returns An array. Description Conversion function; creates a new, empty array or converts specified elements to an array.
break CHAPTER 5 ActionScript Core Language Elements Availability Flash Player 4. Usage break Parameters None. Returns Nothing. Description Statement; appears within a loop (for, for..in, do while or while) or within a block of statements associated with a particular case within a switch statement. When used in a loop, the break statement instructs Flash to skip the rest of the loop body, stop the looping action, and execute the statement following the loop statement.
See also for, for..in, do while, while, switch, case, continue, throw, try..catch..
CHAPTER 5 ActionScript Core Language Elements case Availability Flash Player 4. Usage case expression: statement(s) Parameters expression statement(s) Any expression. Any statement or sequence of statements. Returns Nothing. Description Statement; defines a condition for the switch statement.
See also break, default, === (strict equality), switch case 135
CHAPTER 5 ActionScript Core Language Elements class Availability Flash Player 6. Usage [dynamic] class className [ extends superClass ] [ implements interfaceName [, interfaceName... ] ] { // class definition here } Parameters className superClass The fully qualified name of the class. The name of the class that className extends (inherits from). This parameter is optional. The name of the interface whose methods className must implement. This parameter is optional.
class C implements Interface_i, Interface_j // OK class C extends Class_d implements Interface_i, Interface_j class C extends Class_d, Class_e // not OK // OK For more information, see “Creating and using classes” in Using ActionScript in Flash.For more information, see “Creating and using classes” on page 51. Example The following example creates a class called Plant. The Plant constructor takes two parameters. // Filename Plant.
In your script, use the new operator to create a ImageLoader object. var jakob_mc:MovieClip = this.createEmptyMovieClip("jakob_mc", this.getNextHighestDepth()); var jakob:ImageLoader = new ImageLoader("http://www.macromedia.com/devnet/mx/ blueprint/articles/nielsen/spotlight_jnielsen.jpg", jakob_mc, {_x:10, _y:10, _alpha:70, _rotation:-5}); See also dynamic, extends, implements, import, interface, new, Object.
clearInterval() CHAPTER 5 ActionScript Core Language Elements Availability Flash Player 6. Usage clearInterval( intervalID:Number ) : Void Parameters intervalID A numeric (integer) identifier returned from a call to setInterval(). Returns Nothing. Description Function; cancels an interval created by a call to setInterval(). Example The following example first sets and then clears an interval call: function callback() { trace("interval called: "+getTimer()+" ms.
continue CHAPTER 5 ActionScript Core Language Elements Availability Flash Player 4. Usage continue Parameters None. Returns Nothing. Description Statement; jumps past all remaining statements in the innermost loop and starts the next iteration of the loop as if control had passed through to the end of the loop normally. It has no effect outside a loop.
if (i%3 == 0) { continue; } trace(i); } In the following for..in loop, continue causes the Flash interpreter to skip the rest of the loop body and jump back to the top of the loop, where the next value in the enumeration is processed: for (i in _root) { if (i == "$version") { continue; } trace(i); } See also do while, for, for..
CHAPTER 5 ActionScript Core Language Elements default Availability Flash Player 6. Usage default: statements Parameters statements Any statements. Returns Nothing. Description Statement; defines the default case for a switch statement. The statements execute if the expression parameter of the switch statement doesn’t equal (using the strict equality [===] operation) any of the expression parameters that follow the case keywords for a given switch statement.
CHAPTER 5 ActionScript Core Language Elements delete Availability Flash Player 5. Usage delete reference Parameters reference The name of the variable or object to eliminate. Returns A Boolean value. Description Operator; destroys the object reference specified by the reference parameter, and returns true if the reference is successfully deleted; false otherwise. This operator is useful for freeing memory used by scripts. You can use the delete operator to remove references to objects.
Usage 3: The following example deletes an object property: var my_array:Array = new Array(); my_array[0] = "abc"; // my_array.length == 1 my_array[1] = "def"; // my_array.length == 2 my_array[2] = "ghi"; // my_array.length == 3 // my_array[2] is deleted, but Array.length is not changed delete my_array[2]; trace(my_array.length); // output: 3 trace(my_array); // output: abc,def,undefined Usage 4: The following example shows the behavior of delete on object references: var ref1:Object = new Object(); ref1.
CHAPTER 5 ActionScript Core Language Elements do while Availability Flash Player 4. Usage do { statement(s) } while (condition) Parameters condition The condition to evaluate. statement(s) The statement(s) to execute as long as the condition parameter evaluates to true. Returns Nothing. Description Statement; similar to a while loop, except that the statements are executed once before the initial evaluation of the condition.
See also break, continue, while 146 Chapter 5: ActionScript Core Language Elements
dynamic CHAPTER 5 ActionScript Core Language Elements Availability Flash Player 6. Usage dynamic class className [ extends superClass ] [ implements interfaceName [, interfaceName... ] ] { // class definition here } Description Keyword; specifies that objects based on the specified class can add and access dynamic properties at runtime.
If you add an undeclared function, dance, an error is generated, as shown in the following example: trace(""); craig.dance = true; for (i in craig) { trace("craig."+i +" = "+ craig[i]); } /* output: **Error** Scene=Scene 1, layer=Layer 1, frame=1:Line 14: There is no property with the name 'dance'. craig.
CHAPTER 5 ActionScript Core Language Elements else Availability Flash Player 4. Usage if (condition){ statement(s); } else { statement(s); } Parameters condition An expression that evaluates to true or false. statement(s) An alternative series of statements to run if the condition specified in the if statement is false. Returns Nothing. Description Statement; specifies the statements to run if the condition in the if statement returns false.
CHAPTER 5 ActionScript Core Language Elements else if Availability Flash Player 4. Usage if (condition){ statement(s); } else if (condition){ statement(s); } Parameters condition An expression that evaluates to true or false. statement(s) An alternative series of statements to run if the condition specified in the if statement is false. Returns Nothing. Description Statement; evaluates a condition and specifies the statements to run if the condition in the initial if statement returns false.
CHAPTER 5 ActionScript Core Language Elements escape() Availability Flash Player 5. Usage escape(expression:String) : String Parameters expression The expression to convert into a string and encode in a URL-encoded format. Returns URL-encoded string. Description Function; converts the parameter to a string and encodes it in a URL-encoded format, where all nonalphanumeric characters are replaced with % hexadecimal sequences.
CHAPTER 5 ActionScript Core Language Elements eval() Availability Flash Player 5. Usage eval(expression:String) : Object Parameters expression A string containing the name of a variable, property, object, or movie clip to retrieve. Returns A value, reference to an object or movie clip, or undefined. Description Function; accesses variables, properties, objects, or movie clips by name. If expression is a variable or a property, the value of the variable or property is returned.
CHAPTER 5 ActionScript Core Language Elements extends Availability Flash Player 6. Usage class className extends otherClassName {} interface interfaceName extends otherInterfaceName {} Parameters className The name of the class you are defining. otherClassName interfaceName The name of the class on which className is based. The name of the interface you are defining. otherInterfaceName The name of the interface on which interfaceName is based.
The following example shows a second AS file, called Car.as, in the same directory. This class extends the Vehicle class, modifying it in three ways. First, the Car class adds a variable fullSizeSpare to track whether the car object has a full-size spare tire. Second, it adds a new method specific to cars, activateCarAlarm(), that activates the car’s anti-theft alarm. Third, it overrides the stop() function to add the fact that the Car class uses an anti-lock braking system to stop.
The following example instantiates a Truck object, calls a method overridden by the Truck class (reverse()), then calls a method defined in the Vehicle class (stop()): var myTruck:Truck = new Truck(2, "White", 18); myTruck.reverse(); // output: [Truck] make beeping sound [Vehicle] reverse myTruck.
false CHAPTER 5 ActionScript Core Language Elements Availability Flash Player 5. Usage false Description Constant; a unique Boolean value that represents the opposite of true. When automatic data typing converts false to a number, it becomes 0; when it converts false to a string, it becomes "false". For more information, see “Automatic data typing” on page 24.
CHAPTER 5 ActionScript Core Language Elements for Availability Flash Player 5. Usage for(init; condition; next) { statement(s); } Parameters An expression to evaluate before beginning the looping sequence; usually an assignment expression. A var statement is also permitted for this parameter. init condition An expression that evaluates to true or false. The condition is evaluated before each loop iteration; the loop exits when the condition evaluates to false.
The following example uses for to perform the same action repeatedly. In the code, the for loop adds the numbers from 1 to 100. var sum:Number = 0; for (var i:Number = 1; i<=100; i++) { sum += i; } trace(sum); // output: 5050 The following example shows that curly braces ({}) are not necessary if only one statement will execute: var sum:Number = 0; for (var i:Number = 1; i<=100; i++) sum += i; trace(sum); // output: 5050 See also ++ (increment), –– (decrement), for..
CHAPTER 5 ActionScript Core Language Elements for..in Availability Flash Player 5. Usage for(variableIterant in object){ statement(s); } Parameters The name of a variable to act as the iterant, referencing each property of an object or element in an array. variableIterant object The name of an object to be iterated. statement(s) An instruction to execute for each iteration. Returns Nothing.
The following example shows using for..in to iterate over the elements of an array: var myArray:Array = new Array("one", "two", "three"); for (var index in myArray) trace("myArray["+index+"] = " + myArray[index]); // output: myArray[2] = three myArray[1] = two myArray[0] = one The following example uses the typeof operator with for..
CHAPTER 5 ActionScript Core Language Elements fscommand() Availability Flash Player 3. Usage fscommand("command", "parameters") Parameters A string passed to the host application for any use, or a command passed to Flash Player. command parameters A string passed to the host application for any use, or a value passed to Flash Player. Returns Nothing. Description Function; lets the SWF file communicate with either Flash Player or the program hosting Flash Player, such as a web browser.
The exec command can contain only the characters A–Z, a–z, 0–9, period (.), and underscore (_). The exec command runs in the subdirectory fscommand only. In other words, if you use the fscommand exec command to call an application, the application must reside in a subdirectory named fscommand. Usage 2: To use the fscommand() function to send a message to a scripting language such as JavaScript in a web browser, you can pass any two parameters in the command and parameters parameters.
CHAPTER 5 ActionScript Core Language Elements function Availability Flash Player 5. Usage function functionname ([parameter0, parameter1,...parameterN]){ statement(s) } function ([parameter0, parameter1,...parameterN]){ statement(s) } Parameters functionname parameter The name of the new function. This parameter is optional. An identifier that represents a parameter to pass to the function. This parameter is optional.
Example The following example defines the function sqr, which accepts one parameter and returns the of the parameter: Math.pow(x, 2) function sqr(x:Number) { return Math.pow(x, 2); } var y:Number = sqr(3); trace(y); // output: 9 If the function is defined and used in the same script, the function definition may appear after using the function: var y:Number = sqr(3); trace(y); // output: 9 function sqr(x:Number) { return Math.
CHAPTER 5 ActionScript Core Language Elements get Availability Flash Player 6. Usage function get property() { // your statements here } Parameters The word you use to refer to the property that get accesses; this value must be the same as the value used in the corresponding set command. property Returns Nothing. Description Keyword; permits implicit getting of properties associated with objects based on classes you have defined in external class files.
San Fran San Francisco */ When you trace giants.name, you use the get method to return the value of the property. See also Object.
getTimer() CHAPTER 5 ActionScript Core Language Elements Availability Flash Player 4. Usage getTimer() : Number Parameters None. Returns The number of milliseconds that have elapsed since the SWF file started playing. Description Function; returns the number of milliseconds that have elapsed since the SWF file started playing. Example In the following example, the getTimer() and setInterval() functions are used to create a simple timer: this.createTextField("timer_txt", this.
CHAPTER 5 ActionScript Core Language Elements getURL() Availability Flash 2. The GET and POST options are available only in Flash Player 4 and later versions. Usage getURL(url:String [, window:String [, "variables":String]]) : Void Parameters url The URL from which to obtain the document. window An optional parameter specifying the window or HTML frame into which the document should load.
You can also use GET or POST for sending variables. The following example uses GET to append variables to a URL: var firstName:String = "Gus"; var lastName:String = "Richardson"; var age:Number = 92; myBtn_btn.onRelease = function() { getURL("http://www.macromedia.com", "_blank", "GET"); }; The following ActionScript uses POST to send variables in the HTTP header.
getVersion() CHAPTER 5 ActionScript Core Language Elements Availability Flash Player 5. Usage getVersion() : String Parameters None. Returns A string containing Flash Player version and platform information. Description Function; returns a string containing Flash Player version and platform information.
_global object CHAPTER 5 ActionScript Core Language Elements Availability Flash Player 6. Usage _global.identifier Parameters None. Returns A reference to the global object that holds the core ActionScript classes, such as String, Object, Math, and Array. Description Identifier; creates global variables, objects, or classes. For example, you could create a library that is exposed as a global ActionScript object, similar to the Math or Date object.
CHAPTER 5 ActionScript Core Language Elements if Availability Flash Player 4. Usage if(condition) { statement(s); } Parameters condition An expression that evaluates to true or false. statement(s) The instructions to execute if or when the condition evaluates to true. Returns Nothing. Description Statement; evaluates a condition to determine the next action in a SWF file. If the condition is true, Flash runs the statements that follow the condition inside curly braces ({}).
implements CHAPTER 5 ActionScript Core Language Elements Availability Flash Player 6. Usage myClass implements interface01 [, interface02, ...] Description Keyword; specifies that a class must define all the methods declared in the interface (or interfaces) being implemented. For more information, see “Interfaces as data types” on page 59. Example See interface.
CHAPTER 5 ActionScript Core Language Elements import Availability Flash Player 6. Usage import className import packageName.* Parameters className packageName The fully qualified name of a class you have defined in an external class file. A directory in which you have stored related class files. Description Keyword; lets you access classes without specifying their fully qualified names. For example, if you want to use a custom class macr.util.users.
#include CHAPTER 5 ActionScript Core Language Elements Availability Flash Player 4. Usage #include "[path] filename.as" Note: Do not place a semicolon (;) at the end of the line that contains the #include statement. Parameters The filename and optional path for the script to add to the current script; .as is the recommended filename extension. [path] filename.as Returns Nothing.
// AS file is in a directory at the same level as the directory // that contains the script file // The directory is named "ALL_includes" #include "../ALL_includes/init_script.as" // AS file is specified by an absolute path in Windows // Note use of forward slashes, not backslashes #include "C:/Flash_scripts/init_script.as" // AS file is specified by an absolute path on Macintosh #include "Mac HD:Flash_scripts:init_script.
Infinity CHAPTER 5 ActionScript Core Language Elements 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 CHAPTER 5 ActionScript Core Language Elements 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.
instanceof CHAPTER 5 ActionScript Core Language Elements Availability Flash Player 6. Usage object instanceof class Parameters An ActionScript object. object class A reference to an ActionScript constructor function, such as String or Date. Returns If object is an instance of class, instanceof returns true; false otherwise. Also, _global returns false. instanceof Object Description Operator; determines whether an object belongs to a specified class. Tests whether object is an instance of class.
interface CHAPTER 5 ActionScript Core Language Elements Availability Flash Player 6. Usage interface InterfaceName [extends InterfaceName ] {} Description Keyword; defines an interface. An interface is similar to a class, with the following important differences: • Interfaces contain only declarations of methods, not their implementation. That is, every class that implements an interface must provide an implementation for each method declared in the interface.
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");} } // script file mvar = new D(); trace(mvar.k()); trace(mvar.n(7)); trace(mvar.
CHAPTER 5 ActionScript Core Language Elements isFinite() Availability Flash Player 5. Usage isFinite(expression:Object) : Boolean Parameters expression A Boolean value, variable, or other expression to be evaluated. Returns A Boolean value. Description Function; evaluates expression and returns true if it is a finite number or false if it is infinity or negative infinity. The presence of infinity or negative infinity indicates a mathematical error condition such as division by 0.
CHAPTER 5 ActionScript Core Language Elements isNaN() Availability Flash Player 5. Usage isNaN(expression:Object) : Boolean Parameters expression A Boolean, variable, or other expression to be evaluated. Returns A Boolean value. Description Function; evaluates the parameter and returns true if the value is NaN (not a number). This function is useful for checking whether a mathematical expression evaluates successfully to a number.
CHAPTER 5 ActionScript Core Language Elements NaN Availability Flash Player 5. Usage NaN Description Variable; a predefined variable with the IEEE-754 value for NaN (not a number). To determine if a number is NaN, use isNaN(). See also isNaN(), Number.
new CHAPTER 5 ActionScript Core Language Elements Availability Flash Player 5. Usage new constructor() Parameters constructor A function followed by any optional parameters in parentheses. The function is usually the name of the object type (for example, Array, Number, or Object) to be constructed. Returns Nothing. Description Operator; creates a new, initially anonymous, object and calls the function identified by the constructor parameter.
newline CHAPTER 5 ActionScript Core Language Elements Availability Flash Player 4. Usage newline Parameters None. Returns Nothing. Description Constant; inserts a carriage return character (\n) that generates a blank line in text output generated by your code. Use newline to make space for information that is retrieved by a function or statement in your code. Example The following example shows how newline writes output from the trace() statement on multiple lines.
null CHAPTER 5 ActionScript Core Language Elements 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 null to represent values that are missing or that do not have a defined data type. Example In a numeric context, null evaluates to 0. Equality tests can be performed with null.
CHAPTER 5 ActionScript Core Language Elements Number() Availability Flash Player 4; behavior changed in Flash Player 7. Usage Number(expression) : Number Parameters expression An expression to convert to a number. Returns A number or NaN (not a number). Description Function; converts the parameter expression to a number and returns a value as described in the following list: • If expression is a number, the return value is expression.
CHAPTER 5 ActionScript Core Language Elements Object() Availability Flash Player 5. Usage Object( [ value ] ) : Object Parameters value A number, string, or Boolean value. Returns An object. Description Conversion function; creates a new empty object or converts the specified number, string, or Boolean value to an object. This command is equivalent to creating an object using the Object constructor (see “Constructor for the Object class” on page 376).
CHAPTER 5 ActionScript Core Language Elements on() Availability Flash 2. Not all events are supported in Flash 2. Usage on(mouseEvent) { // your statements here } Parameters statement(s) The instructions to execute when the mouseEvent occurs. A mouseEvent is a trigger called an event. When the event occurs, the statements following it within curly braces ({ }) execute.
Example In the following script, the startDrag() function executes when the mouse is pressed, and the conditional script is executed when the mouse is released and the object is dropped: on (press) { startDrag(this); } on (release) { trace("X:"+this._x); trace("Y:"+this.
parseFloat() CHAPTER 5 ActionScript Core Language Elements Availability Flash Player 5. Usage parseFloat(string:String) : Number Parameters string The string to read and convert to a floating-point number. Returns A number or NaN (not a number). 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.
CHAPTER 5 ActionScript Core Language Elements parseInt() Availability Flash Player 5. Usage parseInt(expression:String [, radix:Number]) : Number Parameters expression A string to convert to an integer. radix An integer representing the radix (base) of the number to parse. Legal values are from 2 to 36. This parameter is optional. Returns A number or NaN (not a number). Description Function; converts a string to an integer.
The following examples show octal number parsing and return 511, which is the decimal representation of the octal 777: parseInt("0777") parseInt("777", 8) See also NaN, parseFloat() 194 Chapter 5: ActionScript Core Language Elements
CHAPTER 5 ActionScript Core Language Elements private Availability Flash Player 6. Usage class someClassName{ private var name; private function name() { // your statements here } } Parameters name The name of the variable or function that you want to specify as private. Description Keyword; specifies that a variable or function is available only to the class that declares or defines it or to subclasses of that class. By default, a variable or function is available to any caller.
Because loginPassword is a private variable, you cannot access it from outside the Login.as class file. Attempts to access the private variable generate an error message.
CHAPTER 5 ActionScript Core Language Elements public Flash Player 6. Usage class someClassName{ public var name; public function name() { // your statements here } } Parameters name The name of the variable or function that you want to specify as public. Description Keyword; specifies that a variable or function is available to any caller. Because variables and functions are public by default, this keyword is used primarily for stylistic reasons.
return CHAPTER 5 ActionScript Core Language Elements Availability Flash Player 5. Usage return[expression] Parameters expression A string, number, Boolean, array, or object to evaluate and return as a value of the function. This parameter is optional. Returns The evaluated expression parameter, if provided. Description Statement; specifies the value returned by a function. The return statement evaluates expression and returns the result as a value of the function in which it executes.
CHAPTER 5 ActionScript Core Language Elements set Availability Flash Player 6. Usage function set property(varName) { // your statements here } Parameters Word that refers to the property that set will access; this value must be the same as the value used in the corresponding get command. property varName The local variable that sets the value you’re assigning. Returns Nothing.
In a FLA or AS file that is in the same directory as Login.as, enter the following ActionScript: var gus:Login = new Login("Gus", "Smith"); trace(gus.username); // output: Gus gus.username = "Rupert"; trace(gus.username); // output: Rupert In the following example, the get function executes when the value is traced. The set function triggers only when you pass it a value, as shown in the line: gus.username = “Rupert”; See also get, Object.
CHAPTER 5 ActionScript Core Language Elements set variable Availability Flash Player 4. Usage set("variableString", expression) Parameters variableString expression A string that names a variable to hold the value of the expression parameter. A value assigned to the variable. Returns Nothing. Description Statement; assigns a value to a variable. A variable is a container that holds data. The container is always the same, but the contents can change.
The following code loops three times and creates three new variables, called caption0, caption1, and caption2: for (var i = 0; i<3; i++) { set("caption"+i, "this is caption "+i); } trace(caption0); trace(caption1); trace(caption2); See also var 202 Chapter 5: ActionScript Core Language Elements
CHAPTER 5 ActionScript Core Language Elements setInterval() Availability Flash Player 6. Usage setInterval(functionName:Function, interval:Number [, param1:Object, param2, ..., paramN]) : Number setInterval(objectName:Object, methodName:Function, interval:Number [, param1:Object, param2, ..., paramN]) : Number Parameters functionName interval A function name or a reference to an anonymous function. The time in milliseconds between calls to the functionName or methodName parameter. param1, param2, ...
setInterval( callback1, 1000 ); setInterval( callback2, 1000, "interval called" ); 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(); obj2.
jpeg_mcl.addListener(listenerObject); jpeg_mcl.loadClip("http://www.macromedia.com/software/central/images/ klynch_breezo.jpg", this.createEmptyMovieClip("jpeg_mc", this.
CHAPTER 5 ActionScript Core Language Elements static Availability Flash Player 6. Usage class someClassName{ static var name; static function name() { // your statements here } } Parameters name The name of the variable or function that you want to specify as static. Description Keyword; specifies that a variable or function is created only once per class rather than being created in every object based on that class. For more information, see “Instance and class members” on page 60.
" " (string delimiter) CHAPTER 5 ActionScript Core Language Elements Availability Flash Player 4. Usage "text" Parameters text A sequence of zero or more characters. Returns Nothing. Description String delimiter; when used before and after characters, quotation marks ("") indicate that the characters have a literal value and are considered a string, not a variable, numerical value, or other ActionScript element.
CHAPTER 5 ActionScript Core Language Elements String() Availability Flash Player 4; behavior changed in Flash Player 7. Usage String(expression) Parameters expression An expression to convert to a string. Returns A string. Description Function; returns a string representation of the specified parameter, as described in the following list: • If expression is a number, the return string is a text representation of the number. • If expression is a string, the return string is expression.
CHAPTER 5 ActionScript Core Language Elements super Availability Flash Player 6. Usage super.method([arg1, ..., argN]) super([arg1, ..., argN]) Parameters method The method to invoke in the superclass. Optional parameters that are passed to the superclass version of the method (syntax 1) or to the constructor function of the superclass (syntax 2). arg1 Returns Both forms invoke a function. The function can return any value.
Then create a new class called Socks that extends the Clothes class, as shown in the following example: class Socks extends Clothes { private var color:String; function Socks(param_color:String) { this.color = param_color; trace("[Socks] I am the constructor"); } function getColor():String { trace("[Socks] I am getColor"); return super.getColor(); } function setColor(param_color:String):Void { this.
CHAPTER 5 ActionScript Core Language Elements switch Availability Flash Player 4. Usage switch (expression){ caseClause: [defaultClause:] } Parameters expression Any expression. caseClause A case keyword followed by an expression, a colon, and a group of statements to execute if the expression matches the switch expression parameter using strict equality (===).
case "i" : trace("you pressed I or i"); break; default : trace("you pressed some other key"); } }; Key.
this CHAPTER 5 ActionScript Core Language Elements Availability Flash Player 5. Usage this Description Identifier; refers to the object in the currently executing scope. If you are in a method and you want a reference to the object instance, use the this identifier. You can also use the this identifier to pass a class instance as an argument of a method to itself or another class.
Inside the FLA or AS file, add the following ActionScript: var obj:Simple = new Simple(); obj.num = 0; obj.func = function() { return true; }; obj.callfunc(); // output: true You get a syntax error when you use the incorrect version of Simple.as. Example In the following example, the keyword this references the Circle object: function Circle(radius:Number):Void { this.radius = radius; this.area = Math.PI*Math.pow(radius, 2); } var myCircle = new Circle(4); trace(myCircle.
CHAPTER 5 ActionScript Core Language Elements throw Availability Flash Player 7. Usage throw expression Description Statement; generates, or throws, an error that can be handled, or caught, by a catch{} code block. If an exception is not caught by a catch or finally block, the string representation of the thrown value is sent to the log file. Typically, you throw instances of the Error class or its subclasses (see the Example section). Parameters expression An ActionScript expression or object.
In a FLA or AS file, enter the following ActionScript: import InvalidEmailAddress; function checkEmail(email:String) { if (email.indexOf("@") == -1) { throw new InvalidEmailAddress(); } } try { checkEmail("Joe Smith"); } catch (e) { this.createTextField("error_txt", this.getNextHighestDepth(), 0, 0, 100, 22); error_txt.autoSize = true; error_txt.text = e.toString(); } See also Error class, try..catch..
CHAPTER 5 ActionScript Core Language Elements trace() Availability Flash Player 4. Usage trace(expression) Parameters expression An expression to evaluate. Returns Nothing. Description You can use Flash Debug Player to capture output from the trace() function and write that output to the log file. Statement; evaluates the expression and writes the result to the log file. Use this statement to record programming notes or to write messages in the log file.
CHAPTER 5 ActionScript Core Language Elements true Availability Flash Player 5. Usage true Description Constant; a unique Boolean value that represents the opposite of false. When automatic data typing converts true to a number, it becomes 1; when it converts true to a string, it becomes "true". Example The following example shows the use of true in an if statement: var shouldExecute:Boolean; /* ...
try..catch..finally CHAPTER 5 ActionScript Core Language Elements 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 { // ... finally block ... }] Parameters The expression thrown from a throw statement, typically an instance of the Error class or one of its subclasses.
If an error is thrown within a function, and the function does not include a catch handler, then the ActionScript interpreter exits that function, as well as any caller functions, until a catch block is found. During this process, finally handlers are called at all levels. Example The following example shows how to create a try..finally statement. Because code in the finally block is guaranteed to execute, it is typically used to perform any necessary clean-up after a try block executes.
The following example demonstrates a try..catch statement. The code within the try block is executed. If an exception is thrown by any code within the try block, control passes to the catch block, which shows the error message in a text field using the Error.toString() method. In the same directory as Account.as, create a new FLA document and enter the following ActionScript: import Account; var account:Account = new Account(); try { var returnVal = account.
function randomNum():Number { return Math.round(Math.random()*10)%3; } } Finally, in another AS file or FLA script, the following code invokes the sortRows() method on an instance of the RecordSet class. It defines catch blocks for each type of error that is thrown by sortRows(). import RecordSet; var myRecordSet:RecordSet = new RecordSet(); try { myRecordSet.sortRows(); trace("everything is fine"); } catch (e:RecordSetException) { trace(e.toString()); } catch (e:MalformedRecord) { trace(e.
CHAPTER 5 ActionScript Core Language Elements typeof Availability Flash Player 5. Usage typeof(expression) : String Parameters expression A string, movie clip, button, object, or function. Description Operator; a unary operator placed before a single parameter. The typeof operator causes the Flash interpreter to evaluate expression; the result is a string specifying whether the expression is a string, movie clip, object, function, number, or Boolean value.
undefined CHAPTER 5 ActionScript Core Language Elements 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 undefined. The ActionScript code typeof(undefined) returns the string "undefined". The only value of type undefined is undefined. The value of undefined.toString() is undefined.
unescape() CHAPTER 5 ActionScript Core Language Elements Availability Flash Player 5. Usage unescape(x:String) : String Parameters x A string with hexadecimal sequences to escape. Returns A string decoded from a URL-encoded parameter. Description Function; evaluates the parameter x as a string, decodes the string from URL-encoded format (converting all hexadecimal sequences to ASCII characters), and returns the string.
CHAPTER 5 ActionScript Core Language Elements var Availability Flash Player 5. Usage var variableName [= value1] [...,variableNameN [=valueN]] Parameters variableName value An identifier. The value assigned to the variable. Returns Nothing. Description Statement; used to declare local variables. If you declare variables inside a function, the variables are local. They are defined for the function and expire at the end of the function call.
void CHAPTER 5 ActionScript Core Language Elements Availability Flash Player 5. Usage void (expression) function functionName():Void {} Description Usage 1: Operator; a unary operator that discards the expression value and returns an undefined value. The void operator is often used in comparisons using the equality (==) operator to test for undefined values. Usage 2: Data type; used in function definitions to indicate that a function will not return a value.
CHAPTER 5 ActionScript Core Language Elements while Availability Flash Player 4. Usage while(condition) { statement(s); } Parameters condition An expression that evaluates to true or false. statement(s) The instructions to execute if the condition evaluates to true. Returns Nothing. Description Statement; evaluates a condition and if the condition evaluates to true, runs a statement or series of statements before looping back to evaluate the condition again.
i += 3; } The following result is written to the log file. 0 3 6 9 12 15 18 See also do while, continue, for, for..
CHAPTER 5 ActionScript Core Language Elements with Availability Flash Player 5. Usage with (object:Object) { statement(s); } Parameters object An instance of an ActionScript object or movie clip. statement(s) An action or group of actions enclosed in curly braces ({}). Returns Nothing. Description Statement; lets you specify an object (such as a movie clip) with the object parameter and evaluate expressions and actions inside that object with the statement(s) parameter.
Instead of using with(), you can use direct paths. If you find that paths are long and cumbersome to type, you can create a local variable and store the path in the variable, which you can then reuse in your code, as shown in the following ActionScript: var shortcut = this._parent._parent.name_txt; shortcut.text = "Hank"; shortcut.autoSize = true; Example The with statement is useful for accessing multiple items in a scope chain list simultaneously.
CHAPTER 6 ActionScript Core Classes This chapter describes functions, properties, and classes of Macromedia Flash Player that you can use in a Macromedia Flex application. However, many of the items described in this chapter are not for use in typical Flex applications and should be used only as necessary. For more information on the items that Macromedia recommends that you use in a Flex application, see Flex ActionScript and MXML API Reference.
CHAPTER 6 ActionScript Core Classes Accessibility class Availability Flash Player 6. Description The Accessibility class manages communication with screen readers. Screen readers are a type of assistive technology for visually impaired users that provides an audio version of screen content. The methods of the Accessibility class are static—that is, you don’t have to create an instance of the class to use its methods.
Example The following example checks whether an accessibility aid is currently active: if (Accessibility.isActive()) { trace ("An accessibility aid is currently active"); } else { trace ("There is currently no active accessibility aid"); } See also Accessibility.updateProperties(), _accProps, System.capabilities.hasAccessibility Accessibility.updateProperties() Availability Flash Player 6 (6.0.65). Usage Accessibility.updateProperties() : Void Parameters None. Returns Nothing.
CHAPTER 6 ActionScript Core Classes _accProps Availability Flash Player 6.65. Usage _accProps.propertyName instanceName._accProps.propertyName Parameters propertyName An accessibility property name (see the following description for valid names). The instance name assigned to an instance of a movie clip, button, dynamic text field, or input text field. To refer to the _accProps object that represents the entire Flash document, omit instanceName.
To refer to the _accProps object that represents the entire Flash document, omit the instanceName parameter. The value of _accProps must be an object. This means that if no _accProps object already exists, you must create one, as shown in the following example, before you can assign values to the properties of the _accProps object: if ( _accProps == undefined ) { _accProps = new Object(); } _accProps.
CHAPTER 6 ActionScript Core Classes arguments object Availability Flash Player 5; property added in Flash Player 6. Description The arguments object 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. A local variable, arguments, is also created and lets you refer to the arguments object.
} } trace(factorial(4)); // output: 24 arguments.caller Availability Flash Player 6. Usage arguments.caller:Function Description Property; refers to the calling function. The value of this property is null if the current function was not called by another function.
Description Property; the number of parameters actually passed to a function. Example The following ActionScript includes a function called getArgLength, which returns the number of arguments that are passed into the function. Although the method expects three arguments, you can pass as many arguments as you want. function getArgLength(param_arg1:String, param_arg2:String, param_arg3:String) { return (arguments.
CHAPTER 6 ActionScript Core Classes Array class Availability Flash Player 5. Description The Array class lets you access and manipulate arrays. An array is an object whose properties are identified by a number representing their position in the array. This number is referred to as the index. All arrays are zero-based, which means that the first element in the array is [0], the second element is [1], and so on. To create an Array object, you use the constructor new Array().
Constructor for the Array class Availability Flash Player 5. Usage new Array() : Array new Array(length:Number) : Array new Array(element0, element1, element2,...elementN) : Array Parameters length An integer that specifies the number of elements in the array. A list of two or more arbitrary values. The values can be of type Boolean, Number, String, Object, or Array. The first element in an array always has an index or position of 0. element0...
Usage 3: The following example creates the new Array object go_gos_array with an initial length of 5: var go_gos_array:Array = new Array("Belinda", "Gina", "Kathy", "Charlotte", "Jane"); trace(go_gos_array.length); // returns 5 trace(go_gos_array.
var alphaNumeric_array:Array =alpha_array.concat(numeric_array); trace(alphaNumeric_array); // creates array [a,b,c,1,2,3] The following code concatenates three arrays: var num1_array:Array = [1,3,5]; var num2_array:Array = [2,4,6]; var num3_array:Array = [7,8,9]; var nums_array:Array=num1_array.concat(num2_array,num3_array) trace(nums_array); // creates array [1,3,5,2,4,6,7,8,9] Nested arrays are not flattened in the same way as normal arrays.
Example The following example creates an array with three elements: Earth, Moon, and Sun. It then joins the array three times—first using the default separator (a comma [,] and a space), then using a dash (-), and then using a plus sign (+). var a_array:Array = new Array("Earth","Moon","Sun") trace(a_array.join()); // displays Earth,Moon,Sun trace(a_array.join(" - ")); // displays Earth - Moon - Sun trace(a_array.
my_array[9] = 'c'; trace(my_array.length); // my_array.length is updated to 10 trace(my_array); // displays: // a,b,undefined,undefined,undefined,undefined,undefined,undefined,undefined,c // if the length property is now set to 5, the array will be truncated my_array.length = 5; trace(my_array.length); // my_array.length is updated to 5 trace(my_array); // outputs: a,b,undefined,undefined,undefined Array.pop() Availability Flash Player 5. Usage my_array.pop() : Object Parameters None.
Returns An integer representing 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 myPets_array with two elements, cat and dog. The second line adds two elements to the array. Because the push() method returns the new length of the array, the trace() statement in the last line sends the new length of myPets_array (4) to the log file.
Array.shift() Availability Flash Player 5. Usage my_array.shift() : Object 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 myPets_array and then removes the first element from the array and assigns it to the variable shifted: var myPets_array:Array = new Array("cat", "dog", "bird", "fish"); var shifted:String = myPets_array.
Description Method; returns a new array that consists of a range of elements from the original array, without modifying the original array. The returned array includes the start element and all elements up to, but not including, the end element. If you don’t pass any parameters, a duplicate of my_array is created.
One or more numbers or names of defined constants, separated by the | (bitwise OR) operator, that change the behavior of the sort from the default. The following values are acceptable for option: option • • • • • 1 or Array.CASEINSENSITIVE 2 or Array.DESCENDING 4 or Array.UNIQUESORT 8 or Array.RETURNINDEXEDARRAY 16 or Array.NUMERIC For information on this parameter, see Array.sortOn(). Note: Array.
Example Usage 1: The following example shows the use of Array.sort() with and without a value passed for option: var fruits_array:Array = new Array("oranges", "apples", "strawberries", "pineapples", "cherries"); trace(fruits_array); // displays oranges,apples,strawberries,pineapples,cherries fruits_array.sort(); trace(fruits_array); // writes apples,cherries,oranges,pineapples,strawberries fruits_array.sort(Array.
Array.sortOn() Availability Flash Player 6; additional capabilities added in Flash Player 7. Usage my_array.sortOn("fieldName":String ) : Array my_array.sortOn("fieldName":String, option:Number | option |... ) : Array my_array.sortOn( [ "fieldName" , "fieldName" , ... ]:Array) : Array my_array.sortOn( [ "fieldName" , "fieldName" , ... ]:Array , option:Number | option |...
By default, Array.sortOn() works as described in the following list: • Sorting is case-sensitive (Z precedes a). • Sorting is ascending (a precedes b). • The array is modified to reflect the sort order; multiple elements that have identical sort fields are placed consecutively in the sorted array in no particular order. • Numeric fields are sorted as if they were strings, so 100 precedes 99, because “1” is a lower string value than “9”. You can use the option flags to override these defaults.
Performing a default sort on the age field produces the following results: my_array.sortOn("age"); // 29 // 3 // 35 // 4 Performing a numeric sort on the age field produces the following results: my_array.sortOn("age", 16); // 3 // 4 // 29 // 35 Performing a descending numeric sort on the age field produces the following results: my_array.sortOn("age", 18); // 35 // 29 // 4 // 3 Performing a sort changes the elements in the array produces the following results: // // // // // Before sorting my_array[0].
Example The following example creates a new array and sorts it according to the fields name and city: The first sort uses name as the first sort value and city as the second. The second sort uses city as the first sort value and name as the second. var rec_array:Array = new Array(); rec_array.push( { name: "john", city: "omaha", zip: 68144 } ); rec_array.push( { name: "john", city: "kansas city", zip: 72345 } ); rec_array.push( { name: "bob", city: "omaha", zip: 94010 } ); for(i=0; i
deleteCount An integer that specifies the number of elements to be deleted. This number includes the element specified in the start parameter. If no value is specified for deleteCount, the method deletes all the values from the start element to the last element in the array. If the value is 0, no elements are deleted. value An optional parameter that specifies the values to insert into the array at the insertion point specified in the start parameter.
Parameters None. Returns A string. Description Method; returns a String value representing the elements in the specified Array object. Every element in the array, starting with index 0 and ending with index my_array.length-1, is converted to a concatenated string and separated by commas. To specify a custom separator, use Array.join().
Example The following example shows the use of Array.unshift(): var pets_array:Array = new Array("dog", "cat", "fish"); trace( pets_array ); // dog,cat,fish pets_array.unshift("ferrets", "gophers", "engineers"); trace( pets_array ); // ferrets,gophers,engineers,dog,cat,fish Array.
CHAPTER 6 ActionScript Core Classes Boolean class Availability Flash Player 5. Description The Boolean class is a wrapper object with the same functionality as the standard JavaScript Boolean object. Use the Boolean class to retrieve the primitive data type or string representation of a Boolean object. You must use the constructor new Boolean() to create a Boolean object before calling its methods. Method summary for the Boolean class Method Description Boolean.
Usage myBoolean.toString() : String Parameters None. Returns A string; "true" or "false". Description Method; returns the string representation ("true" or "false") of the Boolean object. Example This example creates a variable of type Boolean and uses toString() to convert the value to a string for use in the trace statement: var myBool:Boolean = true; trace("The value of the Boolean myBool is: " + myBool.toString()); myBool = false; trace("The value of the Boolean myBool is: " + myBool.
CHAPTER 6 ActionScript Core Classes Date class Availability Flash Player 5. Description The Date class lets you retrieve date and time values relative to universal time (Greenwich Mean Time, now called universal time or UTC) or relative to the operating system on which Flash Player is running. The methods of the Date class are not static but apply only to the individual Date object specified when the method is called. The Date.UTC() method is an exception; it is a static method.
Method Description Date.setDate() Sets the day of the month according to local time. Returns the new time in milliseconds. Date.setFullYear() Sets the full year according to local time. Returns the new time in milliseconds. Date.setHours() Sets the hour according to local time. Returns the new time in milliseconds. Date.setMilliseconds() Sets the milliseconds according to local time. Returns the new time in milliseconds. Date.setMinutes() Sets the minutes according to local time.
Constructor for the Date class Availability Flash Player 5. Usage new Date() : Date new Date(timeValue:Number) : Date new Date(year:Number, month:Number [, date:Number [, hour:Number [, minute:Number [, second:Number [, millisecond:Number ]]]]]) : Date Parameters A value of 0 to 99 indicates 1900 through 1999; otherwise all four digits of the year must be specified. year month An integer from 0 (January) to 11 (December). date An integer from 1 to 31. This parameter is optional.
Date.getDate() Availability Flash Player 5. Usage my_date.getDate() : Number Parameters None. Returns An integer. Description Method; returns the day of the month (an integer from 1 to 31) of the specified Date object according to local time. Local time is determined by the operating system on which Flash Player is running. Example The following example creates a new Date object and concatenates the returned values of Date.getMonth(), Date.getDate(), and Date.
Example The following example creates a new Date object and uses getDay() to determine the current day of the week: var dayOfWeek_array:Array = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"); var today_date:Date = new Date(); var day_str:String = dayOfWeek_array[today_date.getDay()]; trace("Today is "+day_str); Date.getFullYear() Availability Flash Player 5. Usage my_date.getFullYear() : Number Parameters None. Returns An integer representing the year.
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. Example The following example uses the constructor to create a Date object based on the current time and uses the getHours() method to display hour values from that object: var my_date:Date = new Date(); trace(my_date.
Example The following example uses the constructor to create a Date object based on the current time and uses the getMilliseconds() method to return the milliseconds value from that object: var my_date:Date = new Date(); trace(my_date.getMilliseconds()); Date.getMinutes() Availability Flash Player 5. Usage my_date.getMinutes() : Number Parameters None. Returns An integer. Description Method; returns the minutes (an integer from 0 to 59) of the specified Date object, according to local time.
Description Method; returns the month (0 for January, 1 for February, 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. Example The following example uses the constructor to create a Date object based on the current time and uses the getMonth() method to return the month value from that object: var my_date:Date = new Date(); trace(my_date.
Date.getTime() Availability Flash Player 5. Usage my_date.getTime() : Number 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.
Example The following example returns the difference between the local daylight saving time for San Francisco and universal time. Daylight saving time is factored into the returned result only if the date defined in the Date object occurs during daylight saving time. var my_date:Date = new Date(); trace(my_date.getTimezoneOffset()); // 420 is written to the log file // (7 hours * 60 minutes/hour = 420 minutes). // This example is Pacific Daylight Time (PDT, GMT-0700).
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 universal time. Example The following example creates a new Date object and uses Date.getUTCDay() and Date.getDay(). The value returned by Date.getUTCDay() can differ from the value returned by Date.getDay(), depending on the relationship between your local time zone and universal time. var today_date:Date = new Date(); trace(today_date.
Date.getUTCHours() Availability Flash Player 5. Usage my_date.getUTCHours() : Number Parameters None. Returns An integer. Description Method; returns the hour (an integer from 0 to 23) of the specified Date object, according to universal time. Example The following example creates a new Date object and uses Date.getUTCHours() and Date.getHours(). The value returned by Date.getUTCHours() may differ from the value returned by Date.
Example The following example creates a new Date object and uses getUTCMilliseconds() to return the milliseconds value from the Date object. var today_date:Date = new Date(); trace(today_date.getUTCMilliseconds()); Date.getUTCMinutes() Availability Flash Player 5. Usage my_date.getUTCMinutes() : Number Parameters None. Returns An integer. Description Method; returns the minutes (an integer from 0 to 59) of the specified Date object, according to universal time.
Description Method; returns the month (0 [January] to 11 [December]) of the specified Date object, according to universal time. Example The following example creates a new Date object and uses Date.getUTCMonth() and Date.getMonth(). The value returned by Date.getUTCMonth() can differ from the value returned by Date.getMonth() if today’s date is the first or last day of a month, depending on the relationship between your local time zone and universal time.
Returns An integer. 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. Example The following example creates a Date object with the month and year set to May 2004. The Date.getYear() method returns 104, and Date.getFullYear() returns 2004: var today_date:Date = new Date(2004,4); trace(today_date.
Date.setFullYear() Availability Flash Player 5. Usage my_date.setFullYear(year:Number [, month:Number [, date:Number]] ) : Number Parameters A four-digit number specifying a year. Two-digit numbers do not represent four-digit years; for example, 99 is not the year 1999, but the year 99. year An integer from 0 (January) to 11 (December). This parameter is optional. month date A number from 1 to 31. This parameter is optional. Returns An integer.
Description Method; sets the hours for the 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. Example The following example initially creates a new Date object, setting the time and date to 8:00 a.m. on May 15, 2004, and uses Date.setHours() to change the time to 4:00 p.m.: var my_date:Date = new Date(2004,4,15,8); trace(my_date.getHours()); // output: 8 my_date.
Date.setMinutes() Availability Flash Player 5. Usage my_date.setMinutes(minute:Number) : Number 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. Example The following example initially creates a new Date object, setting the time and date to 8:00 a.m.
Example The following example initially creates a new Date object, setting the date to May 15, 2004, and uses Date.setMonth() to change the date to June 15, 2004: var my_date:Date = new Date(2004,4,15); trace(my_date.getMonth()); //output: 4 my_date.setMonth(5); trace(my_date.getMonth()); //output: 5 Date.setSeconds() Availability Flash Player 5. Usage my_date.setSeconds(second:Number) : Number Parameters second An integer from 0 to 59. Returns An integer.
Returns An integer. Description Method; sets the date for the specified Date object in milliseconds since midnight on January 1, 1970, and returns the new time in milliseconds. Example The following example initially creates a new Date object, setting the time and date to 8:00 a.m. on May 15, 2004, and uses Date.setTime() to change the time to 8:30 a.m.: var my_date:Date = new Date(2004,4,15,8,0,0); var myDate_num:Number = my_date.
Date.setUTCFullYear() Availability Flash Player 5. Usage my_date.setUTCFullYear(year:Number [, month:Number [, date:Number]]) : Number Parameters year An integer that represents the year specified as a full four-digit year, such as 2000. An integer from 0 (January) to 11 (December). This parameter is optional. month date An integer from 1 to 31. This parameter is optional. Returns An integer.
Parameters hour A number; an integer from 0 (midnight) to 23 (11 p.m.). minute A number; an integer from 0 to 59. This parameter is optional. second A number; an integer from 0 to 59. This parameter is optional. millisecond A number; an integer from 0 to 999. This parameter is optional. Returns An integer. Description Method; sets the hour for the specified Date object in universal time and returns the new time in milliseconds.
Example The following example initially creates a new Date object, setting the date to 8:30 a.m. on May 15, 2004 with the milliseconds value set to 250, and uses Date.setUTCMilliseconds() to change the milliseconds value to 575: var my_date:Date = new Date(2004,4,15,8,30,0,250); trace(my_date.getUTCMilliseconds()); // output: 250 my_date.setUTCMilliseconds(575); trace(my_date.getUTCMilliseconds()); // output: 575 Date.setUTCMinutes() Availability Flash Player 5. Usage my_date.
Parameters An integer from 0 (January) to 11 (December). month date An integer from 1 to 31. This parameter is optional. Returns An integer. Description Method; sets the month, and optionally the day, 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, but Date.getUTCDay() and Date.
my_date.setUTCSeconds(45); trace(my_date.getUTCSeconds()); // output: 45 Date.setYear() Availability Flash Player 5. Usage my_date.setYear(year:Number) : Number Parameters A number that represents the year. If year is an integer between 0–99, setYear sets the year at 1900 + year; otherwise, the year is the value of the year parameter. year Returns An integer. Description Method; sets the year for the specified Date object in local time and returns the new time in milliseconds.
Returns A string. Description Method; returns a string value for the specified date object in a readable format. Example The following example returns the information in the dateOfBirth_date Date object as a string: var dateOfBirth_date:Date = new Date(74, 7, 12, 18, 15); trace (dateOfBirth_date); trace (dateOfBirth_date.toString()); /* The output from the trace statements will be in local time and will vary accordingly.
Example The following example creates a new maryBirthday_date Date object defined in universal time. This is the universal time variation of the example used for the new Date constructor method. var maryBirthday_date:Date = new Date(Date.
CHAPTER 6 ActionScript Core Classes Error class Availability Flash Player 7. Description Contains information about an error that occurred in a script. You create an Error object using the Error constructor function. Typically, you throw a new Error object from within a try code block that is then caught by a catch or finally code block. You can also create a subclass of the Error class and throw instances of that subclass. Method summary for the Error class Method Description Error.
throw new Error("Strings to not match."); } } try { compareStrings("Dog", "dog"); // output: Strings to not match. } catch (e_err:Error) { trace(e_err.toString()); } See also throw, try..catch..finally Error.message Availability Flash Player 7. Usage my_err.message:String Description Property; contains the message associated with the Error object. By default, the value of this property is "Error".
Error.name Availability Flash Player 7. Usage myError.name:String Description Property; contains the name of the Error object. By default, the value of this property is "Error". Example In the following example, a function throws a specified error depending on the two numbers that you try to divide: function divideNumber(numerator:Number, denominator:Number):Number { if (isNaN(numerator) || isNaN(denominator)) { throw new Error("divideNum function requires two numeric parameters.
Returns A string. Description Method; returns the string "Error" by default or the value contained in Error.message, if defined. Example In the following example, a function throws an error (with a specified message) if the two strings that are passed to it are not identical: function compareStrings(str1_str:String, str2_str:String):Void { if (str1_str != str2_str) { throw new Error("Strings to not match."); } } try { compareStrings("Dog", "dog"); // output: Strings to not match.
CHAPTER 6 ActionScript Core Classes Function class Availability Flash Player 6. Description Both user-defined and built-in functions in ActionScript are represented by Function objects, which are instances of the Function class. Method summary for the Function class Method Description Function.apply() Invokes the function represented by a Function object, with parameters passed in through an array. Function.call() Invokes the function represented by a Function object. Function.
The following simple example shows how apply() passes an array of parameters: function theFunction() { trace(arguments); } // create a new array to pass as a parameter to apply() var firstArray:Array = new Array(1,2,3); theFunction.apply(null,firstArray); // outputs: 1,2,3 // create a second array to pass as a parameter to apply() var secondArray:Array = new Array("a", "b", "c"); theFunction.
Function.call() Availability Flash Player 6. Usage myFunction.call(thisObject:Object, parameter1, ..., parameterN) Parameters thisObject An object that specifies the value of this within the function body. A parameter to be passed to the myFunction. You can specify zero or more parameters. parameter1 parameterN Returns Nothing. Description Method; invokes the function represented by a Function object.
var obj:Object = new myObject(); myMethod.call(obj, obj); The trace() statement displays: The trace() statement sends the following code to the log file: this == obj? true See also Function.
CHAPTER 6 ActionScript Core Classes 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. The properties of the Key class are constants representing the keys most commonly used to control games.
Property Description Key code Key.PGUP The key code value for the Page Up key. 33 Key.RIGHT The key code value for the Right Arrow key. 39 Key.SHIFT The key code value for the Shift key. 16 Key.SPACE The key code value for the Spacebar. 32 Key.TAB The key code value for the Tab key. 9 Key.UP The key code value for the Up Arrow key. 38 Listener summary for the Key class Method Description Key.onKeyDown Notified when a key is pressed. Key.onKeyUp Notified when a key is released.
myListener.onKeyUp = function () { trace ("You released a key."); } Key.addListener(myListener); The following example assigns the keyboard shortcut Control+7 to a button with an instance name of my_btn and makes information about the shortcut available to screen readers (see _accProps). In this example, when you press Control+7 the myOnPress function writes the text “hello” to the log file. function myOnPress() { trace("hello"); } function myOnKeyDown() { // 55 is key code for 7 if (Key.isDown(Key.
}; Key.addListener(keyListener); Key.CAPSLOCK Availability Flash Player 5. Usage Key.CAPSLOCK:Number Description Property; constant associated with the key code value for the Caps Lock key (20). Example The following example creates a new listener object and defines a function for onKeyDown. The last line uses addListener() to register the listener with the Key object so that it can receive notification from the key down event. var keyListener:Object = new Object(); keyListener.
} function myOnKeyDown() { // 55 is key code for 7 if (Key.isDown(Key.CONTROL) && Key.getCode() == 55) { Selection.setFocus(my_btn); my_btn.onPress(); } } var myListener:Object = new Object(); myListener.onKeyDown = myOnKeyDown; Key.addListener(myListener); my_btn.onPress = myOnPress; my_btn._accProps.shortcut = "Ctrl+7"; Accessibility.updateProperties(); Key.DELETEKEY Availability Flash Player 5. Usage Key.
}; Key.addListener(keyListener); Key.DOWN Availability Flash Player 5. Usage Key.DOWN:Number Description Property; constant associated with the key code value for the Down Arrow key (40). Example The following example moves a movie clip called car_mc a constant distance (10) when you press the arrow keys. A sound plays when you press the Spacebar. Give a sound in the library a linkage identifier of horn_id for this example. var DISTANCE:Number = 10; var horn_sound:Sound = new Sound(); horn_sound.
Description Property; constant associated with the key code value for the End key (35). Key.ENTER Availability Flash Player 5. Usage Key.ENTER:Number Description Property; constant associated with the key code value for the Enter key (13). Example The following example moves a movie clip called car_mc a constant distance (10) when you press the arrow keys. The car_mc instance stops when you press Enter and delete the onEnterFrame event.
Key.ESCAPE Availability Flash Player 5. Usage Key.ESCAPE:Number Description Property; constant associated with the key code value for the Escape key (27). Example The following example sets a timer. When you press Escape, the log file writes information that includes how long it took you to press the key. var keyListener:Object = new Object(); keyListener.onKeyDown = function() { if (Key.isDown(Key.ESCAPE)) { // get the current timer, convert the value to seconds and round it to two decimal places.
Example The following example calls the getAscii() method any time a key is pressed. The example creates a listener object named keyListener and defines a function that responds to the onKeyDown event by calling Key.getAscii(). The keyListener object is then registered to the Key object, which broadcasts the onKeyDown message whenever a key is pressed while the SWF file plays. var keyListener:Object = new Object(); keyListener.onKeyDown = function() { trace("The ASCII code for the last key typed is: "+Key.
Example The following example calls the getCode() method any time a key is pressed. The example creates a listener object named keyListener and defines a function that responds to the onKeyDown event by calling Key.getCode(). The keyListener object is then registered to the Key object, which broadcasts the onKeyDown message whenever a key is pressed while the SWF file plays. var keyListener:Object = new Object(); keyListener.onKeyDown = function() { // compare return value of getCode() to constant if (Key.
this.attachMovie("car_id", "car_mc", this.getNextHighestDepth(), {_x:0, _y:0}); car_mc.onPress = function() { this.startDrag(); }; car_mc.onRelease = function() { this.stopDrag(); }; var keyListener:Object = new Object(); keyListener.onKeyDown = function() { if (Key.isDown(Key.HOME)) { car_mc._x = 0; car_mc._y = 0; } }; Key.addListener(keyListener); Key.INSERT Availability Flash Player 5. Usage Key.INSERT:Number Description Property; constant associated with the key code value for the Insert key (45).
Parameters keycode The key code value assigned to a specific key or a Key class property associated with a specific key. To match the returned key code value with the key on a standard keyboard, see Appendix B, “Keyboard Keys and Key Code Values,” on page 811. Returns A Boolean value. Description Method: returns true if the key specified in keycode is pressed; false otherwise. On the Macintosh, the key code values for the Caps Lock and Num Lock keys are identical. Key.
Information is written to the log file when you press the Caps Lock key. The log file writes either true or false, depending on whether the Caps Lock is activated using the isToggled method. The following example creates two text fields that update when the Caps Lock and Num Lock keys are toggled. Each text field displays true when the key is activated, and false when the key is deactivated. this.createTextField("capsLock_txt", this.getNextHighestDepth(), 0, 0, 100, 22); capsLock_txt.
break; case Key.RIGHT : car_mc._x += DISTANCE; break; case Key.DOWN : car_mc._y += DISTANCE; break; } }; Key.addListener(keyListener_obj); Key.onKeyDown Availability Flash Player 6. Usage keyListener.onKeyDown Description Listener; notified when a key is pressed. To use onKeyDown, you must create a listener object.
Description Listener; notified when a key is released. To use onKeyUp, you must create a listener object. You can then define a function for onKeyUp and use addListener() to register the listener with the Key object, as shown in the following example: var keyListener:Object = new Object(); keyListener.onKeyDown = function() { trace("DOWN -> Code: "+Key.getCode()+"\tACSII: "+Key.getAscii()+"\tKey: "+chr(Key.getAscii())); }; keyListener.onKeyUp = function() { trace("UP -> Code: "+Key.
Key.PGUP Availability Flash Player 5. Usage Key.PGUP:Number Description Property; constant associated with the key code value for the Page Up key (33). Example The following example rotates a movie clip called car_mc when you press the Page Down and Page Up keys. var keyListener:Object = new Object(); keyListener.onKeyDown = function() { if (Key.isDown(Key.PGDN)) { car_mc._rotation += 5; } else if (Key.isDown(Key.PGUP)) { car_mc._rotation -= 5; } }; Key.addListener(keyListener); Key.
switch (Key.getCode()) { case Key.LEFT : car_mc._x -= 10; break; case Key.RIGHT : car_mc._x += 10; break; case Key.ESCAPE : Key.removeListener(keyListener); } }; Key.addListener(keyListener); Key.RIGHT Availability Flash Player 5. Usage Key.RIGHT:Number Description Property; constant associated with the key code value for the Right Arrow key (39). Example The following example moves a movie clip called car_mc a constant distance (10) when you press the arrow keys.
Key.SHIFT Availability Flash Player 5. Usage Key.SHIFT:Number Description Property; constant associated with the key code value for the Shift key (16). Example The following example scales car_mc when you press Shift. var keyListener:Object = new Object(); keyListener.onKeyDown = function() { if (Key.isDown(Key.SHIFT)) { car_mc._xscale *= 2; car_mc._yscale *= 2; } else if (Key.isDown(Key.CONTROL)) { car_mc._xscale /= 2; car_mc._yscale /= 2; } }; Key.addListener(keyListener); Key.
case Key.LEFT : car_mc._x -= DISTANCE; break; case Key.UP : car_mc._y -= DISTANCE; break; case Key.RIGHT : car_mc._x += DISTANCE; break; case Key.DOWN : car_mc._y += DISTANCE; break; } }; Key.addListener(keyListener_obj); Key.TAB Availability Flash Player 5. Usage Key.TAB:Number Description Property; constant associated with the key code value for the Tab key (9). Example The following example creates a text field, and displays the date in the text field when you press Tab. this.
Description Property; constant associated with the key code value for the Up Arrow key (38). Example The following example moves a movie clip called car_mc a constant distance (10) when you press the arrow keys. A sound plays when you press the Spacebar. Give a sound in the library a linkage identifier of horn_id for this example. var DISTANCE:Number = 10; var horn_sound:Sound = new Sound(); horn_sound.attachSound("horn_id"); var keyListener_obj:Object = new Object(); keyListener_obj.
CHAPTER 6 ActionScript Core Classes LoadVars class Availability Flash Player 6. Description You can use the LoadVars class to obtain verification of successful data loading and to monitor download progress. 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. It also lets you send specific variables, rather than all the variables, which can make your application more efficient. You can use the LoadVars.
Property summary for the LoadVars class Property Description LoadVars.contentType A string that indicates the MIME type of the data. LoadVars.loaded A Boolean value that indicates whether a load or sendAndLoad operation has completed. Event handler summary for the LoadVars class Event handler Description LoadVars.onData Invoked when data has been completely downloaded from the server, or when an error occurs while data is downloading from a server. LoadVars.
Parameters headerName headerValue A string that represents an HTTP request header name. A string that represents the value associated with headerName. Returns Nothing. Description Method; adds or changes HTTP request headers (such as Content-Type or SOAPAction) sent with POST actions. In the first usage, you pass two strings to the method: headerName and headerValue. In the second usage, you pass an array of strings, alternating header names and header values.
LoadVars.contentType Availability Flash Player 6. Usage my_lv.contentType:String Description Property; the MIME type that is sent to the server when you call LoadVars.send() or LoadVars.sendAndLoad(). The default is application/x-www-form-urlencoded. Example The following example creates a LoadVars object and displays the default content type of the data that is sent to the server. var my_lv:LoadVars = new LoadVars(); trace(my_lv.
trace(my_lv.toString()); // Iterate over properties in my_lv for (var prop in my_lv) { trace(prop+" -> "+my_lv[prop]); } See also LoadVars.onData, XML.parseXML() LoadVars.getBytesLoaded() Availability Flash Player 6. Usage my_lv.getBytesLoaded() : Number Parameters None. Returns An integer. Description Method; returns the number of bytes downloaded by LoadVars.load() or LoadVars.sendAndLoad(). This method returns undefined if no load operation is in progress or if a load operation has not yet begun.
my_lv.onLoad = function(success:Boolean) { loadvars_pb.setProgress(my_lv.getBytesLoaded(), my_lv.getBytesTotal()); delete timer_mc.onEnterFrame; if (success) { trace("LoadVars loaded successfully."); } else { trace("An error occurred while loading variables."); } }; my_lv.load("[place a valid URL pointing to a text file here]"); LoadVars.getBytesTotal() Availability Flash Player 6. Usage my_lv.getBytesTotal() : Number Parameters None. Returns An integer.
trace("Loaded "+lvBytesLoaded+" of "+lvBytesTotal+" bytes."); loadvars_pb.setProgress(lvBytesLoaded, lvBytesTotal); } }; my_lv.onLoad = function(success:Boolean) { loadvars_pb.setProgress(my_lv.getBytesLoaded(), my_lv.getBytesTotal()); delete timer_mc.onEnterFrame; if (success) { trace("LoadVars loaded successfully."); } else { trace("An error occurred while loading variables."); } }; my_lv.load("[place a valid URL pointing to a text file here]"); LoadVars.
var my_lv:LoadVars = new LoadVars(); my_lv.onLoad = function(success:Boolean) { if (success) { trace(this.toString()); } else { trace("Error loading/parsing LoadVars."); } }; my_lv.load("http://www.flash-mx.com/mm/params.txt"); For an in-depth example, see “Using the LoadVars class” on page 69 and the Macromedia DevNet article “Macromedia Flash MX and PHP” at www.macromedia.com/devnet/mx/flash/articles/ flashmx_php.html. LoadVars.loaded LoadVars.loaded Availability Flash Player 6. Usage my_lv.
LoadVars.onData Availability Flash Player 6. Usage my_lv.onData = function(src:String) { // your statements here } Parameters src A string or undefined; the raw (unparsed) data from a LoadVars.load() or method call. LoadVars.sendAndLoad() Returns Nothing. Description Event handler; invoked when data has completely downloaded from the server or when an error occurs while data is downloading from a server.
LoadVars.onLoad Availability Flash Player 6. Usage my_lv.onLoad = function(success:Boolean) { // your statements here } Parameters success A Boolean value that indicates whether the load operation ended in success (true) or failure (false). Returns A Boolean value. Description Event handler; invoked when a LoadVars.load() or LoadVars.sendAndLoad() operation has ended.
Returns A Boolean value; false if no parameters are specified, true otherwise. Description Method; sends the variables in the my_lv object to the specified URL. All enumerable variables in my_lv are concatenated into a string in the application/x-www-form-urlencoded format by default, and the string is posted to the URL using the HTTP POST method. The MIME content type sent in the HTTP request headers is the value of my_lv.contentType or the default application/x-www-form-urlencoded.
Parameters url A string; the URL to which to upload variables. If the SWF file issuing this call is running in a web browser, url must be in the same domain as the SWF file; for details, see “Description”. targetObject method LoadVars; the LoadVars object that receives the downloaded variables. A string; the GET or POST method of the HTTP protocol. Returns A Boolean value. Description Method; posts variables in the my_lv object to the specified URL.
Example The following example instantiates a new LoadVars() object, creates two properties, and uses toString() to return a string containing both properties in URL encoded format: var my_lv:LoadVars = new LoadVars(); my_lv.name = "Gary"; my_lv.age = 26; trace (my_lv.toString()); //output: age=26&name=Gary LoadVars.
CHAPTER 6 ActionScript Core Classes 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 fscommand() or JavaScript. LocalConnection objects can communicate only among SWF files that are running on the same client computer, but they can be running in different applications—for example, a SWF file running in a browser and a SWF file running in a projector.
Method Description LocalConnection.domain() Returns a string representing the superdomain of the location of the current SWF file. LocalConnection.send() Invokes a method on a specified LocalConnection object. Event handler summary for the LocalConnection class Event handler Description LocalConnection.allowDomain Invoked whenever the current (receiving) LocalConnection object receives a request to invoke a method from a sending LocalConnection object. LocalConnection.
}; receiving_lc.connect("lc_name"); The following SWF file sends the request to the first SWF file. // Code in the sending SWF file var sending_lc:LocalConnection = new LocalConnection(); sending_lc.send("lc_name", "methodToExecute", 5, 7); See also LocalConnection.connect(), LocalConnection.send() LocalConnection.allowDomain Availability Flash Player 6; behavior changed in Flash Player 7. Usage receiving_lc.
In files authored for Flash Player 6, the sendingDomain parameter contains the superdomain of the caller. In files authored for Flash Player 7 or later, the sendingDomain parameter contains the exact domain of the caller. In the latter case, to allow access by SWF files hosted at either www.domain.com or store.domain.com, you must explicitly allow access from both domains. // For Flash Player 6 receiving_lc.allowDomain = function(sendingDomain) { return(sendingDomain=="domain.
domain_txt.text = sendingDomain; return true; }; my_lc.allowInsecureDomain = function(sendingDomain:String) { return (sendingDomain == this.domain()); } my_lc.sayHello = function(name:String) { welcome_txt.text = "Hello, "+name; }; my_lc.connect("_mylc"); The following example sends a string to the previous SWF file and displays a status message about whether the local connection was able to connect to the file.
LocalConnection.allowInsecureDomain Availability Flash Player 7. Usage receiving_lc.allowInsecureDomain = function([sendingDomain:String]) : Boolean { // Your statements here return true or false } Parameters A string that represents an optional parameter specifying the domain of the SWF file that contains the sending LocalConnection object. sendingDomain Returns A Boolean value.
}; my_lc.allowInsecureDomain = function(sendingDomain:String) { return (sendingDomain == this.domain()); } my_lc.sayHello = function(name:String) { welcome_txt.text = "Hello, "+name; }; my_lc.connect("lc_name"); See also LocalConnection.allowDomain, LocalConnection.connect() LocalConnection.close() Availability Flash Player 6. Usage receiving_lc.close() : Void Parameters None. Returns Nothing. Description Method; closes (disconnects) a LocalConnection object.
}; close_button.addEventListener("click", closeListener); See also LocalConnection.connect() LocalConnection.connect() Availability Flash Player 6. Usage receiving_lc.connect(connectionName:String) : Boolean Parameters connectionName A string that corresponds to the connection name specified in the command that wants to communicate with receiving_lc. LocalConnection.
If you are implementing communication between SWF files in different domains, specifying a string for connectionName that begins with an underscore (_) will make the SWF with the receiving LocalConnection object more portable between domains. Here are the two possible cases: • If the string for connectionName does not begin with an underscore (_), Flash Player adds a prefix with the superdomain and a colon (for example, "myDomain:connectionName").
playback_pb.setStyle("themeColor", "haloBlue"); this.createEmptyMovieClip("timer_mc", this.getNextHighestDepth()); var receiving_lc:LocalConnection = new LocalConnection(); receiving_lc.playMP3 = function(mp3Path:String, mp3Name:String) { song_lbl.text = mp3Name; playback_pb.indeterminate = true; my_sound = new Sound(); my_sound.onLoad = function(success:Boolean) { playback_pb.indeterminate = false; }; my_sound.onSoundComplete = function() { delete timer_mc.onEnterFrame; }; timer_mc.
Returns A string representing the domain of the location of the current SWF file; for more information, see the Description section. Description 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".
Line numbers are included for reference purposes. The sequence of events is described in the following list: • The receiving SWF file prepares to receive commands on a connection named "sum" (line 11). The Flash Player resolves the name of this connection to "mydomain.com:sum" (see LocalConnection.connect()). • The sending SWF file prepares to receive a reply on the LocalConnection object named (line 67). It also specifies that it will accept commands only from SWF files at mydomain.com (lines 51 to 53).
60 61 62 63 64 65 66 67 68 var domainArray:Array = channelDomain.split("."); // if more than two elements are found, // chop off first element to create superdomain if (domainArray.length > 2) { domainArray.shift(); channelDomain = domainArray.join("."); } } lc.connect("result"); lc.send("mydomain.com:sum", "aSum", channelDomain + ':' + "result", "aResult", 123, 456); See also LocalConnection.allowDomain LocalConnection.onStatus Availability Flash Player 6. Usage sending_lc.
If the information object returned by this event handler contains a level value of error, Flash cannot send the command to a receiving LocalConnection object, most likely because there is no receiving LocalConnection object connected whose name corresponds to the name specified in the sending_lc.send() command that invoked this handler. In addition to this onStatus handler, Flash also provides a “super” function called System.onStatus.
method A string specifying the name of the method to be invoked in the receiving LocalConnection object. The following method names cause the command to fail: send, connect, close, domain, onStatus, and allowDomain. p1,...pN Optional parameters to be passed to the specified method. Returns A Boolean value: true if Flash can carry out the request; false otherwise.
See also LocalConnection.allowDomain, LocalConnection.connect(), LocalConnection.domain(), LocalConnection.onStatus LocalConnection.
CHAPTER 6 ActionScript Core Classes Math class Availability Flash Player 5. In Flash Player 4, the methods and properties of the Math class are emulated using approximations and might not be as accurate as the non-emulated math functions that Flash Player 5 supports. Description The Math class is a top-level class whose methods and properties you can use without using a constructor. Use the methods and properties of this class to access and manipulate mathematical constants and functions.
Method Description Math.pow() Computes x raised to the power of the y. Math.random() Returns a pseudo-random number between 0.0 and 1.0. Math.round() Rounds to the nearest integer. Math.sin() Computes a sine. Math.sqrt() Computes a square root. Math.tan() Computes a tangent. Property summary for the Math class All the following properties for the Math class are constants: Property Description Math.E Euler’s constant and the base of natural logarithms (approximately 2.718). Math.
Example The following example shows how Math.abs() returns the absolute value of a number and does not affect the value of the x parameter (called num in this example): var num:Number = -12; var numAbsolute:Number = Math.abs(num); trace(num); // output: -12 trace(numAbsolute); // output: 12 Math.acos() Availability Flash Player 5.
Parameters x A number from -1.0 to 1.0. Returns A number between negative pi divided by 2 and positive pi divided by 2. Description Method; computes and returns the arc sine for the number specified in the parameter x, in radians. Example The following example displays the arc sine for several values. trace(Math.asin(-1)); // output: -1.5707963267949 trace(Math.asin(0)); // output: 0 trace(Math.asin(1)); // output: 1.5707963267949 See also Math.acos(), Math.atan(), Math.atan2(), Math.cos(), Math.
See also Math.acos(), Math.asin(), Math.atan2(), Math.cos(), Math.sin(), Math.tan() Math.atan2() Availability Flash Player 5. In Flash Player 4, the methods and properties of the Math class are emulated using approximations and might not be as accurate as the non-emulated math functions that Flash Player 5 supports. Usage Math.atan2(y:Number, x:Number) : Number Parameters y A number specifying the y coordinate of the point. x A number specifying the x coordinate of the point. Returns A number.
Description Method; returns the ceiling of the specified number or expression. The ceiling of a number is the closest integer that is greater than or equal to the number. Example The following code returns a value of 13: Math.ceil(12.5); See also Math.floor(), Math.round() Math.cos() Availability Flash Player 5. In Flash Player 4, the methods and properties of the Math class are emulated using approximations and might not be as accurate as the non-emulated math functions that Flash Player 5 supports.
Math.E Availability Flash Player 5. In Flash Player 4, the methods and properties of the Math class are emulated using approximations and might not be as accurate as the non-emulated math functions that Flash Player 5 supports. Usage Math.E:Number Description Constant; a mathematical constant for the base of natural logarithms, expressed as e. The approximate value of e is 2.71828182845905. Example This example shows how Math.
Description Method; returns the value of the base of the natural logarithm (e), to the power of the exponent specified in the parameter x. The constant Math.E can provide the value of e. Example The following example displays the logarithm for two number values. trace(Math.exp(1)); // output: 2.71828182845905 trace(Math.exp(2)); // output: 7.38905609893065 Math.floor() Availability Flash Player 5.
Parameters x A number or expression with a value greater than 0. Returns The logarithm of parameter x. Description Method; returns the logarithm of parameter x. Example The following example displays the logarithm for three numerical values. trace(Math.log(0)); // output: -Infinity trace(Math.log(1)); // output: 0 trace(Math.log(2)); // output: 0.693147180559945 Math.LN2 Availability Flash Player 5.
Math.LOG2E Availability Flash Player 5. In Flash Player 4, the methods and properties of the Math class are emulated using approximations and might not be as accurate as the non-emulated math functions that Flash Player 5 supports. Usage Math.LOG2E:Number Parameters None. Returns Nothing. Description Constant; a mathematical constant for the base-2 logarithm of the constant e (Math.E), expressed as log2e, with an approximate value of 1.442695040888963387. Example This example traces the value of Math.
Math.max() Availability Flash Player 5. In Flash Player 4, the methods and properties of the Math class are emulated using approximations and might not be as accurate as the non-emulated math functions that Flash Player 5 supports. Usage Math.max(x:Number , y:Number) : Number Parameters x A number or expression. y A number or expression. Returns A number. Description Method; evaluates x and y and returns the larger value.
Description Method; evaluates x and y and returns the smaller value. Example The following example displays Sat Dec 25 00:00:00 GMT-0700 2004, which is the smaller of the evaluated expressions. var date1:Date = new Date(2004, 11, 25); var date2:Date = new Date(2004, 11, 30); var minDate:Number = Math.min(date1.getTime(), date2.getTime()); trace(new Date(minDate).toString()); See Also Math.max() Math.PI Availability Flash Player 5.
mc.curveTo(-Math.tan(Math.PI/8)*r+x, -r+y, x, -r+y); mc.curveTo(Math.tan(Math.PI/8)*r+x, -r+y, Math.sin(Math.PI/4)*r+x, Math.sin(Math.PI/4)*r+y); mc.curveTo(r+x, -Math.tan(Math.PI/8)*r+y, r+x, y); } Math.pow() Availability Flash Player 5. In Flash Player 4, the methods and properties of the Math class are emulated using approximations and might not be as accurate as the non-emulated math functions that Flash Player 5 supports. Usage Math.
}; Mouse.addListener(mouseListener); Math.random() Availability Flash Player 5. In Flash Player 4, the methods and properties of the Math class are emulated using approximations and might not be as accurate as the non-emulated math functions that Flash Player 5 supports. Usage Math.random() : Number Parameters None. Returns A number. Description Method; returns a pseudo-random number n, where 0 <= n < 1.
Returns A number; an integer. Description Method; rounds the value of the parameter x up or down to the nearest integer and returns the value. If parameter x is equidistant from its two nearest integers (that is, the number ends in .5), the value is rounded up to the next higher integer. Example The following example returns a random number between two specified integers. function randRange(min:Number, max:Number):Number { var randomNum:Number = Math.round(Math.
mc.moveTo(x+r, y); mc.curveTo(r+x, Math.tan(Math.PI/8)*r+y, Math.sin(Math.PI/4)*r+x, Math.sin(Math.PI/4)*r+y); mc.curveTo(Math.tan(Math.PI/8)*r+x, r+y, x, r+y); mc.curveTo(-Math.tan(Math.PI/8)*r+x, r+y, -Math.sin(Math.PI/4)*r+x, Math.sin(Math.PI/4)*r+y); mc.curveTo(-r+x, Math.tan(Math.PI/8)*r+y, -r+x, y); mc.curveTo(-r+x, -Math.tan(Math.PI/8)*r+y, -Math.sin(Math.PI/4)*r+x, Math.sin(Math.PI/4)*r+y); mc.curveTo(-Math.tan(Math.PI/8)*r+x, -r+y, x, -r+y); mc.curveTo(Math.tan(Math.PI/8)*r+x, -r+y, Math.sin(Math.
var line_mc:MovieClip = canvas_mc.createEmptyMovieClip("line"+nextDepth+"_mc", nextDepth); line_mc.moveTo(this.origX, this.origY); line_mc.lineStyle(2, 0x000000, 100); line_mc.lineTo(this.newX, this.newY); var hypLen:Number = Math.sqrt(Math.pow(line_mc._width, 2)+Math.pow(line_mc._height, 2)); line_mc.createTextField("length"+nextDepth+"_txt", canvas_mc.getNextHighestDepth(), this.origX, this.origY-22, 100, 22); line_mc['length'+nextDepth+'_txt'].text = Math.round(hypLen) +" pixels"; }; Mouse.
trace(Math.SQRT2); // Output: 1.4142135623731 Math.tan() Availability Flash Player 5. In Flash Player 4, the methods and properties of the Math class are emulated using approximations and might not be as accurate as the non-emulated math functions that Flash Player 5 supports. Usage Math.tan(x:Number) Parameters x A number that represents an angle measured in radians. Returns A number; tangent of parameter x. Description Method; computes and returns the tangent of the specified angle.
CHAPTER 6 ActionScript Core Classes Mouse class Availability Flash Player 5. Description The Mouse class is a top-level class whose properties and methods you can access without using a constructor. You can use the methods of the Mouse class to hide and show the mouse pointer (cursor) in the SWF file. The mouse pointer is visible by default. Method summary for the Mouse class Method Description Mouse.
Description Method; registers an object to receive notifications of the onMouseDown, onMouseMove, onMouseUp, and onMouseWheel listeners. (The onMouseWheel listener is supported only in Windows.) The newListener parameter should contain an object that has a defined method for at least one of the listeners.
Description Listener; notified when the mouse is pressed. To use the onMouseDown listener, you must create a listener object. You can then define a function for onMouseDown and use addListener() to register the listener with the Mouse object, as shown in the following code: var someListener:Object = new Object(); someListener.onMouseDown = function () { ... }; Mouse.
Mouse.onMouseMove Availability Flash Player 6. Usage someListener.onMouseMove Parameters None. Returns Nothing. Description Listener; notified when the mouse moves. To use the onMouseMove listener, you must create a listener object. You can then define a function for onMouseMove and use addListener() to register the listener with the Mouse object, as shown in the following code: var someListener:Object = new Object(); someListener.onMouseMove = function () { ... }; Mouse.
Mouse.onMouseUp Availability Flash Player 6. Usage someListener.onMouseUp Parameters None. Returns Nothing. Description Listener; notified when the mouse is released. To use the onMouseUp listener, you must create a listener object. You can then define a function for onMouseUp and use addListener() to register the listener with the Mouse object, as shown in the following code: var someListener:Object = new Object(); someListener.onMouseUp = function () { ... }; Mouse.
Mouse.onMouseWheel Availability Flash Player 6 (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 user rolls the mouse wheel. A positive delta value indicates an upward scroll; a negative value indicates a downward scroll. Typical values are from 1 to 3; faster scrolling can produce larger values.
mouseListener.onMouseWheel = function(delta:Number) { line_mc._rotation += delta; }; mouseListener.onMouseDown = function() { trace("Down"); }; Mouse.addListener(mouseListener); See also Mouse.addListener(), TextField.mouseWheelEnabled Mouse.removeListener() Availability Flash Player 6. Usage Mouse.removeListener (listener:Object) : Boolean Parameters listener An object.
mouseListener.onMouseDown = function() { this.isDrawing = true; canvas_mc.lineStyle(2, 0xFF0000, 100); canvas_mc.moveTo(_xmouse, _ymouse); }; mouseListener.onMouseMove = function() { if (this.isDrawing) { canvas_mc.lineTo(_xmouse, _ymouse); } updateAfterEvent(); }; mouseListener.onMouseUp = function() { this.isDrawing = false; }; Mouse.addListener(mouseListener); var clearListener:Object = new Object(); clearListener.click = function() { canvas_mc.clear(); }; clear_button.
Description Method; displays the mouse pointer in a SWF file. The pointer is visible by default. Example The following example attaches a custom cursor from the library when it rolls over a movie clip called my_mc. Give a movie clip a Linkage identifier of cursor_help_id, and add the following ActionScript : my_mc.onRollOver = function() { Mouse.hide(); this.attachMovie("cursor_help_id", "cursor_mc", this.getNextHighestDepth(), {_x:this._xmouse, _y:this._ymouse}); }; my_mc.onMouseMove = function() { this.
CHAPTER 6 ActionScript Core Classes Number class Availability Flash Player 5 (became a native object in Flash Player 6, which improved performance significantly). Description The Number class is a simple wrapper object for the Number data type. You can manipulate primitive numeric values by using the methods and properties associated with the Number class. This class is identical to the JavaScript Number class.
Constructor for the Number class Availability Flash Player 5. Usage new Number(value:Number) : Number Parameters The numeric value of the Number object being created or a value to be converted to a number. The default value is 0 if value is not provided. value Returns A reference to a Number object. Description Constructor; creates a new Number object. You must use the Number constructor when using Number.toString() and Number.valueOf().
This code logs the following values: Number.MIN_VALUE = 4.94065645841247e-324 Number.MAX_VALUE = 1.79769313486232e+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. Example The following ActionScript writes the largest and smallest representable numbers to the log file. trace("Number.MIN_VALUE = "+Number.MIN_VALUE); trace("Number.MAX_VALUE = "+Number.
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. Example This example compares the result of dividing the following values. var posResult:Number = 1/0; if (posResult == Number.
Parameters Specifies the numeric base (from 2 to 36) to use for the number-to-string conversion. If you do not specify the radix parameter, the default value is 10. radix Returns A string. Description Method; returns the string representation of the specified Number object (myNumber). Example The following example uses 2 and 8 for the radix parameter and returns a string that contains the corresponding representation of the number 9: var myNumber:Number = new Number(9); trace(myNumber.
CHAPTER 6 ActionScript Core Classes Object class Availability Flash Player 5 (became a native object in Flash Player 6, which improved performance significantly). Description The Object class is at the root of the ActionScript class hierarchy. This class contains a small subset of the features provided by the JavaScript Object class. Method summary for the Object class Method Description Object.addProperty() Creates a getter/setter property on an object. Object.
Returns A reference to an Object object. Description Constructor; creates an Object object and stores a reference to the object’s constructor method in the object’s constructor property. Example The following example creates a generic object named myObject: var myObject:Object = new Object(); Object.addProperty() Availability Flash Player 6. In ActionScript 2.0 classes, you can use get or set instead of this method. Usage myObject.
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 (similar to adding methods to prototype objects).
The previous example works, but the properties bookcount and bookname are added to every instance of the Book object, which requires having two properties for every instance of the object. If there are many properties, such as bookcount and bookname, in a class, they could consume a great deal of memory. Instead, you can add the properties to Book.prototype so that the bookcount and bookname properties exist only in one place.
Object.constructor Availability Flash Player 5 Usage myObject.constructor Description Property; reference to the constructor function for a given object instance. The constructor property is automatically assigned to all objects when they are created using the constructor for the Object class. Example The following example is a reference to the constructor function for the myObject object. var my_str:String = new String("sven"); trace(my_str.
Object.registerClass() Availability Flash Player 6. Usage Object.registerClass(symbolID:String, theClass:Function) : Boolean Parameters String; the linkage identifier of the movie clip symbol or the string identifier for the ActionScript class. symbolID A reference to the constructor function of the ActionScript class or null to unregister the symbol. theClass Returns A Boolean value: if the class registration succeeds, a value of true is returned; false otherwise.
This property is useful for enabling highly transparent client/server communication, and is the recommended way of invoking server-side methods. Example The following examples progressively build upon the first example and illustrate five different usages of the __resolve property. To aid understanding, key statements that differ from the previous usage are in bold typeface. Usage 1: the following example uses __resolve to build an object where every undefined property returns the value "Hello, world!".
// define the __resolve function myObject.__resolve = function(name) { trace("Resolve called for "+name); // to check when __resolve is called // Not only call the function, but also save a reference to it var f:Function = function () { this.myFunction(name); }; // create a new object method and assign it the reference this[name] = f; // return the reference return f; }; // test __resolve using undefined method names // __resolve will only be called once for each method name myObject.
// define a generic function for __resolve to call myObject.myFunction = function (name) { arguments.shift(); trace("Method " + name + " was called with arguments: " + arguments.join(',')); }; // define the __resolve function myObject.__resolve = function (name) { // reserve the name “onStatus” for local use if (name == "onStatus") { return undefined; } var f:Function = function () { arguments.unshift(name); this.myFunction.
Example This example shows the return value for toString() on a generic object: var myObject:Object = new Object(); trace(myObject.toString()); // output: [object Object] This method can be overridden to return a more meaningful value. The following examples show that this method has been overridden for the built-in classes Date, Array, and Number: // Date.toString() returns the current date and time var myDate:Date = new Date(); trace(myDate.toString()); // output: [current date and time] // Array.
trace(myVehicle.valueOf()); // output: A vehicle that is red and has 2 doors Object.unwatch() Availability Flash Player 6. Usage myObject.unwatch (prop:String) : Boolean Parameters prop A string; the name of the object property that should no longer be watched. Returns A Boolean value: true if the watchpoint is successfully removed, false otherwise. Description Method; removes a watchpoint that Object.watch() created.
Example The following example shows the return value of valueOf() for a generic object (which does not have a primitive value) and compares it to the return value of toString(): // Create a generic object var myObject:Object = new Object(); trace(myObject.valueOf()); // output: [object Object] trace(myObject.toString()); // output: [object Object] The following examples show the return values for the built-in classes Date and Array, and compares them to the return values of Object.
Description Method; registers an event handler to be invoked when a specified property of an ActionScript object changes. When the property changes, the event handler is invoked with myObject as the containing object. Your can use the return statement in your callback method definition to affect the value of the property you are watching. The value returned by your callback method is assigned to the watched object property.
var speedWatcher:Function = function(prop, oldVal, newVal, speedLimit) { // Check whether speed is above the limit if (newVal > speedLimit) { trace ("You are speeding."); } else { trace ("You are not speeding."); } // Return the value of newVal. return newVal; } // Use watch() to register the event handler, passing as parameters: // - the name of the property to watch: "speed" // - a reference to the callback function speedWatcher // - the speedLimit of 55 as the userData parameter myObject.
CHAPTER 6 ActionScript Core Classes 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 print() method, lets you render 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.
// display print dialog box, but only initiate the print job // if start returns successfully. if (my_pj.start()) { // use a variable to track successful calls to addPage var pagesToPrint:Number = 0; // add specified area to print job // repeat once for each page to be printed if (my_pj.addPage([params])) { pagesToPrint++; } if (my_pj.addPage([params])) { pagesToPrint++; } if (my_pj.
Parameters target A number or string; the level or instance name of the movie clip to print. Pass a number to specify a level (for example, 0 is the _root movie), or a string (in quotation marks [""]) to specify the instance name of a movie clip.
Returns A Boolean value: true if the page is successfully sent to the print spooler; false otherwise. Description Method; sends the specified level or movie clip as a single page to the print spooler. Before using this method, you must use PrintJob.start(); after calling PrintJob.addPage() one or more times for a print job, you must use PrintJob.send() to send the spooled pages to the printer. If this method returns false (for example, if you haven’t called PrintJob.
pageCount++; // Starting at 0,0, print an area 400 pixels wide and 500 pixels high // of frame 1 of the _root movie in bitmap format if (my_pj.addPage(0, {xMin:0,xMax:400,yMin:0,yMax:500}, {printAsBitmap:true}, 1)){ pageCount++; // // // if Starting 50 pixels to the right of 0,0 and 70 pixels down, print an area 500 pixels wide and 600 pixels high of frame 4 of level 5 in vector format (my_pj.
PrintJob.send() Availability Flash Player 7. Usage my_pj.send() : Void Parameters None. Returns Nothing. Description Method; used following PrintJob.start() and PrintJob.addPage() to send spooled pages to the printer. Because calls to PrintJob.send() will not be successful if related calls to PrintJob.start() and PrintJob.addpage() failed, you should check that calls to PrintJob.addpage() and PrintJob.start() were successful before calling PrintJob.send(): var my_pj:PrintJob = new PrintJob(); if (my_pj.
Description Method; displays the operating system’s print dialog boxes and starts spooling. The print dialog boxes let the user change print settings. When the PrintJob.start() method returns successfully, the following read-only properties are populated, representing the user’s print settings: Property Type Units Notes PrintJob.paperHeight Number Points Overall paper height. PrintJob.paperWidth Number Points Overall paper width. PrintJob.
// check the user's printer orientation setting // and add appropriate print area to print job if (my_pj.orientation == "portrait") { // Here, the printArea measurements are appropriate for an 8.5" x 11" // portrait page. pageAdded = my_pj.addPage(this,{xMin:0,xMax:600,yMin:0,yMax:800}); } else { // my_pj.orientation is "landscape". // Now, the printArea measurements are appropriate for an 11" x 8.5" // landscape page. pageAdded = my_pj.
SharedObject class CHAPTER 6 ActionScript Core Classes Availability Flash Player 6. Description Shared objects are powerful: They offer real-time data sharing between objects that are persistent on the user’s computer. You can consider local shared objects as cookies. You can use local shared objects to maintain local persistence. For example, you can call SharedObject.getLocal() to create a shared object, such as a calculator with memory, in the player.
• If the user selects None (moves the slider all the way to the left), all SharedObject.flush() commands issued for the object return "pending", and the player asks the user if additional disk space can be allotted to make room for the object. • If the user selects 10K, 100K, 1 MB, or 10 MB, objects are saved locally and SharedObject.flush() returns true if the object fits within the specified amount of space. If more space is needed, SharedObject.
Parameters None. Returns Nothing. Description Method; purges all the data from the shared object and deletes the shared object from the disk. The reference to my_so is still active, and my_so is now empty. Example The following example sets data in the shared object, and then empties all of the data from the shared object. var my_so:SharedObject = SharedObject.getLocal("superfoo"); my_so.data.name = "Hector"; trace("before my_so.clear():"); for (var prop in my_so.
var my_so:SharedObject = SharedObject.getLocal("superfoo"); my_so.data.itemNumbers = items_array; my_so.data.adminPrivileges = currentUserIsAdmin; my_so.data.userName = currentUserName; for (var prop in my_so.data) { trace(prop+": "+my_so.
SharedObject.flush() Availability Flash Player 6. Usage myLocalSharedObject.flush([minimumDiskSpace:Number]) : Boolean Parameters An optional integer specifying the number of bytes that must be allotted for this object. The default value is 0.
Example The following function gets a shared object, my_so, and fills writable properties with userprovided settings. Finally, flush() is called to save the settings and allot a minimum of 1000 bytes of disk space. this.syncSettingsCore = function(soName:String, override:Boolean, settings:Object) { var my_so:SharedObject = SharedObject.getLocal(soName, "http:// www.mydomain.
Description Method; returns a reference to a locally persistent shared object that is available only to the current client. Note: If the user has selected to never allow local storage for this domain, the object is not saved locally, even if a value for localPath is specified. For more information, see “Local disk space considerations” on page 398. To avoid name collisions, Flash looks at the location of the SWF file that is creating the shared object. For example, if a SWF file at www.myCompany.
textListener.enter = function(eventObj:Object) { my_so.data.myTextSaved = eventObj.target.text; my_so.flush(); }; // register listener with TextInput component instance myText_ti.addEventListener("enter", textListener); SharedObject.getSize() Availability Flash Player 6. Usage myLocalSharedObject.getSize() : Number 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.
SharedObject.onStatus Availability Flash Player 6. Usage myLocalSharedObject.onStatus = function(infoObject:Object) { // your statements here } Parameters infoObject A parameter defined according to the status message. Returns Nothing. Description Event handler; invoked every time an error, warning, or informational note is posted for a shared object. If you want to respond to this event handler, you must create a function to process the information object generated by the shared object.
this.createTextField("status_txt", this.getNextHighestDepth(), 10, 30, 300, 100); status_txt.multiline = true; status_txt.html = true; var items_array:Array = new Array(101, 346, 483); var currentUserIsAdmin:Boolean = true; var currentUserName:String = "Ramona"; var my_so:SharedObject = SharedObject.getLocal("superfoo"); my_so.data.itemNumbers = items_array; my_so.data.adminPrivileges = currentUserIsAdmin; my_so.data.userName = currentUserName; my_so.onStatus = function(infoObject:Object) { status_txt.
CHAPTER 6 ActionScript Core Classes 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 String() function.
Method Description String.substring() Returns the characters between two indexes in a string. String.toLowerCase() Converts the string to lowercase and returns the result; does not change the contents of the original object. String.toUpperCase() Converts the string to uppercase and returns the result; does not change the contents of the original object. Property summary for the String class Property Description String.
Parameters A number; an integer specifying the position of a character in the string. The first character is indicated by 0, and the last character is indicated by my_str.length-1. index Returns A character. Description Method; returns the character in the position specified by the parameter index. If index is not a number from 0 to string.length - 1, an empty string is returned. This method is similar to String.
Example In the following example, this method is called on the first letter of the string "Chris": var my_str:String = "Chris"; var firstChar_num:Number = my_str.charCodeAt(0); trace(firstChar_num); // output: 67 See also String.charAt() String.concat() Availability Flash Player 5. Usage my_str.concat(value1,...valueN) : String Parameters value1,...valueN Zero or more values to be concatenated. Returns A string.
Description Method; returns a string comprising the characters represented by the ASCII values in the parameters. Example The following example uses fromCharCode() to insert an @ character in the e-mail address: var address_str:String = "dog"+String.fromCharCode(64)+"house.net"; trace(address_str); // output: dog@house.net String.indexOf() Availability Flash Player 5. Usage my_str.
index = searchString.indexOf("i", 7); trace(index); // output: 19 index = searchString.indexOf("z"); trace(index); // output: -1 See also String.lastIndexOf() String.lastIndexOf() Availability Flash Player 5. Usage my_str.lastIndexOf(substring:String, [startIndex:Number]) : Number Parameters substring startIndex String; the string for which to search. Number; an optional integer specifying the starting point from which to search for substring.
index = searchString.lastIndexOf("i", 18); trace(index); // output: 6 index = searchString.lastIndexOf("z"); trace(index); // output: -1 See also String.indexOf() String.length Availability Flash Player 5. Usage my_str.length:Number Description Property; an 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 is x.length - 1.
String.slice() Availability Flash Player 5. Usage my_str.slice(start:Number, [end:Number]) : String Parameters A number; the zero-based index of the starting point for the slice. If start is a negative number, the starting point is determined from the end of the string, where -1 is the last character. start end A number; an integer that is 1+ the index of the ending point for the slice. The character indexed by the end parameter is not included in the extracted string.
// slices that omit the end parameter use String.length, which equals 5 trace("slice(0): "+my_str.slice(0)); // slice(0): Lorem trace("slice(3): "+my_str.slice(3)); // slice(3): em See also String.substr(), String.substring() String.split() Availability Flash Player 5. Usage my_str.split("delimiter":String, [limit:Number]) : Array Parameters delimiter limit A string; the character or string at which my_str splits. A number; the number of items to place into the array. This parameter is optional.
The following example shows that if you use an empty string ("") for the delimiter parameter, each character in the string is placed as an element in the array: var my_str:String = new String("Joe"); var my_array:Array = my_str.split(""); for (var i = 0; i
String.substring() Availability Flash Player 5. Usage my_str.substring(start:Number, [end:Number]) : String Parameters A number; an integer that indicates the position of the first character of my_str used to create the substring. Valid values for start are 0 through String.length - 1. If start is a negative value, 0 is used. start A number; an integer that is 1+ the index of the last character in my_str to be extracted. Valid values for end are 1 through String.length.
String.toLowerCase() Availability Flash Player 5. Usage my_str.toLowerCase() : String Parameters None. Returns A string. Description Method; returns a copy of the String object, with all uppercase characters converted to lowercase. The original value is unchanged.
Example The following example creates a string with all lowercase characters and then creates a copy of that string using toUpperCase(): var lowerCase:String = "lorem ipsum dolor"; var upperCase:String = lowerCase.toUpperCase(); trace("lowerCase: " + lowerCase); // output: lowerCase: lorem ipsum dolor trace("upperCase: " + upperCase); // output: upperCase: LOREM IPSUM DOLOR See also String.
CHAPTER 6 ActionScript Core Classes 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 in the following table. Method summary for the System class Method Description System.setClipboard() Replaces the contents of the system Clipboard with a text string. System.
If this value is true, the settings and data for a SWF file hosted at here.xyz.com are stored in a directory called here.xyz.com, the settings and data for a SWF file hosted at there.xyz.com are stored in a directory called there.xyz.com, and so on. If this value is false, the settings and data for SWF files hosted at here.xyz.com, there.xyz.com, and xyz.com are shared, and are all stored in a directory called xyz.com.
In addition to these specific onStatus methods, Flash also provides a super function called System.onStatus, which serves as a secondary error message handler. If an instance of the LocalConnection, NetStream, or SharedObject class passes an information object with a level property of “error”, but you have not defined an onStatus function for that particular instance, then Flash uses the function you define for System.onStatus instead.
Description Method; replaces the contents of the Clipboard with a specified text string. Note: Because of security concerns, it is not possible to read the contents of the system Clipboard. In other words, there is no corresponding System.getClipboard() method. Example The following example places the phrase "Hello World" onto the system Clipboard: System.setClipboard("Hello world"); The following example creates two text fields at runtime, called in_txt and out_txt.
Returns Nothing. Description Method; shows the specified Flash Player Settings panel, which lets users do any of the following actions: • • • • Allow or deny access to the camera and microphone Specify the local disk space available for shared objects Select a default camera and microphone Specify microphone gain and echo suppression settings For example, if your application requires the use of a camera, you can tell the user to select Allow in the Privacy Settings panel and then issue a System.
If you load external text files that are not Unicode-encoded, you should set System.useCodepage to true. Add the following code as the first line of code in the SWF file that is loading the data: System.useCodepage = true; When this code is present, Flash Player interprets external text using the traditional code page of the operating system running Flash Player. This is generally CP1252 for an English Windows operating system and Shift-JIS for a Japanese operating system. If you set System.
System.capabilities object CHAPTER 6 ActionScript Core Classes Availability Flash Player 6. Description You can use the System.capabilities object to determine the abilities of the system and player hosting a SWF file, which lets you tailor content for different formats. For example, the screen of a cell phone (black and white, 100 square pixels) is different than the 1000-square-pixel color PC screen. To provide appropriate content to as many users as possible, you can use the System.
Property Description Server string System.capabilities.hasScreenBroadcast Indicates whether the player supports the development of screen broadcast applications to be run through the Flash Communication Server. SB System.capabilities.hasScreenPlayback Indicates whether the player supports the playback of screen broadcast applications that are being run through the Flash Communication Server. SP System.capabilities.hasStreamingAudio Indicates whether the player can play streaming audio.
System.capabilities.avHardwareDisable Availability Flash Player 7. Usage System.capabilities.avHardwareDisable:Boolean Description Read-only property; a Boolean value that specifies whether access to the user’s camera and microphone has been administratively prohibited (true) or allowed (false). The server string is AVD. Example The following example traces the value of this read-only property: trace(System.capabilities.avHardwareDisable); See also Camera.get(), Microphone.get(), System.
Description Read-only property: a Boolean value that is true if the player is running on a system that has audio capabilities; false otherwise. The server string is A. Example The following example traces the value of this read-only property: trace(System.capabilities.hasAudio); System.capabilities.hasAudioEncoder Availability Flash Player 6. Usage System.capabilities.
System.capabilities.hasMP3 Availability Flash Player 6. Usage System.capabilities.hasMP3:Boolean Description Read-only property: a Boolean value that is true if the player is running on a system that has an MP3 decoder; false otherwise. The server string is MP3. Example The following example traces the value of this read-only property: trace(System.capabilities.hasMP3); System.capabilities.hasPrinting Availability Flash Player 6 r65. Usage System.capabilities.
Example The following example traces the value of this read-only property: trace(System.capabilities.hasScreenBroadcast); System.capabilities.hasScreenPlayback Availability Flash Player 6 r79. Usage System.capabilities.hasScreenPlayback:Boolean Description Read-only property: a Boolean value that is true if the player supports the playback of screen broadcast applications that are being run through the Flash Communication Server; false otherwise. The server string is SP.
Description Read-only property: a Boolean value that is true if the player can play streaming video; false otherwise. The server string is SV. Example The following example traces the value of this read-only property: trace(System.capabilities.hasStreamingVideo); System.capabilities.hasVideoEncoder Availability Flash Player 6. Usage System.capabilities.
System.capabilities.language Availability Flash Player 6. Behavior changed in Flash Player 7. Usage System.capabilities.language:String Description Read-only property; indicates the language of the system on which the player is running. This property is specified as a lowercase two-letter language code from ISO 639-1. For Chinese, an additional uppercase two-letter country code subtag from ISO 3166 distinguishes between Simplified and Traditional Chinese.
Language Tag Russian ru Simplified Chinese zh-CN Spanish es Swedish sv Traditional Chinese zh-TW Turkish tr Example The following example traces the value of this read-only property: trace(System.capabilities.language); System.capabilities.localFileReadDisable Availability Flash Player 7. Usage System.capabilities.
Description Read-only property; a string that indicates the manufacturer of Flash Player, in the format "Macromedia OSName" (OSName could be "Windows", "Macintosh", "Linux", or "Other OS Name"). The server string is M. Example The following example traces the value of this read-only property: trace(System.capabilities.manufacturer); System.capabilities.os Availability Flash Player 6. Usage System.capabilities.
System.capabilities.playerType Availability Flash Player 7. Usage System.capabilities.playerType;String Description Read-only property; a string that indicates the type of player.
Description Read-only property; a number that indicates the dots-per-inch (dpi) resolution of the screen, in pixels. The server string is DP. Example The following example traces the value of this read-only property: trace(System.capabilities.screenDPI); System.capabilities.screenResolutionX Availability Flash Player 6. Usage System.capabilities.screenResolutionX:Number Description Read-only property; an integer that indicates the maximum horizontal resolution of the screen.
System.capabilities.serverString Availability Flash Player 6. Usage System.capabilities.serverString:String Description Read-only property; a URL-encoded string that specifies values for each System.capabilities property, as shown in the following 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 19%2C0&M=Macromedia%20Windows&R=1600x1200&DP=72&COL=color&AR=1.
CHAPTER 6 ActionScript Core Classes System.security object Availability Flash Player 6. Description This object contains methods that specify how SWF files in different domains can communicate with each other. Method summary for the System.security object Method Description System.security.allowDomain() Lets SWF files in the identified domains access objects and variables in the calling SWF file or in any other SWF file from the same domain as the calling SWF file. System.security.
// Corresponding commands to allow access by SWF files // that are running in Flash Player 7 or later System.security.allowDomain("www.domain.com", "store.domain.com"); Also, for files running in Flash Player 7 or later, you can’t use this method to let SWF files hosted using a secure protocol (HTTPS) allow access from SWF files hosted in nonsecure protocols; you must use System.security.allowInsecureDomain() instead.
Returns Nothing. Description Method; lets SWF files and HTML files in the identified domains access objects and variables in the calling SWF file, which is hosted using the HTTPS protocol. It also lets the SWF files in the identified domains access any other SWF files in the same domain as the calling SWF file. By default, SWF files hosted using the HTTPS protocol can be accessed only by other SWF files hosted using the HTTPS protocol.
Parameters url A string; the URL where the cross-domain policy file to be loaded is located. Returns Nothing. Description Method; loads a cross-domain policy file from a location specified by the url parameter. Flash Player uses policy files as a permission mechanism to permit Flash movies to load data from servers other than their own. Flash Player 7.0.14.0 looked for policy files in only one location: /crossdomain.xml on the server to which a data-loading request was being made.
A policy file served by an XMLSocket server has the same syntax as any other policy file, except that it must also specify the ports to which access is granted. When a policy file comes from a port lower than 1024, it can grant access to any ports; when a policy file comes from port 1024 or higher, it can grant access only to other ports 1024 and higher. The allowed ports are specified in a "to-ports" attribute in the tag. Single port numbers, port ranges, and wildcards are all allowed.
CHAPTER 6 ActionScript Core Classes XML class Availability Flash Player 5 (became a native object in Flash Player 6, which improved performance significantly). Description Use the methods and properties of the XML class to load, parse, send, build, and manipulate XML document trees. You must use the constructor new XML() to create an XML object before calling any method of the XML class. An XML document is represented in Flash by the XML class.
Property summary for the XML class Property Description XML.contentType The MIME type transmitted to the server. XML.docTypeDecl Sets and returns information about an XML document’s DOCTYPE declaration. XML.firstChild Read-only; references the first child in the list for the specified node. XML.ignoreWhite When set to true, discards, during the parsing process, text nodes that contain only white space. XML.lastChild Read-only; references the last child in the list for the specified node. XML.
Constructor for the XML class Availability Flash Player 5. Usage new XML([source:String]) : XML Parameters source A string; the XML text parsed to create the new XML object. Returns A reference to an XML object. Description Constructor; creates a new XML object. You must use the constructor to create an XML object before you call any of the methods of the XML class. Note: Use the createElement() and createTextNode() methods to add elements and text nodes to an XML document tree.
Returns Nothing. Description Method; adds or changes HTTP request headers (such as Content-Type or SOAPAction) sent with POST actions. In the first usage, you pass two strings to the method: headerName and headerValue. In the second usage, you pass an array of strings, alternating header names and header values. If multiple calls are made to set the same header name, each successive value replaces the value set in the previous call.
Description Method; appends the specified node to the XML object’s child list. This method operates directly on the node referenced by the childNode parameter; it does not append a copy of the node. If the node to be appended already exists in another tree structure, appending the node to the new location will remove it from its current location.
XML.attributes Availability Flash Player 5. Usage my_xml.attributes:Array Description Property; an associative array that contains all the attributes of the specified XML object. Associative arrays use keys as indexes, instead of the simple ordinal integer indexes used by regular arrays. In the XML.attributes associative array, the key index is a string representing the name of the attribute. The value associated with that key index is the string value associated with that attribute.
Description Read-only property; 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. Use the XML.appendChild(), XML.insertBefore(), and XML.removeNode() methods to manipulate child nodes. This property is undefined for text nodes (nodeType == 3). Example The following example shows how to use the XML.
Parameters deep A Boolean value; if set to true, the children of the specified XML object will be recursively cloned. Returns An XMLNode object. Description Method; constructs and returns a new XML node of the same type, name, value, and attributes as the specified XML object. If deep is set to true, all child nodes are recursively cloned, resulting in an exact copy of the original object’s document tree. The clone of the node that is returned is no longer associated with the tree of the cloned item.
// // create a copy of rootNode using cloneNode() to demonstrate a deep copy var rootClone:XMLNode = rootNode.cloneNode(true); // insert the clone, which contains all child nodes, rootNode.appendChild(rootClone); trace(rootNode); // output (with line breaks added): // // // // // // // // // // // // to rootNode XML.contentType Availability Flash Player 6.
XML.createElement() Availability Flash Player 5. Usage my_xml.createElement(name:String) : XMLNode Parameters name The tag name of the XML element being created. Returns An XMLNode; an XML element. Description Method; creates a new XML element with the name specified in the parameter. The new element initially has no parent, no children, and no siblings. The method returns a reference to the newly created XML object that represents the element. This method and the XML.
Parameters text A string; the text used to create the new text node. Returns An XMLNode. 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 that represents the new text node. This method and the XML.createElement() method are the constructor methods for creating nodes for an XML object.
XML.docTypeDecl Availability Flash Player 5. Usage my_xml.docTypeDecl:String Description Property; specifies information about the XML document’s DOCTYPE declaration. After the XML text has been parsed into an XML object, the XML.docTypeDecl property of the XML object is set to the text of the XML document’s DOCTYPE declaration (for example, ). This property is set using a string representation of the DOCTYPE declaration, not an XML node object.
Example The following example shows how to use XML.firstChild to loop through a node’s child nodes: // create a new XML document var doc:XML = new XML(); // create a root node var rootNode:XMLNode = doc.createElement("rootNode"); // create three child nodes var oldest:XMLNode = doc.createElement("oldest"); var middle:XMLNode = doc.createElement("middle"); var youngest:XMLNode = doc.createElement("youngest"); // add the rootNode as the root of the XML document tree doc.
Description Method; returns the number of bytes loaded (streamed) for the XML document. You can compare the value of getBytesLoaded() with the value of getBytesTotal() to determine what percentage of an XML document has loaded. Example The following example shows how to use the XML.getBytesLoaded() method with the XML.getBytesTotal() method to trace the progress of an XML.load() command. You must replace the URL parameter of the XML.
Description Method; returns the size, in bytes, of the XML document. Example See example for XML.getBytesLoaded(). See also XML.getBytesLoaded() XML.hasChildNodes() Availability Flash Player 5. Usage my_xml.hasChildNodes() : Boolean Parameters None. Returns A Boolean value. Description Method; returns true if the specified XML object has child nodes; otherwise, returns false. Example The following example creates a new XML packet.
XML.ignoreWhite Availability Flash Player 5. Usage my_xml.ignoreWhite:boolean XML.prototype.ignoreWhite:boolean Parameters boolean A Boolean (true or false) value. Description Property; default setting is false. When set to true, text nodes that contain only white space are discarded during the parsing process. Text nodes with leading or trailing white space are unaffected. Usage 1: You can set the ignoreWhite property for individual XML objects, as the following code shows: my_xml.
/* output (line breaks added for clarity): ceramic tile linoleum */ If you then change the setting of flooring.ignoreWhite to false, or simply remove that line of code entirely, the fourteen space characters in the foyer tag will be preserved: ... // set the ignoreWhite property to false (default value) flooring.ignoreWhite = false; ...
See also XMLNode class XML.lastChild Availability Flash Player 5. Usage my_xml.lastChild:XMLNode Description Read-only property; an XMLNode value that references the last child in the node’s child list. The XML.lastChild property is null if the node does not have children. This property cannot be used to manipulate child nodes; use the appendChild(), insertBefore(), and removeNode() methods to manipulate child nodes. Example The following example uses the XML.
*/ The following example creates a new XML packet and uses the XML.lastChild property to iterate through the child nodes of the root node: // create a new XML document var doc:XML = new XML(""); var rootNode:XMLNode = doc.firstChild; // use lastChild to iterate through the child nodes of rootNode for (var aNode:XMLNode = rootNode.lastChild; aNode != null; aNode=aNode.
The value you pass for the url parameter must be in exactly the same domain. For example, a SWF file at www.someDomain.com can load data only from sources that are also at www.someDomain.com. If you want to load data from a different domain, you can place a crossdomain policy file on the server that is hosting the SWF file. For more information, see “Applying Flex Security” in Developing Flex Applications. When the load() method is executed, the XML object property loaded is set to false.
Example The following example uses the XML.loaded property in a simple script: var my_xml:XML = new XML(); my_xml.ignoreWhite = true; my_xml.onLoad = function(success:Boolean) { trace("success: "+success); trace("loaded: "+my_xml.loaded); trace("status: "+my_xml.status); }; my_xml.load("http://www.flash-mx.com/mm/problems/products.xml"); Information writes to the log file when the onLoad handler invokes. If the call completes successfully, true writes to the log file for the loaded status.
XML.nodeName Availability Flash Player 5. Usage my_xml.nodeName:String Description Property; a string representing the node name of the XML object. If the XML object is an XML element (nodeType == 1), nodeName is the name of the tag that represents the node in the XML file. For example, TITLE is the nodeName of an HTML TITLE tag. If the XML object is a text node (nodeType == 3), nodeName is null.
trace(aNode.nodeName+":\t"+aNode.firstChild.nodeValue); } } } The following node names write to the log file: output: username:hank password:rudolph See also XML.nodeType XML.nodeType Availability Flash Player 5. Usage my_xml.nodeType:Number Description Read-only property; a nodeType value, either 1 for an XML element or 3 for a text node. The nodeType is a numeric value from the NodeType enumeration in the W3C DOM Level 1 recommendation: www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core.html.
Example The following example creates an element node and a text node, and checks the node type of each: // create an XML document var doc:XML = new XML(); // create an XML node using createElement() var myNode:XMLNode = doc.createElement("rootNode"); // place the new node into the XML tree doc.appendChild(myNode); // create an XML text node using createTextNode() var myTextNode:XMLNode = doc.createTextNode("textNode"); // place the new node into the XML tree myNode.appendChild(myTextNode); trace(myNode.
var myNode:XMLNode = doc.createElement("rootNode"); // place the new node into the XML tree doc.appendChild(myNode); // create an XML text node using createTextNode() var myTextNode:XMLNode = doc.createTextNode("myTextNode"); // place the new node into the XML tree myNode.appendChild(myTextNode); trace(myNode.nodeValue); trace(myTextNode.nodeValue); /* output: null myTextNode */ The following example creates and parses an XML packet.
XML.onData Availability Flash Player 5. Usage my_xml.onData = function(src:String) { // your statements here } Parameters src A string or undefined; 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.
Parameters success A Boolean value that evaluates to true if the XML object is successfully loaded with a or XML.sendAndLoad() operation; otherwise, it is false. XML.load() 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 success parameter is true. If the document was not received, or if an error occurred in receiving the response from the server, the success parameter is false.
Description Read-only property; an XMLNode value that references the parent node of the specified XML object, or returns null if the node has no parent. This is a read-only property and cannot be used to manipulate child nodes; use the appendChild(), insertBefore(), and removeNode() methods to manipulate child nodes.
Description Method; parses the XML text specified in the source parameter, and populates the specified XML object with the resulting XML tree. Any existing trees in the XML object are discarded. Example The following example creates and parses an XML packet: var xml_str:String = " San Francisco" // defining the XML source within the XML constructor: var my1_xml:XML = new XML(xml_str); trace(my1_xml.firstChild.attributes.
XML.removeNode() Availability Flash Player 5. Usage my_xml.removeNode() : Void Parameters None. Returns Nothing. Description Method; removes the specified XML object from its parent. Also deletes all descendants of the node. Example The following example creates an XML packet, and then deletes the specified XML object and its descendant nodes: var xml_str:String = " San Francisco"; var my_xml:XML = new XML(xml_str); var cityNode:XMLNode = my_xml.
Parameters url String; the destination URL for the specified XML object. window String; the browser window to show data that the server returns: • • • • specifies the current frame in the current window. _self _blank specifies a new window. _parent _top specifies the parent of the current frame. specifies the top-level frame in the current window. This parameter is optional; if you do not specify a window parameter, it is the same as specifying _self. Returns Nothing.
Returns Nothing. Description Method; encodes the specified XML object into an XML document, sends it to the specified URL using the POST method, downloads the server’s response, and loads it into the targetXMLobject specified in the parameters. The server response loads in the same manner used by the XML.load() method. The value you pass for the url parameter must be in exactly the same domain. For example, a SWF file at www.someDomain.com can load data only from sources that are also at www.someDomain.
XML.status Availability Flash Player 5. Usage my_xml.status:Number Description Property; automatically sets and returns a numeric value that indicates whether an XML document was successfully parsed into an XML object. The following are the numeric status codes, with descriptions: • • • • • • • • • • 0 No error; parse was completed successfully. -2 A CDATA section was not properly terminated. -3 The XML declaration was not properly terminated. -4 The DOCTYPE declaration was not properly terminated.
case -4 : errorMessage = "The DOCTYPE declaration was not properly terminated."; break; case -5 : errorMessage = "A comment was not properly terminated."; break; case -6 : errorMessage = "An XML element was malformed."; break; case -7 : errorMessage = "Out of memory."; break; case -8 : errorMessage = "An attribute value was not properly terminated."; break; case -9 : errorMessage = "A start-tag was not matched with an end-tag.
For top-level XML objects (those created with the constructor), the XML.toString() method outputs the document’s XML declaration (stored in the XML.xmlDecl property), followed by the document’s DOCTYPE declaration (stored in the XML.docTypeDecl property), followed by the text representation of all XML nodes in the object. The XML declaration is not output if the XML.xmlDecl property is undefined. The DOCTYPE declaration is not output if the XML.docTypeDecl property is undefined.
var my_xml:XML = new XML(); my_xml.ignoreWhite = true; my_xml.onLoad = function(success:Boolean) { var endTime:Number = getTimer(); var elapsedTime:Number = endTime-startTime; if (success) { my_txt.text = "xmlDecl:"+newline+my_xml.xmlDecl+newline+newline; my_txt.text += "contentType:"+newline+my_xml.contentType+newline+newline; my_txt.text += "docTypeDecl:"+newline+my_xml.docTypeDecl+newline+newline; my_txt.text += "packet:"+newline+my_xml.toString()+newline+newline; } else { my_txt.
CHAPTER 6 ActionScript Core Classes XMLNode class Availability Flash Player 5. Description An XML document is represented in Flash by the XML class. Each element of the hierarchical document is represented by an XMLNode object. 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.
XMLSocket class CHAPTER 6 ActionScript Core Classes Availability Flash Player 5. Description The XMLSocket class implements client sockets that let the computer running Flash Player 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. A traditional HTTP-based chat solution frequently polls the server and downloads new messages using an HTTP request.
Method summary for the XMLSocket class Method Description XMLSocket.close() Closes an open socket connection. XMLSocket.connect() Establishes a connection to the specified server. XMLSocket.send() Sends an XML object to the server. Event handler summary for the XMLSocket class Event handler Description XMLSocket.onClose Invoked when an XMLSocket connection is closed. XMLSocket.onConnect Invoked by Flash Player when a connection request initiated through XMLSocket.
Parameters None. Returns Nothing. Description Method; closes the connection specified by XMLSocket object. Example The following simple example creates an XMLSocket object, attempts to connect to the server, and then closes the connection. var socket:XMLSocket = new XMLSocket(); socket.connect(null, 2000); socket.close(); See also XMLSocket.connect() XMLSocket.connect() Availability Flash Player 5; behavior changed in Flash Player 7. Usage myXMLSocket.
If you specify null for the host parameter, the host contacted is the one where the SWF file calling XMLSocket.connect() resides. For example, if the SWF file was downloaded from www.yoursite.com, specifying null for the host parameter is the same as entering the IP address for www.yoursite.com. In SWF files running in a version of the player earlier than Flash Player 7, host must be in the same superdomain as the SWF file that is issuing this call. For example, a SWF file at www.someDomain.
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 custom actions.
Description Event handler; invoked by Flash Player when a connection request initiated through XMLSocket.connect() has succeeded or failed. If the connection succeeded, the success parameter is true; otherwise the success parameter is false. The default implementation of this method performs no actions. To override the default implementation, you must assign a function containing custom actions. See also function, XMLSocket.connect() XMLSocket.onData Availability Flash Player 5. Usage XMLSocket.
XMLSocket.onXML Availability Flash Player 5. Usage myXMLSocket.onXML = function(object:XML) { // your statements here } Parameter object An XML object that contains a parsed XML document received from a server. Returns Nothing. Description Event handler; invoked by Flash Player when the specified XML object containing an XML document arrives over an open XMLSocket connection. An XMLSocket connection can be used to transfer an unlimited number of XML documents between the client and the server.
XMLSocket.send() Availability Flash Player 5. Usage myXMLSocket.send(object:XML) : Void Parameters object An XML object or other data to transmit to the server. Returns Nothing. Description Method; converts the XML object or data specified in the object parameter to a string and transmits it to the server, followed by a zero (0) byte. If object is an XML object, the string is the XML textual representation of the XML object.
CHAPTER 7 ActionScript for Flash This chapter describes functions, properties, and classes of Macromedia Flash Player that you can use in a Macromedia Flex application. However, many items described in this chapter are not for use in typical Flex applications and should be used only as necessary. For more information on the items that Macromedia recommends that you use in a Flex application, see Flex ActionScript and MXML API Reference.
CHAPTER 7 ActionScript for Flash asfunction Availability Flash Player 5. Usage asfunction:function:Function,"parameter":String Parameters function parameter An identifier for a function. A string that is passed to the function named in the function parameter. Returns Nothing. Description Protocol; a special protocol for URLs in HTML text fields. In HTML text fields, text can be linked using the HTML A tag.
CHAPTER 7 ActionScript for Flash Camera class Availability Flash Player 6. Description The Camera class is primarily for use with Macromedia Flash Communication Server, but can be used in a limited way without the server. The Camera class lets you capture video from a video camera attached to the computer that is running Macromedia Flash Player—for example, to monitor a video feed from a web camera attached to your local system.
Property (read-only) Description Camera.motionLevel The amount of motion required to invoke Camera.onActivity(true). Camera.motionTimeOut The number of milliseconds between the time when the camera stops detecting motion and the time Camera.onActivity(false) is invoked. Camera.muted A Boolean value that specifies whether the user has allowed or denied access to the camera. Camera.name The name of the camera as specified by the camera hardware. Camera.
Example The following example detects the amount of motion the camera detects using the activityLevel property: // video instance on the Stage. var my_video:Video; var activity_pb:mx.controls.ProgressBar; var my_cam:Camera = Camera.get(); my_video.attachVideo(my_cam); activity_pb.mode = "manual"; activity_pb.label = "Activity %3%%"; this.onEnterFrame = function() { activity_pb.setProgress(my_cam.activityLevel, 100); }; my_cam.
// bandwidth_nstep.minimum = 0; bandwidth_nstep.maximum = 128; bandwidth_nstep.stepSize = 16; bandwidth_nstep.value = my_cam.bandwidth/1024; function changeBandwidth(evt:Object) { my_cam.setQuality(evt.target.value*1024, 0); } bandwidth_nstep.addEventListener("change", changeBandwidth); See also Camera.setQuality() Camera.currentFps Availability Flash Player 6. Usage active_cam.currentFps:Number Description Read-only property; the rate at which the camera is capturing data, in frames per second.
Camera.fps Availability Flash Player 6. Usage active_cam.fps:Number 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. • To set a desired value for this property, use Camera.setMode(). • To determine the rate at which the camera is currently capturing data, use the Camera.
Parameters An optional zero-based integer that specifies which camera to get, as determined from the array returned by the Camera.names property. To get the default camera (which is recommended for most applications), omit this parameter. index Returns • If index is not specified, this method returns a reference to the default camera or, if it is in use by another application, to the first available camera.
If Camera.get returns null, either the camera is in use by another application, or there are no cameras installed on the system. To determine whether any cameras are installed, use Camera.names.length. To display the Flash Player Camera Settings panel, which lets the user choose the camera to be referenced by Camera.get(), use System.showSettings(3). Scanning the hardware for cameras takes time. When Flash finds at least one camera, the hardware is not scanned again for the lifetime of the player instance.
var my_cam:Camera = Camera.get(); var my_video:Video; my_video.attachVideo(my_cam); var dimensions_lbl:mx.controls.Label; dimensions_lbl.setStyle("fontSize", 9); dimensions_lbl.setStyle("fontWeight", "bold"); dimensions_lbl.setStyle("textAlign", "center"); dimensions_lbl.text = "width: "+my_cam.width+", height: "+my_cam.height+", FPS: "+my_cam.fps; See also the example for Camera.setMode(). See also Camera.setMode(), Camera.width Camera.index Availability Flash Player 6. Usage active_cam.
See also Camera.get(), Camera.names Camera.motionLevel Availability Flash Player 6. Usage active_cam.motionLevel:Number Description Read-only property; a numeric value that specifies the amount of motion required to invoke Camera.onActivity(true). Acceptable values range from 0 to 100. The default value is 50. Video can be displayed regardless of the value of the motionLevel property. For more information, see Camera.setMotionLevel().
/* If isActive equals true, set the themeColor variable to "haloGreen". Otherwise set the themeColor to "haloOrange". */ var themeColor:String = (isActive) ? "haloGreen" : "haloOrange"; motion_pb.setStyle("themeColor", themeColor); }; function changeMotionLevel() { /* Set the motionLevel property for my_cam Camera instance to the value of the NumericStepper component instance. Maintain the current motionTimeOut value of the my_cam Camera instance. */ my_cam.setMotionLevel(motionLevel_nstep.value, my_cam.
motion_pb.label = "Motion is above "+my_cam.motionLevel; } else { motion_pb.setStyle("themeColor", "haloOrange"); motion_pb.label = "Motion is below "+my_cam.motionLevel; } }; function changeMotionTimeOut() { my_cam.setMotionLevel(my_cam.motionLevel, motionTimeOut_nstep.value*1000); } motionTimeOut_nstep.addEventListener("change", changeMotionTimeOut); motionTimeOut_nstep.value = my_cam.motionTimeOut/1000; See also Camera.onActivity, Camera.setMotionLevel() Camera.muted Availability Flash Player 6.
Camera.name Availability Flash Player 6. Usage active_cam.name:String Description Read-only property; a string that specifies the name of the current camera, as returned by the camera hardware. Example The following example writes the name of the default camera to the log file. In Windows, this name is the same as the device name listed in the Scanners and Cameras Control Panel. var my_cam:Camera = Camera.get(); var my_video:Video; my_video.attachVideo(my_cam); this.createTextField("name_txt", this.
Example The following example uses the default camera unless more than one camera is available, in which case the user can choose which camera to set as the default camera. If only one camera is present, then the default camera is used. var my_video:Video; var cam_array:Array = Camera.names; if (cam_array.length>1) { System.showSettings(3); } var my_cam:Camera = Camera.get(); my_video.attachVideo(my_cam); See also Camera.get(), Camera.index, Camera.name Camera.onActivity Availability Flash Player 6.
trace(mode); } See also Camera.onActivity, Camera.setMotionLevel() Camera.onStatus Availability Flash Player 6. Usage active_cam.onStatus = function(infoObject:Object) : Void { // your statements here } Parameters infoObject A parameter defined according to the status message. Returns Nothing. Description Event handler; invoked when the user allows or denies access to the camera.
switch (infoObj.code) { case 'Camera.Muted' : trace("Camera access is denied"); break; case 'Camera.Unmuted' : trace("Camera access granted"); break; } }; See also Camera.get(), Camera.muted, System.showSettings(); System.onStatus Camera.quality Availability Flash Player 6. Usage active_cam.quality:Number Description Read-only property; an integer specifying the required level of picture quality, as determined by the amount of compression being applied to each video frame.
Camera.setMode() Availability Flash Player 6. Usage active_cam.setMode(width:Number, height:Number, fps:Number [,favorSize:Boolean]) : Void Parameters width The requested capture width, in pixels. The default value is 160. height The requested capture height, in pixels. The default value is 120. fps The requested rate at which the camera should capture data, in frames per second. The default value is 15.
var my_video:Video; my_video.attachVideo(my_cam); fps_ti.maxChars = 2; fps_ti.restrict = [0-9]; fps_lbl.text = "Current: "+my_cam.fps+" fps"; function changeFps():Void { my_cam.setMode(my_cam.width, my_cam.height, fps_ti.text); fps_lbl.text = "Current: "+my_cam.fps+" fps"; fps_ti.text = my_cam.fps; Selection.setSelection(0,2); } fps_ti.addEventListener("enter", changeFps); See also Camera.currentFps, Camera.fps, Camera.height, Camera.width Camera.setMotionLevel() Availability Flash Player 6.
• To determine the amount of motion the camera is currently detecting, use the Camera.activityLevel property. Motion sensitivity values correspond directly to activity values. Complete lack of motion is an activity value of 0. Constant motion is an activity value of 100. Your activity value is less than your motion sensitivity value when you’re not moving; when you are moving, activity values frequently exceed your motion sensitivity value. This method is similar in purpose to Microphone.
Parameters bandwidth An integer that specifies the maximum amount of bandwidth that the current outgoing video feed can use, in bytes per second. To specify that Flash video can use as much bandwidth as needed to maintain the value of frameQuality, pass 0 for bandwidth. The default value is 16384. An integer that specifies the required level of picture quality, as determined by the amount of compression being applied to each video frame.
See also Camera.bandwidth, Camera.get(), Camera.quality Camera.width Availability Flash Player 6. Usage active_cam.width:Number Description Read-only property; the current capture width, in pixels. To set a desired value for this property, use Camera.setMode(). Example The following code displays the current width, height and FPS of a video instance in a Label component instance on the Stage. var my_cam:Camera = Camera.get(); var my_video:Video; my_video.attachVideo(my_cam); var dimensions_lbl:mx.
CHAPTER 7 ActionScript for Flash Color class Availability Flash Player 5. Description The Color class lets you set the RGB color value and color transform of movie clips and retrieve those values once they have been set. You must use the constructor new Color() to create a Color object before calling its methods. Method summary for the Color class Method Description Color.getRGB() Returns the numeric RGB value set by the last setRGB() call. Color.
Color.getRGB() Availability Flash Player 5. Usage my_color.getRGB() : Number Parameters None. Returns A number that represents the RGB numeric value for the color specified. Description Method; returns the numeric values set by the last setRGB() call. Example The following code retrieves the RGB value for the Color object my_color, converts the value to a hexadecimal string, and assigns it to the myValue variable: var my_color:Color = new Color(my_mc); // set the color my_color.
Example The following example gets the transform object, and then sets new percentages for colors and alpha of my_mc relative to their current values: var my_color:Color = new Color(my_mc); var myTransform:Object = my_color.getTransform(); myTransform = { ra: 50, ba: 50, aa: 30}; my_color.setTransform(myTransform); For descriptions of the parameters for a color transform object, see Color.setTransform(). See also Color.setTransform() Color.setRGB() Availability Flash Player 5. Usage my_color.
Color.setTransform() Availability Flash Player 5. Usage my_color.setTransform(colorTransformObject:Object) : Void Parameters colorTransformObject An object created with the new Object constructor. This instance of the Object class must have the following properties that specify color transform values: ra, rb, ga, gb, ba, bb, aa, ab. These properties are explained below. Returns Nothing. Description Method; sets color transform information for a Color object.
Example This example creates a new Color object for a target SWF file, creates a generic object called myColorTransform with the properties defined above, and uses the setTransform() method to pass the colorTransformObject to a Color object.
CHAPTER 7 ActionScript for Flash ContextMenu class Availability Flash Player 7. Description The ContextMenu class provides runtime control over the items in the Flash Player context menu, which appears when a user right-clicks (Windows) or Control-clicks (Macintosh) on Flash Player. You can use the methods and properties of the ContextMenu class to add custom menu items, control the display of the built-in context menu items (for example, Zoom In and Print), or create copies of menus.
Property summary for the ContextMenu class Property Description ContextMenu.builtInItems An object whose members correspond to built-in context menu items. ContextMenu.customItems An array, undefined by default, that contains ContextMenuItem objects. Event handler summary for the ContextMenu class Property Description ContextMenu.onSelect Invoked before the menu is displayed. Constructor for the ContextMenu class Availability Flash Player 7.
var showItem = true; // Change this to false to remove var my_cm:ContextMenu = new ContextMenu(menuHandler); my_cm.customItems.push(new ContextMenuItem("Hello", itemHandler)); function menuHandler(obj, menuObj) { if (showItem == false) { menuObj.customItems[0].enabled = false; } else { menuObj.customItems[0].enabled = true; } } function itemHandler(obj, item) { //...put code here... trace("selected!"); } this.
var propValue = my_cm.builtInItems[propName]; trace(propName + ": " + propValue); } ContextMenu.copy() Availability Flash Player 7. Usage my_cm.copy() : ContextMenu Parameters None. Returns A ContextMenu object. Description Method; creates a copy of the specified ContextMenu object. The copy inherits all the properties of the original menu object. Example This example creates a copy of the ContextMenu object named my_cm whose built-in menu items are hidden, and adds a menu item with the text “Save...
ContextMenu.customItems Availability Flash Player 7. Usage my_cm.customItems:Array 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 menu_mc.customItems array (for example, using Array.push()).
Description Method; hides all built-in menu items (except Settings) in the specified ContextMenu object. If the Flash Debug Player is running, the Debugging menu item shows, although it is dimmed for SWF files that don’t have remote debugging enabled. 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.
Example The following example determines over what type of object the context menu was invoked: my_cm = new ContextMenu(); function menuHandler(obj:Object, menu:ContextMenu) { if(obj instanceof MovieClip) { trace("Movie clip: " + obj); } if(obj instanceof TextField) { trace("Text field: " + obj); } if(obj instanceof Button) { trace("Button: " + obj); } } my_cm.onSelect = menuHandler; my_mc.menu = my_cm; my_btn.menu = my_cm; ContextMenu.
CHAPTER 7 ActionScript for Flash ContextMenuItem class Availability Flash Player 7. Description You use the ContextMenuItem class to create custom menu items to display in the Flash Player context menu. Each ContextMenuItem object has a caption (text) that is displayed in the context menu, and a callback handler (a function) that is invoked when the menu item is selected. To add a new context menu item to a context menu, you add it to the customItems array of a ContextMenu object.
Constructor for the ContextMenuItem class Availability Flash Player 7. Usage new ContextMenuItem(caption:String, callbackFunction:Function, [ separatorBefore:Boolean, [ enabled:Boolean, [ visible:Boolean] ] ] ) : ContextMenuItem Parameters caption A string that specifies the text associated with the menu item. callbackFunction A function that you define, which is called when the menu item is selected.
ContextMenuItem.caption Availability Flash Player 7. Usage menuItem_cmi.caption:String Description Property; a string that specifies the menu item caption (text) displayed in the context menu. Example The following example writes the caption for the selected menu item (Pause Game) to the log file: var my_cm:ContextMenu = new ContextMenu(); var menuItem_cmi:ContextMenuItem = new ContextMenuItem("Pause Game", onPause); my_cm.customItems.
my_cm.customItems.push(copy_cmi); my_mc.menu = my_cm; ContextMenuItem.enabled Availability Flash Player 7. Usage menuItem_cmi.enabled:Boolean Description Property; a Boolean value that indicates whether the specified menu item is enabled or disabled. By default, this property is true. Example The following example creates two new context menu items: Start and Stop. When the user selects Start, the number of milliseconds from when the SWF file started is traced. Start is then disabled in the menu.
ContextMenuItem.onSelect Availability Flash Player 7. Usage menuItem_cmi.onSelect = function (obj:Object, menuItem:ContextMenuItem) : Void { // your statements here } Parameters obj A reference to the movie clip (or Timeline), button, or selectable text field that the user right-clicked or Control-clicked. menuItem A reference to the selected ContextMenuItem object. Returns Nothing. Description Event handler; invoked when the specified menu item is selected from the Flash Player context menu.
ContextMenuItem.separatorBefore Availability Flash Player 7. Usage menuItem_cmi.separatorBefore:Boolean Description Property; a Boolean value that indicates whether a separator bar should appear above the specified menu item. By default, this property is false. Note: A separator bar always appears between any custom menu items and the built-in menu items. Example This example creates three menu items, labeled Open, Save, and Print. A separator bar divides the Save and Print items.
Example The following example creates two new context menu items: Start and Stop. When the user selects Start, the number of milliseconds from when the SWF file started is displayed. Start is then made invisible in the menu. When Stop is selected, the number of milliseconds that have elapsed since the SWF file started is displayed. The Start menu item is made visible and the Stop menu item is made invisible.
duplicateMovieClip() CHAPTER 7 ActionScript for Flash Availability Flash Player 4. Usage duplicateMovieClip(target:String, newname:String, depth:Number) : Void Parameters target newname The target path of the movie clip to duplicate. A unique identifier for the duplicated movie clip. A unique depth level for the duplicated movie clip. The depth level is a stacking order for duplicated movie clips.
_focusrect CHAPTER 7 ActionScript for Flash Availability Flash Player 4. Usage _focusrect = Boolean; Description Property (global); specifies whether a yellow rectangle appears around the button or movie clip that has keyboard focus. If _focusrect is set to its default value of true, then a yellow rectangle appears around the currently focused button or movie clip as the user presses the Tab key to navigate through objects in a SWF file. Specify false if you do not want to show the yellow rectangle.
getProperty() CHAPTER 7 ActionScript for Flash Availability Flash Player 4. Usage getProperty(my_mc:Object, property:Object) : Object Parameters my_mc The instance name of a movie clip for which the property is being retrieved. property A property of a movie clip. Returns The value of the specified property. Description Function; returns the value of the specified property for the movie clip my_mc.
CHAPTER 7 ActionScript for Flash Microphone class Availability Flash Player 6. Description The Microphone class lets you capture audio from a microphone attached to the computer that is running Flash Player. The Microphone class is primarily for use with Flash Communication Server but can be used in a limited fashion without the server—for example, to transmit sound from your microphone through the speakers on your local system.
Property (read-only) Description Microphone.names Class property; an array of strings reflecting the names of all available sound capture devices, including sound cards and microphones. Microphone.rate The sound capture rate, in kHz. Microphone.silenceLevel The amount of sound required to activate the microphone. Microphone.silenceTimeOut The number of milliseconds between the time the microphone stops detecting sound and Microphone.onActivity(false) is called. Microphone.
activityLevel_pb.label = "Activity Level: %3%%"; activityLevel_pb.setStyle("themeColor", "0xFF0000"); this.createEmptyMovieClip("sound_mc", this.getNextHighestDepth()); var active_mic:Microphone = Microphone.get(); sound_mc.attachAudio(active_mic); this.onEnterFrame = function() { activityLevel_pb.setProgress(active_mic.activityLevel, 100); }; active_mic.
Microphone.get() Availability Flash Player 6. Usage Microphone.get([index:Number]) : Microphone Note: The correct syntax is Microphone.get(). To assign the Microphone object to a variable, use syntax like active_mic = Microphone.get(). Parameters index An optional zero-based integer that specifies which microphone to get, as determined from the array that Microphone.names contains. To get the default microphone (which is recommended for most applications), omit this parameter.
The user can also specify permanent privacy settings for a particular domain by right-clicking (Windows) or Control-clicking (Macintosh) while a SWF file is playing, choosing Settings, opening the Privacy panel, and selecting Remember. 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 System.showSettings(0). If the user selects Remember, Flash Player no longer displays the Privacy dialog box for SWF files from this domain.
mic_lbl.text = "["+active_mic.index+"] "+active_mic.name; mic_cb.dataProvider = Microphone.names; mic_cb.selectedIndex = active_mic.index; var cbListener:Object = new Object(); cbListener.change = function(evt:Object) { active_mic = Microphone.get(evt.target.selectedIndex); sound_mc.attachAudio(active_mic); mic_lbl.text = "["+active_mic.index+"] "+active_mic.name; }; mic_cb.addEventListener("change", cbListener); See also Microphone.get(), Microphone.names Microphone.muted Availability Flash Player 6.
Example The following example displays information about the sound capturing device(s) on your computer system, including an array of names and the default device. var status_ta:mx.controls.TextArea; status_ta.html = false; status_ta.setStyle("fontSize", 9); var microphone_array:Array = Microphone.names; var active_mic:Microphone = Microphone.get(); status_ta.text = "The default device is: "+active_mic.name+newline+newline; status_ta.text += "You have "+microphone_array.length+" device(s) installed.
status_ta.text += "You have "+microphone_array.length+" device(s) installed."+newline+newline; for (var i = 0; i
active_mic.onActivity = function(active:Boolean) { if (active) { activityLevel_pb.indeterminate = false; activityLevel_pb.label = "Activity Level: %3%%"; } else { activityLevel_pb.indeterminate = true; activityLevel_pb.label = "Activity Level: (inactive)"; } }; this.onEnterFrame = function() { activityLevel_pb.setProgress(active_mic.activityLevel, 100); }; See also Microphone.setSilenceLevel() Microphone.onStatus Availability Flash Player 6. Usage active_mic.
Note: If the user chooses to permanently allow or deny access to all SWF files from a specified domain, this method is not invoked for SWF files from that domain unless the user later changes the privacy setting. For more information, see Microphone.get(). Example The following example launches the Privacy dialog box that lets the user choose whether to allow or deny access to the microphone when they click a hyperlink. If the user chooses to deny access, muted is displayed in large red text.
Example The following code lets you use a ComboBox instance, called rate_cb, to change the rate at which your microphone captures sound. The current rate displays in a Label instance called rate_lbl. this.createEmptyMovieClip("sound_mc", this.getNextHighestDepth()); var active_mic:Microphone = Microphone.get(); sound_mc.attachAudio(active_mic); var rate_array:Array = new Array(5, 8, 11, 22, 44); rate_cb.dataProvider = rate_array; rate_cb.
You can think of this setting like a volume knob on a stereo: 0 is no volume and 50 is normal volume; numbers below 50 specify lower than normal volume, while numbers above 50 specify higher than normal volume. Example The following example uses a ProgressBar instance called gain_pb to display and a NumericStepper instance called gain_nstep to set the microphone’s gain value. this.createEmptyMovieClip("sound_mc", this.getNextHighestDepth()); var active_mic:Microphone = Microphone.get(); sound_mc.
Example The following example sets the microphone rate to the user’s preference (which you have assigned to the userRate variable) if it is one of the following values: 5, 8, 11, 22, or 44. If it is not, the value is rounded to the nearest acceptable value that the sound capture device supports. active_mic.setRate(userRate); The following example lets you use a ComboBox instance, called rate_cb, to change the rate at which your microphone captures sound.
Returns Nothing. Description Method; sets the minimum input level that should be considered sound and (optionally) the amount of silent time signifying that silence has actually begun. • To prevent the microphone from detecting sound at all, pass a value of 100 for level; Microphone.onActivity is never invoked. • To determine the amount of sound the microphone is currently detecting, use Microphone.activityLevel.
var nstepListener:Object = new Object(); nstepListener.change = function(evt:Object) { active_mic.setSilenceLevel(evt.target.value, active_mic.silenceTimeOut); }; silenceLevel_nstep.addEventListener("change", nstepListener); this.onEnterFrame = function() { silenceLevel_pb.setProgress(active_mic.activityLevel, 100); }; active_mic.onActivity = function(active:Boolean) { if (active) { silenceLevel_pb.indeterminate = false; silenceLevel_pb.setStyle("themeColor", "haloGreen"); silenceLevel_pb.
Generally, echo suppression is advisable when the sound being captured is played through speakers—instead of a headset—on the same computer. If your SWF file allows users to specify the sound output device, you may want to call Microphone.setUseEchoSuppression(true) if they indicate they are using speakers and will be using the microphone as well. Users can also adjust these settings in the Flash Player Microphone Settings panel.
var silenceLevel_pb:mx.controls.ProgressBar; var silenceLevel_nstep:mx.controls.NumericStepper; this.createEmptyMovieClip("sound_mc", this.getNextHighestDepth()); var active_mic:Microphone = Microphone.get(); sound_mc.attachAudio(active_mic); silenceLevel_pb.label = "Activity level: %3"; silenceLevel_pb.mode = "manual"; silenceLevel_nstep.minimum = 0; silenceLevel_nstep.maximum = 100; silenceLevel_nstep.value = active_mic.silenceLevel; var nstepListener:Object = new Object(); nstepListener.
Example The following example enables the user to control the amount of time between when the microphone stops detecting sound and when Microphone.onActivity(false) is invoked. The user controls this value using a NumericStepper instance called silenceTimeOut_nstep. The ProgressBar instance called silenceLevel_pb modifies its appearance depending on whether the audio stream is considered silent. Otherwise, it displays the activity level of the audio stream. var silenceLevel_pb:mx.controls.
Description Property (read-only); a Boolean value of true if echo suppression is enabled, false otherwise. The default value is false unless the user has selected Reduce Echo in the Flash Player Microphone Settings panel. Example The following example turns on echo suppression if the user selects a CheckBox instance called useEchoSuppression_ch. The ProgressBar instance called activityLevel_pb displays the current activity level of the audio stream. var useEchoSuppression_ch:mx.controls.
CHAPTER 7 ActionScript for Flash MMExecute() Availability Flash Player 7. Usage MMExecute("Flash JavaScript API command;":String) Parameters Flash JavaScript API command Any command that you can use in a Flash JavaScript (JSFL) file. Returns A string representation of the result, if any, sent by the JavaScript statement. Description Function; lets you issue Flash JavaScript API (JSAPI) commands from ActionScript.
CHAPTER 7 ActionScript for Flash MovieClip class Availability Flash Player 3. Description The MovieClip class is the base class for Flex components. However, while Macromedia supports some of the MovieClip interface for use in Flex applications, much of the interface has been overridden by Flex. For more information on using the MovieClip class with Flex, see Developing Flex Applications.
Method Description MovieClip.globalToLocal() Converts Stage coordinates to the local coordinates of the specified movie clip. MovieClip.gotoAndPlay() Sends the playhead to a specific frame in the movie clip and plays the movie clip. MovieClip.gotoAndStop() Sends the playhead to a specific frame in the movie clip and stops the movie clip. MovieClip.hitTest() Returns true if bounding box of the specified movie clip intersects the bounding box of the target movie clip. MovieClip.
Method Description MovieClip.lineStyle() Defines the stroke of lines created with the MovieClip.lineTo() and MovieClip.curveTo() methods. MovieClip.lineTo() Draws a line using the current line style. MovieClip.moveTo() Moves the current drawing position to specified coordinates. Property summary for the MovieClip class 556 Property Description MovieClip._alpha The transparency value of a movie clip instance. MovieClip.
Property Description MovieClip._target Read-only; the target path of a movie clip instance. MovieClip._totalframes Read-only; the total number of frames in a movie clip instance. MovieClip.trackAsMenu A Boolean value that indicates whether other movie clips can receive mouse release events. MovieClip._url Read-only; the URL of the SWF file from which a movie clip was downloaded. MovieClip.
Event handler Description MovieClip.onLoad Invoked when the movie clip is instantiated and appears in the Timeline. MovieClip.onMouseDown Invoked when the left mouse button is pressed. MovieClip.onMouseMove Invoked every time the mouse is moved. MovieClip.onMouseUp Invoked when the left mouse button is released. MovieClip.onPress Invoked when the mouse is pressed while the pointer is over a movie clip. MovieClip.
// replace with your own image or use the following holder_mc.image_mc.loadMovie("http://www.macromedia.com/devnet/mx/blueprint/ articles/nielsen/spotlight_jnielsen.jpg"); holder_mc.onRollOver = function() { this._alpha = 50; }; holder_mc.onRollOut = function() { this._alpha = 100; }; See also TextField._alpha, MovieClip._visible MovieClip.attachAudio() Availability Flash Player 6; the ability to attach audio from Flash Video (FLV) files was added in Flash Player 7. Usage my_mc.
volUp_btn.onRelease = function() { if (audio_sound.getVolume()<100) { audio_sound.setVolume(audio_sound.getVolume()+10); updateVolume(); } }; volDown_btn.onRelease = function() { if (audio_sound.getVolume()>0) { audio_sound.setVolume(audio_sound.getVolume()-10); updateVolume(); } }; // updates the volume this.createTextField("volume_txt", this.getNextHighestDepth(), 0, 0, 100, 22); updateVolume(); function updateVolume() { volume_txt.text = "Volume: "+audio_sound.
Returns A reference to the newly created instance. Description Method; takes a symbol from the library and attaches it to the SWF file on the Stage specified by my_mc. Use MovieClip.removeMovieClip() or MovieClip.unloadMovie() to remove a SWF file attached with attachMovie(). You can extend the methods and event handlers of the MovieClip class by creating a subclass.
Example The following example creates a square with red fill on the Stage. this.createEmptyMovieClip("square_mc", this.getNextHighestDepth()); square_mc.beginFill(0xFF0000); square_mc.moveTo(10, 10); square_mc.lineTo(100, 10); square_mc.lineTo(100, 100); square_mc.lineTo(10, 100); square_mc.lineTo(10, 10); square_mc.endFill(); See also MovieClip.beginGradientFill(), MovieClip.endFill() MovieClip.beginGradientFill() Availability Flash Player 6. Usage my_mc.
moveTo(100, lineTo(100, lineTo(300, lineTo(300, lineTo(100, endFill(); 100); 300); 300); 100); 100); } If a matrixType property does not exist then the remaining parameters are all required; the 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). • matrixType, x, y, w, h, r.
If a matrixType property exists then it must equal "box" and the remaining parameters are all required. The function fails if any of these conditions are not met. Returns Nothing. Description Method; indicates the beginning of a new drawing path. If the first parameter is undefined, or if 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 MovieClip.
moveTo(100, lineTo(100, lineTo(600, lineTo(600, lineTo(100, endFill(); 310); 510); 510); 310); 310); } See also MovieClip.beginFill(), MovieClip.endFill(), MovieClip.lineStyle(), MovieClip.lineTo(), MovieClip.moveTo() MovieClip.clear() Availability Flash Player 6. Usage my_mc.clear() : Void Parameters None. Returns Nothing. Description Method; removes all the graphics created during runtime using the movie clip draw methods, including line styles specified with MovieClip.lineStyle().
box_mc.onRelease = function() { this.clear(); }; drawBox(box_mc, 10, 10, 320, 240); function drawBox(mc:MovieClip, x:Number, y:Number, w:Number, h:Number):Void { mc.lineStyle(0); mc.beginFill(0xEEEEEE); mc.moveTo(x, y); mc.lineTo(x+w, y); mc.lineTo(x+w, y+h); mc.lineTo(x, y+h); mc.lineTo(x, y); mc.endFill(); } See also MovieClip.lineStyle() MovieClip.createEmptyMovieClip() Availability Flash Player 6. Usage my_mc.
MovieClip.createTextField() Availability Flash Player 6. Usage my_mc.createTextField(instanceName:String, depth:Number, x:Number, y:Number, width:Number, height:Number) : Void Parameters instanceName depth A string that identifies the instance name of the new text field. A positive integer that specifies the depth of the new text field. x An integer that specifies the x coordinate of the new text field. y An integer that specifies the y coordinate of the new text field.
variable = maxChars = styleSheet tabInded = null null = undefined undefined A text field created with createTextField() receives the following default TextFormat object: font = "Times New Roman" size = 12 color = 0x000000 bold = false italic = false underline = false url = "" target = "" align = "left" leftMargin = 0 rightMargin = 0 indent = 0 leading = 0 blockIndent = 0 bullet = false display = block tabStops = [] (empty array) You can extend the methods and event handlers of the MovieClip class by crea
Description Read-only property; 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 _currentframe property to direct the playhead of the movie clip actionClip_mc to advance five frames ahead of its current location: actionClip_mc.gotoAndStop(actionClip_mc._currentframe + 5); MovieClip.curveTo() Availability Flash Player 6. Usage my_mc.
Example The following example draws a circle with a solid blue hairline stroke and a solid red fill: this.createEmptyMovieClip("circle_mc", 1); with (circle_mc) { lineStyle(0, 0x0000FF, 100); beginFill(0xFF0000); moveTo(500, 500); curveTo(600, 500, 600, 400); curveTo(600, 300, 500, 300); curveTo(400, 300, 400, 400); curveTo(400, 500, 500, 500); endFill(); } The curve drawn in this example is a quadratic bezier curve. Quadratic bezier curves consist of two anchor points and a control point.
MovieClip._droptarget Availability Flash Player 4. Usage my_mc._droptarget:String Description Read-only property; returns the absolute path in slash syntax notation of the movie clip instance on which my_mc was dropped. The _droptarget property always returns a path that starts with a slash (/). To compare the _droptarget property of an instance to a reference, use the eval() function to convert the returned value from slash syntax to a dot syntax reference.
Parameters A unique identifier for the duplicate movie clip. newname depth A unique number specifying the depth at which the SWF file specified is to be placed. (Supported for Flash Player 6 and later.) An object containing properties with which to populate the duplicated movie clip. This parameter allows dynamically created movie clips to receive clip parameters. If initObject is not an object, it is ignored. All properties of initObject are copied into the new instance.
Description Property; a Boolean value that indicates whether a movie clip is enabled. The default value of enabled is true. If enabled is set to false, the movie clip’s callback methods and on action event handlers are no longer invoked, and the Over, Down, and Up frames are disabled. The enabled property does not affect the Timeline of the movie clip; if a movie clip is playing, it continues to play.
square_mc.lineTo(10, 100); square_mc.lineTo(10, 10); square_mc.endFill(); See Also MovieClip.beginFill(), MovieClip.beginGradientFill(), MovieClip.moveTo() MovieClip.focusEnabled Availability Flash Player 6. Usage my_mc.focusEnabled:Boolean Description Property; if the value is undefined or false, a movie clip cannot receive input focus unless it is a button. If the focusEnabled property value is true, a movie clip can receive input focus even if it is not a button.
Example This example demonstrates how to hide the yellow rectangle around a specified movie clip instance in a SWF file when it has focus in a browser window. Create three movie clips called mc1_mc, mc2_mc, and mc3_mc, and add the following ActionScript: mc1_mc._focusrect = true; mc2_mc._focusrect = false; mc3_mc._focusrect = true; mc1_mc.onRelease = traceOnRelease; mc3_mc.onRelease = traceOnRelease; function traceOnRelease() { trace(this._name); } Test the SWF file in a browser window.
Parameters targetCoordinateSpace The target path of the Timeline whose coordinate system you want to use as a reference point. Returns An object with the properties xMin, xMax, yMin, and yMax. Description Method; returns properties that are the minimum and maximum x and y coordinate values of the instance specified by my_mc for the targetCoordinateSpace parameter. Note: Use MovieClip.localToGlobal() and MovieClip.
MovieClip.getBytesLoaded() Availability Flash Player 5. Usage my_mc.getBytesLoaded() : Number 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 my_mc. You can compare this value with the value returned by MovieClip.getBytesTotal() to determine what percentage of a movie clip has loaded.
MovieClip.getDepth() Availability Flash Player 6. Usage my_mc.getDepth() : Number Parameters None. Returns An integer. Description Method; returns the depth of a movie clip instance. You can extend the methods and event handlers of the MovieClip class by creating a subclass. Example The following code traces the depth of all movie clip instances on the Stage: for (var i in this) { if (typeof (this[i]) == "movieclip") { trace("movie clip '"+this[i]._name+"' is at depth "+this[i].
Description Method; lets you determine if a particular depth is already occupied by a movie clip. You can use this method before using MovieClip.attachMovie(), MovieClip.duplicateMovieClip(), or MovieClip.createEmptyMovieClip() to determine if the depth parameter you want to pass to any of these methods already contains a movie clip. You can extend the methods and event handlers of the MovieClip class by creating a subclass.
mclListener.onLoadInit = function(target_mc:MovieClip) { target_mc.onPress = function() { this.startDrag(); }; target_mc.onRelease = function() { this.stopDrag(); }; }; logo_mcl.addListener(mclListener); logo_mcl.loadClip("http://www.macromedia.com/devnet/mx/blueprint/articles/ nielsen/spotlight_jnielsen.jpg", logo_mc); See also MovieClip.getDepth(), MovieClip.getInstanceAtDepth(), MovieClip.swapDepths() MovieClip.getSWFVersion() Availability Flash Player 7. Usage my_mc.
MovieClip.getTextSnapshot() Availability Authoring: Flash MX 2004. Playback: SWF files published for Flash Player 6 or later, playing in Flash Player 7 or later. Usage my_mc.getTextSnapshot() : TextSnapshot Parameters None. Returns A TextSnapshot object that contains the static text from my_mc. Description Method; returns a TextSnapshot object that contains the text in all the static text fields in the specified movie clip; text in child movie clips is not included.
text_mc.textSnapshot_txt.htmlText += ""+i+"\t"+textSnap[i]; } text_mc.textSnapshot_txt.htmlText += ""; The following text appears in text_mc.textSnapshot_txt: getTextRunInfo[type Function] setSelectColor[type Function] findText[type Function] hitTestTextNearPos[type Function] getSelectedText[type Function] getText [type Function] getSelected[type Function] setSelected[type Function] getCount[type Function] See also TextSnapshot object MovieClip.getURL() Availability Flash Player 5.
Example The following ActionScript creates a new movie clip instance and opens the Macromedia website in a new browser window: this.createEmptyMovieClip("loader_mc", this.getNextHighestDepth()); loader_mc.getURL("http://www.macromedia.com", “_blank”); The getURL() method also allows you to send variables to a remove server-side script, as seen in the following code: this.createEmptyMovieClip("loader_mc", this.getNextHighestDepth()); loader_mc.username = "some user input"; loader_mc.
var mouseListener:Object = new Object(); mouseListener.onMouseMove = function() { var point:Object = {x:_xmouse, y:_ymouse}; target_mc.globalToLocal(point); var rowHeaders = " \t_x\t_y"; var row_1 = "_root\t"+_xmouse+"\t"+_ymouse; var row_2 = "target_mc\t"+point.x+"\t"+point.y; coords_txt.htmlText = ""; coords_txt.htmlText += rowHeaders; coords_txt.htmlText += row_1; coords_txt.htmlText += row_2; coords_txt.htmlText += ""; }; Mouse.
Returns Nothing. Description Method; brings the playhead to the specified frame of the movie clip and stops it there. You can extend the methods and event handlers of the MovieClip class by creating a subclass. MovieClip._height Availability Flash Player 4. Usage my_mc._height:Number Description Property; the height of the movie clip, in pixels. Example The following code example writes the height and width of a movie clip to the log file : this.createEmptyMovieClip("image_mc", this.
Description Property; designates another movie clip to serve as the hit area for a movie clip. If the hitArea property does not exist or is null or undefined, the movie clip itself is used as the hit area. The value of the hitArea property may be a reference to a movie clip object. You can change the hitArea property at any time; the modified movie clip immediately takes on the new hit area behavior.
Returns A Boolean value of true if my_mc overlaps with the specified hit area, false otherwise. Description Method; evaluates the instance specified by my_mc to see if it overlaps or intersects with the hit area identified by the target or x and y coordinate parameters. Usage 1: Compares the x and y coordinates to the shape or bounding box of the specified instance, according to the shapeFlag setting.
alpha An integer that indicates the alpha value of the line’s color; valid values are 0–100. If a value isn’t indicated, Flash uses 100 (solid). If the value is less than 0, Flash uses 0; if the value is greater than 100, Flash uses 100. Returns Nothing. Description Method; specifies a line style that Flash uses for subsequent calls to lineTo() and curveTo() until you call lineStyle() with different parameters.
Description Method; draws a line using the current line style from the current drawing position to (x, y); the current drawing position is then set to (x, y). If the movie clip that you are drawing in contains content that was created with the Flash drawing tools, calls to lineTo() are drawn underneath the content. If you call lineTo() before any calls to the moveTo() method, the current drawing position defaults to (0, 0).
Description Method; loads SWF or JPEG files into a movie clip in Flash Player while the original SWF file is playing. Tip: If you want to monitor the progress of the download, use MovieClipLoader.loadClip() instead of this function. Without the loadMovie() method, Flash Player displays a single SWF file and then closes. The loadMovie() method lets you display several SWF files at once and switch between SWF files without loading another HTML document.
See also MovieClip.loadMovie(), MovieClip.loadVariables(), MovieClip.unloadMovie(), unloadMovie(), unloadMovieNum() MovieClip.loadVariables() Availability Flash Player 5. Usage my_mc.loadVariables(url:String [, variables:String]) : Void Parameters The absolute or relative URL for the external file that contains the variables to be loaded. If the SWF file issuing this call is running in a web browser, url must be in the same domain as the SWF file; for details, see “Description,” below.
Parameters point The name or identifier of an object created with the Object class, specifying the x and y coordinates as properties. Returns Nothing. Description Method; converts the point object from the movie clip’s (local) coordinates to the Stage (global) coordinates. You can extend the methods and event handlers of the MovieClip class by creating a subclass.
For example, suppose you have a document called Games.fla that lets a user choose a game to play, and loads the game (for example, Chess.swf ) into the game_mc movie clip. You want to make sure that, if _root is used in Chess.swf, it still refers to _root in Chess.swf after being loaded into Games.swf. If you have access to Chess.fla and publish it to Flash Player 7 or later, you can add this statement to Chess.fla on the main Timeline: this._lockroot = true; If you don’t have access to Chess.
The lockroot.swf file has _lockroot applied to it, and nolockroot.swf does not. After the files are loaded, each file dumps variables from their _root scopes. Place the following ActionScript on the main Timeline of a FLA document: this.createEmptyMovieClip("lockroot_mc", this.getNextHighestDepth()); lockroot_mc.loadMovie("lockroot.swf"); this.createEmptyMovieClip("nolockroot_mc", this.getNextHighestDepth()); nolockroot_mc.loadMovie("nolockroot.
from lockroot.swf myOtherVar -> 2 myVar -> 1 MovieClip.menu Availability Flash Player 7. Usage my_mc.menu:ContextMenu = contextMenu Parameters contextMenu A ContextMenu object. Description Property; associates the specified ContextMenu object with the movie clip my_mc. The ContextMenu class lets you modify the context menu that appears when the user right-clicks (Windows) or Control-clicks (Macintosh) in Flash Player.
MovieClip.moveTo() Availability Flash Player 6. Usage my_mc.moveTo(x:Number, y:Number) : Void Parameters An integer indicating the horizontal position relative to the registration point of the parent movie clip. x An integer indicating the vertical position relative to the registration point of the parent movie clip. y Returns Nothing. Description Method; moves the current drawing position to (x, y).
Example The following example lets you right-click or Control-click a movie clip on the Stage and select “Info...” from the context menu to view information about that instance. Add several movie clips with instance names, and then add the following ActionScript to your AS or FLA file: var menu_cm:ContextMenu = new ContextMenu(); menu_cm.customItems.push(new ContextMenuItem("Info...", getMCInfo)); function getMCInfo(target_mc:MovieClip, obj:Object) { trace("You clicked on the movie clip '"+target_mc.
Parameters None. Returns Nothing. Description Event handler; invoked when a movie clip receives data from a MovieClip.loadVariables() or MovieClip.loadMovie() call. You must define a function that executes when the event handler is invoked. You can define the function on the Timeline or in a class file that extends the MovieClip class or is linked to a symbol in the library. This handler can be used only with movie clips for which you have a symbol in the library that is associated with a class.
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. You can define the function on the Timeline or in a class file that extends the MovieClip class or is linked to a symbol in the library.
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. You can define the function on the Timeline or in a class file that extends the MovieClip class or is linked to a symbol in the library. Example The following example defines a function for the onDragOver method that writes the results of a trace() method to the log file: my_mc.
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() and Key.getCode() methods to determine which key was pressed. You must define a function that executes when the event handler is invoked.
See also MovieClip.onKeyUp 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 onKeyUp event handler is invoked with no parameters. You can use the Key.getAscii() and Key.getCode() methods to determine which key was pressed. You must define a function that executes when the event handler is invoked.
MovieClip.onKillFocus Availability Flash Player 6. Usage my_mc.onKillFocus = function (newFocus:Object) { // your statements here } Parameters newFocus The object that is receiving the keyboard focus. Returns Nothing. Description Event handler; invoked when a movie clip loses keyboard focus. The onKillFocus method receives one parameter, newFocus, which is an object that represents the new object receiving the focus. If no object receives the focus, newFocus contains the value null.
Parameters None. Returns Nothing. Description Event handler; invoked when the movie clip is instantiated and appears in the Timeline. You must define a function that executes when the event handler is invoked. You can define the function on the Timeline or in a class file that extends the MovieClip class or is linked to a symbol in the library. This handler can be used only with movie clips for which you have a symbol in the library that is associated with a class.
MovieClip.onMouseDown Availability Flash Player 6. Usage my_mc.onMouseDown = function() { // your statements here } Parameters None. Returns Nothing. Description Event handler; invoked when the mouse button is pressed. You must define a function that executes when the event handler is invoked. You can define the function on the Timeline or in a class file that extends the MovieClip class or is linked to a symbol in the library.
Example The following example defines a function for the onMouseMove method that writes the results of a trace() method to the log file: my_mc.onMouseMove = function () { trace ("onMouseMove called"); }; 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.
Returns Nothing. Description Event handler; invoked when the user clicks the mouse while the pointer is over a movie clip. You must define a function that executes when the event handler is invoked. You can define the function on the Timeline or in a class file that extends the MovieClip class or is linked to a symbol in the library. Example The following example defines a function for the onMouseUp method that writes the results of a trace() method to the log file: my_mc.
MovieClip.onReleaseOutside Availability Flash Player 6. Usage my_mc.onReleaseOutside = function() { // your statements here } Parameters None. Returns Nothing. Description Event handler; invoked after the mouse button has been pressed inside the movie clip area and then released outside the movie clip area. You must define a function that executes when the event handler is invoked.
Description Event handler; invoked when the pointer moves outside a movie clip area. You must define a function that executes when the event handler is invoked. You can define the function on the Timeline or in a class file that extends the MovieClip class or is linked to a symbol in the library. Example The following example defines a function for the onRollOut method that writes the results of a trace() method to the log file: my_mc.onRollOut = function () { trace ("onRollOut called"); }; MovieClip.
MovieClip.onSetFocus Availability Flash Player 6. Usage my_mc.onSetFocus = function(oldFocus){ // your statements here } Parameters oldFocus The object to lose focus. Returns Nothing. Description Event handler; invoked when a movie clip receives keyboard focus. The oldFocus parameter is the object that loses the focus. For example, if the user presses the Tab key to move the input focus from a movie clip to a text field, oldFocus contains the movie clip instance.
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 onUnload event handler before attaching any actions to the affected frame. You must define a function that executes when the event handler is invoked.
Example The following example logs the reference to a movie clip and its relationship to the main Timeline. Create a movie clip with the instance name my_mc, and add it to the main Timeline. Add the following ActionScript to your FLA or AS file: my_mc.onRelease = function() { trace("You clicked the movie clip: "+this); trace("The parent of "+this._name+" is: "+this._parent); } When you click the movie clip, the following information writes to the log file. You clicked the movie clip: _level0.
See also MovieClip.gotoAndPlay() MovieClip.prevFrame() Availability Flash Player 5. Usage my_mc.prevFrame() : Void Parameters None. Returns Nothing. Description Method; sends the playhead to the previous frame and stops it. You can extend the methods and event handlers of the MovieClip class by creating a subclass. Example In the following example, two movie clip buttons control the Timeline.
MovieClip.removeMovieClip() Availability Flash Player 5. Usage my_mc.removeMovieClip() : Void Parameters None. Returns Nothing. Description Method; removes a movie clip instance created with duplicateMovieClip(), MovieClip.duplicateMovieClip(), or MovieClip.attachMovie(). You can extend the methods and event handlers of the MovieClip class by creating a subclass. Example Each time you click a button in the following example, you attach a movie clip instance to the Stage in a random position.
Description Property; the rotation of the movie clip, 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 my_mc._rotation = 450 is the same as my_mc._rotation = 90. Example The following example creates a movie clip instance dynamically, rotates, and loads an image into the instance.
To cancel a mask created with ActionScript, pass the value null to the setMask() method. The following code cancels the mask without affecting the mask layer in the Timeline. UIMask.setMask(null); You can extend the methods and event handlers of the MovieClip class by creating a subclass. Example The following code uses the movie clip circleMask_mc to mask the movie clip theMaskee_mc: theMaskee_mc.setMask(circleMask_mc); MovieClip.startDrag() Availability Flash Player 5. Usage my_mc.
}; var image_mcl:MovieClipLoader = new MovieClipLoader(); image_mcl.addListener(mclListener); image_mcl.loadClip("http://www.macromedia.com/devnet/mx/blueprint/articles/ nielsen/spotlight_jnielsen.jpg", image_mc); See also MovieClip._droptarget, startDrag(), MovieClip.stopDrag() MovieClip.stop() Availability Flash Player 5. Usage my_mc.stop() : Void Parameters None. Returns Nothing. Description Method; stops the movie clip currently playing.
Description Method; ends a MovieClip.startDrag() method. A movie clip that was made draggable with that method remains draggable until a stopDrag() method is added, or until another movie clip becomes draggable. Only one movie clip is draggable at a time. You can extend the methods and event handlers of the MovieClip class by creating a subclass. Example The following example creates a draggable movie clip instance called image_mc. A MovieClipLoader object is used to load an image into image_mc. this.
Description Method; swaps the stacking, or z-order (depth level), of the specified instance (my_mc) with the movie clip specified by the target parameter, or with the movie clip that currently occupies the depth level specified in the depth parameter. Both movie clips must have the same parent movie clip. Swapping the depth level of movie clips has the effect of moving one movie clip in front of or behind the other. If a movie clip is tweening when this method is called, the tweening is stopped.
The following example disables tabbing for all children movie clips inside a parent movie clip called menu_mc. menu_mc.onRelease = function(){}; menu_mc.menu1_mc.onRelease = function(){}; menu_mc.menu2_mc.onRelease = function(){}; menu_mc.menu3_mc.onRelease = function(){}; menu_mc.menu4_mc.onRelease = function(){}; menu_mc.tabChildren = false; Change the last line of code to the following, in order to include the children movie clip instances of menu_mc in the automatic tab ordering. menu_mc.
MovieClip.tabIndex Availability Flash Player 6. Usage my_mc.tabIndex:Number Description Property; lets you customize the tab ordering of objects in a movie. The tabIndex property is undefined by default. You can set tabIndex on a button, movie clip, or text field instance. If an object in a SWF file contains a tabIndex property, automatic tab ordering is disabled, and the tab ordering is calculated from the tabIndex properties of objects in the SWF file.
for (var i in this) { if (typeof (this[i]) == "movieclip") { trace("name: "+this[i]._name+",\t target: "+this[i]._target+",\t target(2): "+eval(this[i]._target)); } } MovieClip._totalframes Availability Flash Player 4. Usage my_mc._totalframes:Number Description Read-only property; returns the total number of frames in the movie clip instance specified in the MovieClip parameter. Example In the following example, two movie clip buttons control the Timeline.
Description Property; a Boolean value that indicates whether or not other buttons or movie clips can receive mouse release events. This allows you to create menus. You can set the trackAsMenu property on any button or movie clip object. If the trackAsMenu property does not exist, the default behavior is false. You can change the trackAsMenu property at any time; the modified movie clip immediately takes on the new behavior.
Example The following example unloads a movie clip instance called image_mc when a user clicks the unloadMC_btn instance. this.createEmptyMovieClip("image_mc", 1); image_mc.loadMovie("http://www.macromedia.com/images/shared/product_boxes/ 112x112/box_studio_112x112.jpg"); unloadMC_btn.onRelease = function() { image_mc.unloadMovie(); }; See also MovieClip.attachMovie(), MovieClip.loadMovie(), unloadMovie(), unloadMovieNum() MovieClip._url Availability Flash Player 4. Usage my_mc.
}; var image_mcl:MovieClipLoader = new MovieClipLoader(); image_mcl.addListener(mclListener); image_mcl.loadClip("photo1.jpg", image_mc); function viewImage(target_mc:MovieClip, obj:Object) { getURL(target_mc._url, "_blank"); } When you right-click or Control-click the image at runtime, select View Image in Browser from the context menu to open the image in a browser window. MovieClip.useHandCursor Availability Flash Player 6. Usage my_mc.
Description Property; a Boolean value that indicates whether the movie clip specified by my_mc is visible. Movie clips that are not visible (_visible property set to false) are disabled. For example, a button in a movie clip with _visible set to false cannot be clicked. Example The following example sets the _visible property for two movie clips called myMC1_mc and myMC2_mc. The property is set to true for one instance, and false for the other.
MovieClip._x Availability Flash Player 3. Usage my_mc._x:Number 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). If the move clip is inside another movie clip that has transformations, the movie clip is in the local coordinate system of the enclosing movie clip.
Example The following example returns the current x and y coordinates of the mouse on the Stage (_level0) and in relation to a movie clip on the Stage called my_mc. this.createTextField("mouse_txt", this.getNextHighestDepth, 0, 0, 150, 66); mouse_txt.html = true; mouse_txt.multiline = true; var row1_str:String = " \t_xmouse\t_ymouse"; my_mc.onMouseMove = function() { mouse_txt.htmlText = ""; mouse_txt.htmlText += row1_str; mouse_txt.
endFill(); } box_mc.onRollOver = function() { this._x -= this._width/2; this._y -= this._height/2; this._xscale = 200; this._yscale = 200; }; box_mc.onRollOut = function() { this._xscale = 100; this._yscale = 100; this._x += this._width/2; this._y += this._height/2; }; See also MovieClip._x, MovieClip._y, MovieClip._yscale, MovieClip._width MovieClip._y Availability Flash Player 3. Usage my_mc.
See also MovieClip._x, MovieClip._xscale, MovieClip._yscale MovieClip._ymouse Availability Flash Player 5. Usage my_mc._ymouse:Number Description Read-only property; indicates the y coordinate of the mouse position. Example The following example returns the current x and y coordinates of the mouse on the Stage (_level0) and in relation to a movie clip on the Stage called my_mc. this.createTextField("mouse_txt", this.getNextHighestDepth, 0, 0, 150, 66); mouse_txt.html = true; mouse_txt.
Example The following example creates a movie clip at runtime called box_mc. The Drawing API is used to draw a box in this instance, and when the mouse rolls over the box, horizontal and vertical scaling is applied to the movie clip. When the mouse rolls off the instance, it returns to the previous scaling. this.createEmptyMovieClip("box_mc", 1); box_mc._x = 100; box_mc.
CHAPTER 7 ActionScript for Flash 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 loadMovie() or MovieClip.loadMovie() to load SWF files. After you issue the MovieClipLoader.
Listener summary for the MovieClipLoader class Listener Description MovieClipLoader.onLoadComplete Invoked when a file loaded with MovieClipLoader.loadClip() has completely downloaded. MovieClipLoader.onLoadError Invoked when a file loaded with MovieClipLoader.loadClip() has failed to load. MovieClipLoader.onLoadInit Invoked when the actions on the first frame of the loaded clip have been executed. MovieClipLoader.
Parameters listenerObject An object that listens for a callback notification from the MovieClipLoader event handlers. Returns Nothing. Description Method; registers an object to receive notification when a MovieClipLoader event handler is invoked. Example The following example loads an image into a movie clip called image_mc. The movie clip instance is rotated and centered on the Stage, and both the Stage and movie clip have a stroke drawn around their perimeters. this.
Returns An object that has two integer properties: bytesLoaded and bytesTotal. Description Method; returns the number of bytes loaded and total number of bytes for a file that is being loaded using MovieClipLoader.loadClip(); for compressed movies, it reflects the number of compressed bytes. This method lets you explicitly request this information, instead of (or in addition to) writing a MovieClipLoader.onLoadProgress listener function.
target The target path of a movie clip, or an integer specifying the level in Flash Player into which the movie will be loaded. The target movie clip is replaced by the loaded SWF file or image. Returns A Boolean value. The return value is true if the URL request was sent successfully; otherwise the return value is false. Description Method; loads a SWF or JPEG file into a movie clip in Flash Player while the original movie is playing.
var myListener:Object = new Object(); myListener.onLoadStart = function(target_mc:MovieClip) { trace("*********First my_mcl instance*********"); trace("Your load has begun on movie clip = "+target_mc); var loadProgress:Object = my_mcl.getProgress(target_mc); trace(loadProgress.bytesLoaded+" = bytes loaded at start"); trace(loadProgress.bytesTotal+" = bytes total at start"); }; myListener.
var loadProgress:Object = my_mcl.getProgress(target_mc); trace(loadProgress.bytesLoaded+" = bytes loaded at start"); trace(loadProgress.bytesTotal+" = bytes total at start"); }; myListener2.onLoadComplete = function(target_mc:MovieClip) { trace("*********Second my_mcl instance*********"); trace("Your load is done on movie clip = "+target_mc); var loadProgress:Object = my_mcl.getProgress(target_mc); trace(loadProgress.bytesLoaded+" = bytes loaded at end"); trace(loadProgress.
Description Listener; invoked when a file loaded with MovieClipLoader.loadClip() has completely downloaded. The value for target_mc identifies the movie clip for which this call is being made. This is useful if multiple files are being loaded with the same set of listeners. This parameter is passed by Flash to your code, but you do not have to implement all of the parameters in the listener function.
// your statements here } Parameters listenerObject A listener object that was added using MovieClipLoader.addListener(). target_mc A movie clip loaded by a MovieClipLoader.loadClip() method. errorCode A string that explains the reason for the failure. Returns One of two strings: "URLNotFound" or "LoadNeverCompleted". Description Listener; invoked when a file loaded with MovieClipLoader.loadClip() has failed to load. The string "URLNotFound" is returned if neither the MovieClipLoader.
image_mcl.addListener(mclListener); image_mcl.loadClip("http://www.fakedomain.com/images/bad_hair_day.jpg", image_mc); MovieClipLoader.onLoadInit Availability Flash Player 7. Usage listenerObject.onLoadInit = function([target_mc:MovieClip]) { // your statements here } Parameters listenerObject target_mc A listener object that was added using MovieClipLoader.addListener(). A movie clip loaded by a MovieClipLoader.loadClip() method. This parameter is optional. Returns Nothing.
var image_mcl:MovieClipLoader = new MovieClipLoader(); image_mcl.addListener(mclListener); image_mcl.loadClip("http://www.macromedia.com/images/shared/product_boxes/ 112x112/box_studio_112x112.jpg", image_mc); See also MovieClipLoader.onLoadStart MovieClipLoader.onLoadProgress Availability Flash Player 7. Usage listenerObject.
Example The following example creates a progress bar using the Drawing API. The progress bar displays the loading progress of an image using the onLoadProgress listener. When the image finishes loading, the progress bar is removed from the Stage. You must replace the URL parameter of the image_mcl.loadClip() command so that the parameter refers to a valid JPEG file using HTTP.
See also MovieClipLoader.getProgress() MovieClipLoader.onLoadStart Availability Flash Player 7. Usage listenerObject.onLoadStart = function([target_mc:Object]) { // your statements here } Parameters listenerObject target_mc A listener object that was added using MovieClipLoader.addListener(). A movie clip loaded by a MovieClipLoader.loadClip() method. This parameter is optional. Returns Nothing. Description Listener; invoked when a call to MovieClipLoader.
See also MovieClipLoader.onLoadError, MovieClipLoader.onLoadInit, MovieClipLoader.onLoadComplete MovieClipLoader.removeListener() Availability Flash Player 7. Usage my_mcl.removeListener(listenerObject:Object) : Void Parameters listenerObject A listener object that was added using MovieClipLoader.addListener(). Returns Nothing. Description Method; removes the listener that was used to receive notification when a MovieClipLoader event handler was invoked. No further loading messages will be received.
image_mcl.loadClip("http://www.macromedia.com/devnet/images/160x160/ flex_logo.jpg", image_mc); }; stop_button.clickHandler = function() { trace("Stopping..."); start_button.enabled = true; stop_button.enabled = false; // image_mcl.removeListener(mclListener); }; stop_button.enabled = false; MovieClipLoader.unloadClip() Availability Flash Player 7. Usage my_mcl.unloadClip(target:Object) Parameters target The string or integer passed to the corresponding call to my_mcl.loadClip(). Returns Nothing.
CHAPTER 7 ActionScript for Flash 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 the Flash Communication Server documentation. Description The NetConnection class provides the means to play back streaming FLV files from a local drive or HTTP address. Method summary for the NetConnection class Method Description NetConnection.
NetConnection.connect() Availability Flash Player 7. Note: This method is also supported in Flash Player 6 when used with Flash Communication Server. For more information, see the Flash Communication Server documentation. Usage my_nc.connect(null) : Void Parameters None (you must pass null). Returns Nothing. Description Constructor; opens a local connection through which you can play back video (FLV) files from an HTTP address or from the local file system.
CHAPTER 7 ActionScript for Flash 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 the Flash Communication Server documentation. Description The NetStream class provides methods and properties for playing Flash Video (FLV) files from the local file system or an HTTP address. You use a NetStream object to stream video through a NetConnection object.
Event handler summary for the NetStream class Event handler Description NetStream.onStatus Invoked every time a status change or error is posted for the NetStream object. 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 the Flash Communication Server documentation. Usage new NetStream(my_nc:NetConnection) : NetStream Parameters my_nc A NetConnection object.
Usage my_ns.bufferLength:Number Description Read-only property; the number of seconds of data currently in the buffer. You can use this property in conjunction with NetStream.bufferTime to estimate how close the buffer is to being full—for example, to display feedback to a user who is waiting for data to be loaded into the buffer. Example The following example dynamically creates a text field that displays information about the number of seconds that are currently in the buffer.
Description Read-only property; the number of seconds assigned to the buffer by NetStream.setBufferTime(). The default value is .1(one-tenth of a second). To determine the number of seconds currently in the buffer, use NetStream.bufferLength. Example The following example dynamically creates a text field that displays information about the number of seconds that are currently in the buffer. The text field also displays the buffer length that the video is set to, and percentage of buffer that is filled.
Example The following example creates a progress bar using the Drawing API and the bytesLoaded and bytesTotal properties that displays the loading progress of video1.flv into the video object instance called my_video. A text field called loaded_txt is dynamically created to display information about the loading progress as well. var connection_nc:NetConnection = new NetConnection(); connection_nc.connect(null); var stream_ns:NetStream = new NetStream(connection_nc); my_video.
NetStream.bytesTotal Availability Flash Player 7. Usage my_ns.bytesTotal:Number Description Read-only property; the total size in bytes of the file being loaded into the player. Example The following example creates a progress bar using the Drawing API and the bytesLoaded and bytesTotal properties that displays the loading progress of video1.flv into the video object instance called my_video. A text field called loaded_txt is dynamically created to display information about the loading progress as well.
loaded_txt.text = Math.round(my_ns.bytesLoaded/1000)+" of "+Math.round(my_ns.bytesTotal/1000)+" KB loaded ("+pctLoaded+"%)"; progressBar_mc.bar_mc._xscale = pctLoaded; if (pctLoaded>=100) { clearInterval(loaded_interval); } } See also NetStream.bytesLoaded, NetStream.bufferTime 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 the Flash Communication Server documentation. Usage my_ns.
NetStream.currentFps Availability Flash Player 7. Note: This property is also supported in Flash Player 6 when used with Flash Communication Server. For more information, see the Flash Communication Server documentation. Usage my_ns.currentFps:Number Description Read-only property; the number of frames per second being displayed.
Returns Nothing. Description Event handler; invoked every time a status change or error is posted for the NetStream object. If you want to respond to this event handler, you must create a function to process the information object. The information object has a code property containing a string that describes the result of the onStatus handler, and a level property containing a string that is either status or error.
See also System.onStatus, NetStream.setBufferTime() NetStream.pause() Availability Flash Player 7. Note: This method is also supported in Flash Player 6 when used with Flash Communication Server. For more information, see the Flash Communication Server documentation. Usage my_ns.pause( [ pauseResume:Boolean ] ) : Void Parameters pauseResume A Boolean value specifying whether to pause play (true) or resume play (false). If you omit this parameter, NetStream.
Parameters The name of an FLV file to play, in quotation marks. Both http:// and file:// formats are supported; the file:// location is always relative to the location of the SWF file. fileName Returns Nothing. Description Method; begins playback of an external video (FLV) file. To view video data, you must call a Video.attachVideo() method; audio being streamed with the video, or an FLV file that contains only audio, is played automatically.
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 the Flash Communication Server documentation. Usage my_ns.seek(numberOfSeconds:Number) : Void Parameters numberOfSeconds The approximate time value, in seconds, to move to in an FLV file. The playhead moves to the keyframe of the video that’s closest to numberOfSeconds.
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 the Flash Communication Server documentation. Usage my_ns.setBufferTime(numberOfSeconds:Number) : Void Parameters numberOfSeconds The number of seconds of data to be buffered before Flash begins displaying data. The default value is 0.1 (one-tenth of a second).
stream_ns.play("video1.flv"); // stream_ns.onStatus = function(infoObject:Object) { statusCode_txt.text = infoObject.code; }; this.createTextField("time_txt", this.getNextHighestDepth(), 10, 10, 100, 22); time_txt.text = "LOADING"; var time_interval:Number = setInterval(checkTime, 500, stream_ns); function checkTime(my_ns:NetStream) { var ns_seconds:Number = my_ns.time; var minutes:Number = Math.floor(ns_seconds/60); var seconds = Math.
CHAPTER 7 ActionScript for Flash onClipEvent() Availability Flash Player 5. Usage onClipEvent(movieEvent){ // your statements here } Parameters A movieEvent is a trigger called an event. When the event occurs, the statements following it within curly braces ({}) are executed. Any of the following values can be specified for the movieEvent parameter: • load • unload The action is initiated in the first frame after the movie clip is removed from the Timeline.
Example The following example uses onClipEvent() with the keyDown movie event and is designed to be attached to a movie clip or button. The keyDown movie event is usually used with one or more methods and properties of the Key object. The following script uses Key.getCode() to find out which key the user has pressed; if the pressed key matches the Key.RIGHT property, the playhead is sent to the next frame; if the pressed key matches the Key.LEFT property, the playhead is sent to the previous frame.
onUpdate CHAPTER 7 ActionScript for Flash Availability Flash Player 6. Usage function onUpdate() { ...statements...; } Parameters None. Returns Nothing. Description Event handler; onUpdate is defined for a Live Preview used with a component. When an instance of a component on the Stage has a Live Preview, the authoring tool invokes the Live Preview’s onUpdate function whenever the component parameters of the component instance change.
_parent CHAPTER 7 ActionScript for Flash Availability Flash Player 5. Usage _parent.property _parent._parent.property Description Identifier; specifies or returns a reference to the movie clip or object that contains the current movie clip or object. The current object is the object containing the ActionScript code that references _parent. Use _parent to specify a relative path to movie clips or objects that are above the current movie clip or object.
removeMovieClip() CHAPTER 7 ActionScript for Flash Availability Flash Player 4. Usage removeMovieClip(target) Parameters The target path of a movie clip instance created with duplicateMovieClip() or the instance name of a movie clip created with MovieClip.attachMovie(), MovieClip.duplicateMovieClip(), or MovieClip.createEmptyMovieClip(). target Returns None. Description Function; deletes the specified movie clip.
CHAPTER 7 ActionScript for Flash _root Availability Flash Player 5. Usage _root.movieClip _root.action _root.property Parameters movieClip action property The instance name of a movie clip. An action or method. A property of the MovieClip object. Description Identifier; specifies or returns a reference to the root movie clip Timeline. If a movie clip has multiple levels, the root movie clip Timeline is on the level containing the currently executing script.
CHAPTER 7 ActionScript for Flash Selection class Availability Flash Player 5. Description The Selection class lets you set and control the text field in which the insertion point is located (that is, the field that has focus). Selection-span indexes are zero-based (for example, the first position is 0, the second position is 1, and so on). There is no constructor function for the Selection class, because there can be only one currently focused field at a time.
Parameters newListener An object with an onSetFocus method. Returns None. Description Method; registers an object to receive keyboard focus change notifications. When the focus changes (for example, whenever Selection.setFocus() is invoked), all listening objects registered with addListener() have their onSetFocus method invoked. Multiple objects may listen for focus change notifications. If the listener newListener is already registered, no change occurs.
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). Example The following example creates a text field at runtime, and sets its properties. A context menu item is added that can be used to change the currently selected text to uppercase characters. this.
Description Method; returns the index of the blinking insertion point (caret) position. If there is no blinking insertion point displayed, 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). Example The following example creates and sets the properties of a text field at runtime. The getCaretIndex() method is used to return the index of the caret and display its value in another text field. this.
Example /* define the function which converts the selected text in an instance, and convert the string to upper or lower case. */ function convertCase(target, menuItem) { var beginIndex:Number = Selection.getBeginIndex(); var endIndex:Number = Selection.getEndIndex(); var tempString:String; // make sure that text is actually selected. if (beginIndex>-1 && endIndex>-1) { // set the temporary string to the text before the selected text. tempString = target.text.slice(0, beginIndex); switch (menuItem.
• If a TextField object has focus, and the object has an instance name, this method returns the target path of the TextField object. Otherwise, it returns the TextField’s variable name. • If a Button object or button movie clip has focus, this method returns the target path of the Button object or button movie clip. • If neither a TextField object, Button object, Component instance, nor button movie clip has focus, this method returns null.
// statements } Selection.addListener(someListener); Listeners enable different pieces of code to cooperate because multiple listeners can receive notification about a single event. Example The following example demonstrates how to determine when input focus changes in a SWF file between several dynamically created text fields. Enter the following ActionScript into a FLA or AS file and then test the document: this.createTextField("one_txt", 1, 0, 0, 100, 22); this.
Returns If listener was successfully removed, the method returns a true value. If listener was not successfully removed—for example, if listener was not on the Selection object’s listener list— the method returns a value of false. Description Method; removes an object previously registered with Selection.addListener(). Example The following ActionScript dynamically creates several text field instances. When you select a text field, information writes to the log file.
Returns A Boolean value; true if the focus attempt is successful, false if it fails. Description Method; gives focus to the selectable (editable) text field, button, or movie clip specified by instanceName. The instancePathName parameter must be a string literal of the path to the instance. You can use dot or slash notation to specify the path. You can also use a relative or absolute path. If you are using ActionScript 2.0, you must use dot notation.
status_txt.text = "success!"; Selection.setFocus(null); return true; } See also Selection.getFocus(), Selection.onSetFocus Selection.setSelection() Availability Flash Player 5. Usage Selection.setSelection(start:Number, end:Number) : Void Parameters The beginning index of the selection span. start end The ending index of the selection span. Returns Nothing. Description Method; sets the selection span of the currently focused text field.
setProperty() CHAPTER 7 ActionScript for Flash Availability Flash Player 4. Usage setProperty(target:Object, property:Object, value/expression:Object) : Void Parameters The path to the instance name of the movie clip whose property is to be set. target property value The property to be set. The new literal value of the property. expression An equation that evaluates to the new value of the property. Returns Nothing.
CHAPTER 7 ActionScript for Flash Sound class Availability Flash Player 5. Description The Sound class lets you control sound in a movie. You can add sounds to a movie clip from the library while the movie is playing and control those sounds. If you do not specify a target when you create a new Sound object, you can use the methods to control sound for the whole movie. You must use the constructor new Sound to create a Sound object before calling the methods of the Sound class.
Event handler summary for the Sound class Event handler Description Sound.onID3 Invoked each time new ID3 data is available. Sound.onLoad Invoked when a sound loads. Sound.onSoundComplete Invoked when a sound stops playing. Constructor for the Sound class Availability Flash Player 5. Usage new Sound([target:Object]) : Sound Parameters target The movie clip instance on which the Sound object operates. This parameter is optional. Returns A reference to a Sound object.
Parameters The identifier of an exported sound in the library. The identifier is located in the Linkage Properties dialog box. idName Returns Nothing. Description Method; attaches the sound specified in the idName parameter to the specified Sound object. The sound must be in the library of the current SWF file and specified for export in the Linkage Properties dialog box. You must call Sound.start() to start playing the sound. Example The following example attaches the sound logoff_id to my_sound.
The following example loads several songs into a SWF file. A progress bar, created using the Drawing API, displays the loading progress. When the music starts and completes loading, information writes to the log file. Add the following ActionScript to your FLA or AS file. var pb_height:Number = 10; var pb_width:Number = 100; var pb:MovieClip = this.createEmptyMovieClip("progressBar_mc", this.getNextHighestDepth()); pb.createEmptyMovieClip("bar_mc", pb.getNextHighestDepth()); pb.
function updateProgressBar(the_sound:Sound):Void { var pos:Number = Math.round(the_sound.position/the_sound.duration*100); pb.bar_mc._xscale = pos; pb.vBar_mc._x = pb.bar_mc._width; pb.pos_txt.text = pos+"%"; } See Also Sound.position Sound.getBytesLoaded() Availability Flash Player 6. Usage my_sound.getBytesLoaded() : Number 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.
clearInterval(my_interval); }; my_sound.loadSound("song2.mp3", true); var my_interval:Number; my_interval = setInterval(checkProgress, 100, my_sound); function checkProgress(the_sound:Sound):Void { var pct:Number = Math.round(the_sound.getBytesLoaded()/ the_sound.getBytesTotal()*100); var pos:Number = Math.round(the_sound.position/the_sound.duration*100); status_txt.text = the_sound.getBytesLoaded()+" of "+the_sound.getBytesTotal()+" bytes ("+pct+"%)"+newline; status_txt.text += the_sound.
Parameters None. Returns An integer. Description Method; returns the pan level set in the last setPan() call as an integer from -100 (left) to 100 (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. This method is cumulative with setVolume() or setTransform(). Example The following example creates a slider bar using the Drawing API.
}; knob_mc.onRelease = function() { this.stopDrag(); var multiplier:Number = 100/(this.right-this.left)*2; var pan:Number = (this._x-this.left-(bar_width/2))*multiplier; my_sound.setPan(pan); pan_txt.text = my_sound.getPan(); }; var my_sound:Sound = new Sound(); my_sound.loadSound("song2.mp3", true); this.createTextField("pan_txt", this.getNextHighestDepth(), knob_mc._x, knob_mc._y+knob_mc._height, 20, 22); pan_txt.selectable = false; pan_txt.autoSize = "center"; pan_txt.text = my_sound.
transform_mc.createTextField("transform_txt", transform_mc.getNextHighestDepth, 0, 8, 120, 22); transform_mc.transform_txt.html = true; var knob_ll:MovieClip = transform_mc.attachMovie("knob_id", transform_mc.getNextHighestDepth(), {_x:0, _y:30}); var knob_lr:MovieClip = transform_mc.attachMovie("knob_id", transform_mc.getNextHighestDepth(), {_x:30, _y:30}); var knob_rl:MovieClip = transform_mc.attachMovie("knob_id", transform_mc.getNextHighestDepth(), {_x:60, _y:30}); var knob_rr:MovieClip = transform_mc.
function releaseKnob() { this.stopDrag(); updateTransformTxt(); } function updateTransformTxt() { var ll_num:Number = 30+100-knob_ll._y; var lr_num:Number = 30+100-knob_lr._y; var rl_num:Number = 30+100-knob_rl._y; var rr_num:Number = 30+100-knob_rr._y; my_sound.setTransform({ll:ll_num, lr:lr_num, rl:rl_num, rr:rr_num}); transform_mc.transform_txt.htmlText = ""; transform_mc.transform_txt.htmlText += ll_num+"\t"+lr_num+"\t"+rl_num+"\t"+rr_num; transform_mc.transform_txt.
knob_mc.bottom = knob_mc._y; knob_mc._x = my_sound.getVolume(); with (knob_mc) { lineStyle(0, 0x000000); beginFill(0xCCCCCC); moveTo(0, 0); lineTo(4, 0); lineTo(4, 18); lineTo(0, 18); lineTo(0, 0); endFill(); } knob_mc.createTextField("volume_txt", knob_mc.getNextHighestDepth(), knob_mc._width+4, 0, 30, 22); knob_mc.volume_txt.text = my_sound.getVolume(); knob_mc.onPress = function() { this.startDrag(false, this.left, this.top, this.right, this.bottom); this.isDragging = true; }; knob_mc.
Flash Player 6 (6.0.40.0) and later use the Sound.id3 property to support ID3 1.0 and ID3 1.1 tags. Flash Player 7 adds support for ID3 2.0 tags, specifically 2.3 and 2.4. The following table lists the standard ID3 2.0 tags and the type of content the tags represent; you query them in the format my_sound.id3.COMM, my_sound.id3.TIME, and so on. MP3 files can contain tags other than those in this table; Sound.id3 provides access to those tags as well.
Property Description TPOS Part of a set TPUB Publisher TRCK Track number/position in set TRDA Recording dates TRSN Internet radio station name TRSO Internet radio station owner TSIZ Size TSRC ISRC (international standard recording code) TSSE Software/hardware and settings used for encoding TYER Year 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.
Sound.loadSound() Availability Flash Player 6. Usage my_sound.loadSound(url:String, isStreaming:Boolean) : Void Parameters url The location on a server of an MP3 sound file. isStreaming A Boolean value that indicates whether the sound is a streaming sound (true) or an event sound (false). Returns Nothing. Description Method; loads an MP3 file into a Sound object. You can use the isStreaming parameter to indicate whether the sound is an event or a streaming sound.
Sound.onID3 Availability Flash Player 7. Usage my_sound.onID3 = function(){ // your statements here } Parameters None. Returns Nothing. Description Event handler; invoked each time new ID3 data is available for an MP3 file that you load using Sound.attachSound() or Sound.loadSound(). This handler provides access to ID3 data without polling. If both ID3 1.0 and ID3 2.0 tags are present in a file, this handler is called twice. Example The following example displays the ID3 properties of song1.
Sound.onLoad Availability Flash Player 6. Usage my_sound.onLoad = function(success:Boolean){ // your statements here } Parameters success A Boolean value of true if my_sound has been loaded successfully, false otherwise. Returns Nothing. Description Event handler; invoked automatically when a sound loads. You must create a function that executes when the this handler is invoked. You can use either an anonymous function or a named function (for an example of each, see Sound.onSoundComplete).
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. You can use either an anonymous function or a named function.
Sound.position Availability Flash Player 6. Usage my_sound.position:Number Description Read-only property; the number of milliseconds a sound has been playing. If the sound is looped, the position is reset to 0 at the beginning of each loop. Example See Sound.duration for a sample usage of this property. See Also Sound.duration Sound.setPan() Availability Flash Player 5. Usage my_sound.setPan(pan:Number) : Number Parameters An integer specifying the left-right balance for a sound.
Sound.setTransform() Availability Flash Player 5. Usage my_sound.setTransform(soundTransformObject:Object) : Void Parameters soundTransformObject An object created with the constructor for the generic Object class. Returns Nothing. Description Method; sets the sound transform (or balance) information, for a Sound object.
Mono sounds play all sound input in the left speaker and have the following transform settings by default: ll lr rr rl = = = = 100 100 0 0 Example The following example illustrates a setting that can be achieved by using setTransform(), but cannot be achieved by using setVolume() or setPan(), even if they are combined. The following code creates a new soundTransformObject object and sets its properties so that sound from both channels will play only in the left channel.
Sound.setVolume() Availability Flash Player 5. Usage my_sound.setVolume(volume:Number) : Void Parameters A number from 0 to 100 representing a volume level. 100 is full volume and 0 is no volume. The default setting is 100. volume Returns Nothing. Description Method; sets the volume for the Sound object. Example See Sound.getVolume() for a sample usage of this method. See also Sound.setPan(), Sound.setTransform() Sound.start() Availability Flash Player 5. Usage my_sound.
Example The following example creates a new Sound object, and loads a sound. Loading the sound is handled by the onLoad handler, which allows you to start the song after it’s successfully loaded. Then the sound starts playing using the start() method. Create a new FLA file, and add the following ActionScript to your FLA or AS file. For this example to work, you must have an MP3 called song1.mp3 in the same directory as your FLA or AS file. this.createTextField("status_txt", this.
Example The following example uses two buttons, stop_btn and play_btn, to control the playback of a sound that loads into a SWF file. Add two buttons to your document and add the following ActionScript to your FLA or AS file: var my_sound:Sound = new Sound(); my_sound.loadSound("song1.mp3", true); stop_btn.onRelease = function() { trace("sound stopped"); my_sound.stop(); }; play_btn.onRelease = function() { trace("sound started"); my_sound.start(); }; See also Sound.
_soundbuftime CHAPTER 7 ActionScript for Flash Availability Flash Player 4. Usage _soundbuftime:Number = integer Parameters integer The number of seconds before the SWF file starts to stream. Description Property (global); establishes the number of seconds of streaming sound to buffer. The default value is 5 seconds. Example The following example streams an MP3 file and buffers the sound before it plays for the user. Two text fields are created at runtime to hold a timer and debugging information.
CHAPTER 7 ActionScript for Flash 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. In Flex, use the Application class rather than the Stage class. Method summary for the Stage class Method Description Stage.
Returns Nothing. Description Method; detects when a SWF file is resized (but only if Stage.scaleMode = "noScale"). The addListener() method doesn’t work with the default movie clip scaling setting (showAll) or other scaling settings (exactFit and noBorder). To use addListener(), you must first create a listener object. Stage listener objects receive notification from Stage.onResize. Example This example creates a new listener object called stageListener.
Value Vertical Horizontal "TL" top left "TR" top right "BL" bottom left "BR" bottom right Example The following example demonstrates different alignments of the SWF file. Add a ComboBox instance to your document with the instance name stageAlign_cb. Add the following ActionScript to your FLA or AS file: var stageAlign_cb:mx.controls.ComboBox; stageAlign_cb.dataProvider = ['T', 'B', 'L', 'R', 'TL', 'TR', 'BL', 'BR']; var cbListener:Object = new Object(); cbListener.
Stage.scaleMode = "noScale"; Stage.addListener(stageListener); See also Stage.align, Stage.scaleMode, Stage.width Stage.onResize Availability Flash Player 6. Usage myListener.onResize = function(){ // your statements here } Parameters None. Returns Nothing. Description Listener; invoked when Stage.scaleMode is set to noScale and the SWF file is resized. You can use this event handler to write a function that lays out the objects on the Stage when a SWF file is resized.
Parameters myListener An object added to an object’s callback list with addListener(). Returns A Boolean value. Description Method; removes a listener object created with addListener(). See also Stage.addListener() Stage.scaleMode Availability Flash Player 6. Usage Stage.scaleMode:String Description Property; indicates the current scaling of the SWF file within Flash Player. The scaleMode property forces the SWF file into a specific scaling mode.
Description Property; specifies whether to show or hide the default items in the Flash Player context menu. If showMenu is set to true (the default), all context menu items appear. If showMenu is set to false, only Settings and About Macromedia Flash Player items appear. Example The following example creates a clickable text link that lets the user enable and disable the Flash Player context menu. this.createTextField("showMenu_txt", this.getNextHighestDepth(), 10, 10, 100, 22); showMenu_txt.
stageListener.onResize = function() { stageSize_txt.text = "w:"+Stage.width+", h:"+Stage.height; }; Stage.scaleMode = "noScale"; Stage.addListener(stageListener); See also Stage.align, Stage.height, Stage.
startDrag() CHAPTER 7 ActionScript for Flash Availability Flash Player 4. Usage startDrag(target:Object,[lock:Boolean, left:Number, top:Number, right:Number, bottom:Number]) : Void Parameters target The target path of the movie clip to drag. A Boolean value specifying whether the draggable movie clip is locked to the center of the mouse position (true) or locked to the point where the user first clicked the movie clip (false). This parameter is optional.
stop() CHAPTER 7 ActionScript for Flash Availability Flash 2. Usage stop() Parameters None. Returns Nothing. Description Function; stops the SWF file that is currently playing. The most common use of this action is to control movie clips with buttons. See also MovieClip.
stopAllSounds() CHAPTER 7 ActionScript for Flash Availability Flash Player 3. Usage stopAllSounds() : Void 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 in which they are located. Example The following code creates a text field, in which the song’s ID3 information appears.
stopDrag() CHAPTER 7 ActionScript for Flash Availability Flash Player 4. Usage stopDrag() : Void Parameters None. Returns Nothing. Description Function; stops the current drag operation. Example The following code, placed in the main Timeline, stops the drag action on the movie clip instance my_mc when the user releases the mouse button: my_mc.onPress = function () { startDrag(this); } my_mc.onRelease = function() { stopDrag(); } See also MovieClip._droptarget, MovieClip.
targetPath() CHAPTER 7 ActionScript for Flash Availability Flash Player 5. Usage targetpath(movieClipObject:MovieClip) : String Parameters movieClipObject Reference (for example, _root or _parent) to the movie clip for which the target path is being retrieved. Returns A string containing the target path of the specified movie clip. Description Function; returns a string containing the target path of movieClipObject. The target path is returned in dot (.) notation.
CHAPTER 7 ActionScript for Flash TextField class Availability Flash Player 6. Description You can use the TextField class to perform low-level text rendering. However, in Flex, you typically use the Label, Text, TextArea, and TextInput controls to process text. All dynamic and input text fields in a SWF file are instances of the TextField class. The TextField class inherits from the Object class. To create a text field dynamically, you do not use the new operator. Instead, you use MovieClip.
Property Description TextField.border Indicates if the text field has a border. TextField.borderColor Indicates the color of the border. TextField.bottomScroll Read-only; the bottommost visible line in a text field. 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 affects only the bounding box of the text field; it does not affect the border thickness or text font size.
Property Description TextField.textHeight The height of the text field’s bounding box. TextField.textWidth The width of the text field’s bounding box. TextField.type Indicates whether a text field is an input text field or dynamic text field. TextField._url Read-only; the URL of the SWF file that created the text field instance. TextField.variable The variable name associated with the text field. TextField.
TextField.addListener() Availability Flash Player 6. Usage my_txt.addListener(listener:Object) : Void Parameters listener An object with an onChanged or onScroller event handler. Returns Nothing. Description Method; registers an object to receive notification when the onChanged and onScroller event handlers have been invoked. When a text field changes or is scrolled, the TextField.onChanged and TextField.
}; my_txt.addListener(txtListener); See also TextField.onChanged, TextField.onScroller, TextField.removeListener() TextField._alpha Availability Flash Player 6. Usage my_txt._alpha:Number Description Property; sets or retrieves the alpha transparency value of the text field specified by my_txt. Valid values are 0 (fully transparent) to 100 (fully opaque). The default value is 100. Transparency values are not supported for text files that use device fonts.
The values of autoSize and TextField.wordWrap determine whether a text field expands or contracts to the left side, right side, or bottom side. The default value for each of these properties is false. If autoSize is set to "none" (the default) or false, then no resizing will occur. If autoSize is set to "left" or true, then the text is treated as left-justified text, meaning the left side of the text field will remain fixed and any resizing of a single line text field will be on the right side.
// define a function that executes when a user clicks the mouse myMouseListener.onMouseDown = function() { left_txt.autoSize = "left"; left_txt.text = "This is much longer text"; center_txt.autoSize = "center"; center_txt.text = "This is much longer text"; right_txt.autoSize = "right"; right_txt.text = "This is much longer text"; true_txt.autoSize = true; true_txt.text = "This is much longer text"; false_txt.autoSize = false; false_txt.
Description Property; the color of the text field background. Default is 0xFFFFFF (white). This property may be retrieved or set, even if there currently is no background, but the color is only visible if the text field has a border. Example See the example for TextField.background. See also TextField.background TextField.border Availability Flash Player 6. Usage my_txt.border:Boolean Description Property; if true, the text field has a border. If false, the text field has no border.
my_txt.borderColor = 0x00FF00; my_txt.text = "Lorum ipsum"; See also TextField.border TextField.bottomScroll Availability Flash Player 6. Usage my_txt.bottomScroll:Number Description Read-only property; an integer (one-based index) that indicates the bottommost line that is currently visible in my_txt. Think of the text field as a “window” onto a block of text. The property TextField.scroll is the one-based index of the topmost visible line in the window. All the text between lines TextField.
Description Property; a Boolean value that specifies whether extra white space (spaces, line breaks, and so on) in an HTML text field should be removed when the field is rendered in a browser. The default value is false. If you set this value to true, you must use standard HTML commands such as
and
to place line breaks in the text field. If my_txt.html is false, this property is ignored. Example The following example creates two text fields, called first_txt and second_txt.
Example In this example, you need to create a dynamic text field called my_txt, and then use the following ActionScript to embed fonts and rotate the text field. The reference to my font refers to a Font symbol in the library, with linkage set to my font. var my_fmt:TextFormat = new TextFormat(); my_fmt.font = "my font"; this.createTextField("my_txt", this.getNextHighestDepth(), 10, 10, 160, 120); my_txt.wordWrap = true; my_txt.embedFonts = true; my_txt.text = "Hello world"; my_txt.
TextField.getFontList() Availability Flash Player 6. Usage TextField.getFontList() : Array Parameters None. Returns An array. Description Method; a static method of the global TextField class. You don’t specify a specific text field (such as my_txt) when you call this method. This method returns names of fonts on the player’s host system as an array. (It does not return names of all fonts in currently loaded SWF files.) The names are of type String.
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 replaceSel() method or text entered by a user, receives. When getNewTextFormat() is invoked, the TextFormat object returned has all of its properties defined. No property is null. Example The following example displays the specified text field’s (my_txt) text format object. this.
Example The following ActionScript traces all of the formatting information for a text field that is created at runtime. this.createTextField("dyn_txt", this.getNextHighestDepth(), 0, 0, 100, 200); dyn_txt.text = "Frank"; dyn_txt.setTextFormat(new TextFormat()); var my_fmt:TextFormat = dyn_txt.getTextFormat(); for (var prop in my_fmt) { trace(prop+": "+my_fmt[prop]); } See also TextField.getNewTextFormat(), TextField.setNewTextFormat(), TextField.setTextFormat() TextField.
Horizontal scrolling is measured in pixels because most fonts you typically use are proportionally spaced; meaning, the characters can have different widths. Flash performs vertical scrolling by line because users usually want to see a line of text in its entirety, as opposed to seeing a partial line. Even if there are multiple fonts on a line, the height of the line adjusts to fit the largest font in use. Note: The hscroll property is zero-based—not one-based like the vertical scrolling property TextField.
Example The following example creates a text field that sets the html property to true. HTML-formatted text displays in the text field. this.createTextField("my_txt", this.getNextHighestDepth(), 10, 10, 160, 22); my_txt.html = true; my_txt.htmlText = " this is bold text "; See also TextField.htmlText TextField.htmlText Availability Flash Player 6. Usage my_txt.
Example The following example outputs the number of characters in the date_txt text field, which displays the current date. var today:Date = new Date(); this.createTextField("date_txt", this.getNextHighestDepth(), 10, 10, 100, 22); date_txt.autoSize = true; date_txt.text = today.toString(); trace(date_txt.length); TextField.maxChars Availability Flash Player 6. Usage my_txt.maxChars:Number Description Property; indicates the maximum number of characters that the text field can contain.
TextField.maxscroll Availability Flash Player 6. Usage TextField.maxscroll:Number Description Read-only property; indicates the maximum value of TextField.scroll. Example The following example sets the maximum value for the scrolling text field my_txt. Create two buttons, scrollUp_btn and scrollDown_btn, to scroll the text field. Add the following ActionScript to your FLA or AS file. this.createTextField("scroll_txt", this.getNextHighestDepth(), 10, 10, 160, 20); this.createTextField("my_txt", this.
This property works only with selectable (editable) text fields; it has no effect on nonselectable text fields. In Flex, only top-level components in the application can have context menus. For example, if a DataGrid control is a child of a TabNavigator or VBox container, the DataGrid control cannot have its own context menu. Example The following example assigns the ContextMenu object menu_cm to the text field news_txt.
Example The following example creates two text fields. The scrollable_txt field has the mouseWheelEnabled property set to true, so scrollable_txt scrolls when you click the field and roll the mouse wheel. The nonscrollable_txt field does not scroll if you click the field and roll the mouse wheel. var font_array:Array = TextField.getFontList().sort(); this.createTextField("scrollable_txt", this.getNextHighestDepth(), 10, 10, 240, 320); scrollable_txt.border = true; scrollable_txt.
TextField._name Availability Flash Player 6. Usage my_txt._name:String Description Property; the instance name of the text field specified by my_txt. Example The following example demonstrates text fields residing at different depths. Add the following ActionScript to your FLA or AS file, which dynamically creates two text fields at runtime and displays their depths in the Output panel. this.createTextField("first_mc", this.getNextHighestDepth(), 10, 10, 100, 22); this.createTextField("second_mc", this.
A reference to the text field instance is passed as a parameter to the onChanged handler. You can capture this data by putting a parameter in the event handler method. For example, the following code uses textfield_txt as the parameter that is passed to the onChanged event handler. The parameter is then used in a trace() method to write the instance name of the text field to the log file: this.createTextField("myInputText_txt", 99, 10, 10, 300, 20); myInputText_txt.border = true; myInputText_txt.
second_txt.border = true; second_txt.type = "input"; first_txt.onKillFocus = function(newFocus:Object) { trace(this._name+" lost focus. New focus changed to: "+newFocus._name); }; first_txt.onSetFocus = function(oldFocus:Object) { trace(this._name+" gained focus. Old focus changed from: "+oldFocus._name); } See Also TextField.onSetFocus TextField.onScroller Availability Flash Player 6. Usage my_txt.onScroller = function(textFieldInstance:TextField){ // your statements here } myListenerObj.
onScroller is called whether the scroll position changed because of a users interaction with the text field, or programmatic changes. The onChanged handler fires only if a user interaction causes the change. These two options are necessary because often one piece of code changes the scrolling position, while the scroll bar code is unrelated and won't know that the scroll position changed without being notified.
Returns Nothing. Description Event handler; invoked when a text field receives keyboard focus. The oldFocus parameter is the 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, oldFocus contains the text field instance. If there is no previously focused object, oldFocus contains a null value. Example See the example for TextField.onKillFocus. See Also TextField.onKillFocus TextField._parent Availability Flash Player 6.
The following information writes to the log file: first_txt's _parent is: _level0 second_txt's _parent is: _level0.holder_mc See also MovieClip._parent, _root, targetPath() TextField.password Availability Flash Player 6. Usage my_txt.password:Boolean Description Property; if the value of password is true, the text field is a password text field and hides the input characters using asterisks instead of the actual characters. If false, the text field is not a password text field.
TextField._quality Availability Flash Player 6. Usage my_txt._quality:String Description Property (global); sets or retrieves the rendering quality used for a SWF file. Device fonts are always aliased and, therefore, are unaffected by the _quality property. Note: Although you can specify this property for a TextField object, it is actually a global property, and you can specify its value simply as _quality. TextField.removeListener() Availability Flash Player 6. Usage my_txt.
txtListener.onChanged = function(textfield_txt:TextField) { trace(textfield_txt+" changed. Current length is: "+textfield_txt.length); }; my_txt.addListener(txtListener); removeListener_btn.onRelease = function() { trace("Removing listener..."); if (!my_txt.removeListener(txtListener)) { trace("Error! Unable to remove listener"); } }; TextField.removeTextField() Availability Flash Player 6. Usage my_txt.removeTextField() : Void Description Method; removes the text field specified by my_txt.
Returns Nothing. Description Method; replaces the current selection with the contents of the text parameter. The text is inserted at the position of the current selection, using the current default character format and default paragraph format. The text is not treated as HTML, even if the text field is an HTML text field. You can use the replaceSel() method to insert and delete text without disrupting the character and paragraph formatting of the rest of the text. You must use Selection.
Description Method; replaces a range of characters, specified by the beginIndex and endIndex parameters, in the specified text field with the contents of the text parameter. Example The following example creates a text field called my_txt and assigns the text dog@house.net to the field. The indexOf() method is used to find the first occurrence of the specified symbol (@). If the symbol is found, the specified text (between the index of 0 and the symbol) replaces with the string bird.
The following example includes all characters, but excludes lowercase letters: my_txt.restrict = "^a-z"; You can use a backslash to enter a ^ or - verbatim. The accepted backslash sequences are \-, \^ or \\. The backslash must be an actual character in the string, so when specified in ActionScript, a double backslash must be used. For example, the following code includes only the dash (-) and caret (^): my_txt.
Apply additional formatting for the text field using the TextFormat class. See also MovieClip._rotation TextField.scroll Availability Flash Player 6. Usage my_txt.scroll Description Property; defines the vertical position of text in a text field. The scroll property is useful for directing users to a specific paragraph in a long passage, or creating scrolling text fields. This property can be retrieved and modified.
TextField.selectable Availability Flash Player 6. Usage my_txt.selectable:Boolean Description Property; a Boolean value that indicates whether the text field is selectable. The value true indicates that the text is selectable. The selectable property controls whether a text field is selectable, and not whether a text field is editable. A dynamic text field can be selectable even if it's not editable. If a dynamic text field is not selectable, that means you cannot select its text.
Description Method; sets the default new text format of a text field; that is, the text format to be used for newly inserted text, such as text inserted with the replaceSel() method or text entered by a user. When text is inserted, the newly inserted text is assigned the default new text format. The new default text format is specified by textFormat, which is a TextFormat object. Example In the following example, a new text field (called my_txt) is created at runtime and several properties are set.
Description Method; applies the text formatting specified by textFormat to some or all of the text in a text field. textFormat must be a TextFormat object that specifies the text formatting changes desired. Only the non-null properties of textFormat are applied to the text field. Any property of textFormat that is set to null will not be applied. By default, all of the properties of a newly created TextFormat object are set to null.
See also TextField.setNewTextFormat(), TextFormat class TextField.styleSheet Availability Flash Player 7. Usage my_txt.styleSheet = TextField StyleSheet Description Property; attaches a style sheet to the text field specified by my_txt. For information on creating style sheets, see the TextField.StyleSheet class entry. The style sheet associated with a text field may be changed at any time. If the style sheet in use is changed, the text field is redrawn using the new style sheet.
css2_btn.onRelease = function() { var styleObj:TextField.StyleSheet = new TextField.StyleSheet(); styleObj.onLoad = function(success:Boolean) { if (success) { news_txt.styleSheet = styleObj; news_txt.htmlText = newsText; } }; styleObj.load("styles2.css"); }; clearCss_btn.onRelease = function() { news_txt.styleSheet = undefined; news_txt.htmlText = newsText; }; The following styles are applied to the text field.
TextField.tabEnabled Availability Flash Player 6. Usage my_txt.tabEnabled:Boolean Description Property; specifies whether my_txt is included in automatic tab ordering. It is undefined by default. If the tabEnabled property is undefined or true, the object is included in automatic tab ordering. If the tabIndex property is also set to a value, the object is included in custom tab ordering as well.
Parameters None. Returns Nothing. 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 undefined by default. If any currently displayed object in the SWF file contains a tabIndex property, automatic tab ordering is disabled, and the tab ordering is calculated from the tabIndex properties of objects in the SWF file.
TextField._target Availability Flash Player 6. Usage my_txt._target:String Description Read-only property; the target path of the text field instance specified by my_txt. The _self target specifies the current frame in the current window, _blank specifies a new window, _parent specifies the parent of the current frame, and _top specifies the top-level frame in the current window.
htmlText:
Remember to always update your help panel.
text: Remember to always update your help panel. */ See also TextField.htmlText TextField.textColor Availability Flash Player 6. Usage my_txt.textColor:Number Description Property; indicates the color of the text in a text field. The hexadecimal color system uses six digits to represent color values. Each digit has sixteen possible values or characters.trace("after my_txt.autoSize = true;"); trace("_height: "+my_txt._height+", _width: "+my_txt._width); Which outputs the following information: textHeight: 15, textWidth: 56 _height: 300, _width: 100 after my_txt.autoSize = true; _height: 19, _width: 60 See Also TextField.textWidth TextField.textWidth Availability Flash Player 6. Usage my_txt.textWidth:Number Description Property; indicates the width of the text. Example See the example for TextField.textHeight. See Also TextField.textHeight TextField.
username_txt.border = true; username_txt.type = "input"; username_txt.maxChars = 16; username_txt.text = "hello"; this.createTextField("password_txt", this.getNextHighestDepth(), 10, 40, 100, 22); password_txt.border = true; password_txt.type = "input"; password_txt.maxChars = 16; password_txt.password = true; password_txt.text = "world"; TextField._url Availability Flash Player 6. Usage my_txt._url:String Description Read-only property; retrieves the URL of the SWF file that created the text field.
Description Property; The name of the variable that the text field is associated with. The type of this property is String. Example The following example creates a text field called my_txt and associates the variable today_date with the text field. When you change the variable today_date, then the text that displays in my_txt updates. this.createTextField("my_txt", 1, 10, 10, 200, 22); my_txt.
TextField._width Availability Flash Player 6. Usage my_txt._width:Number Description Property; the width of the text field, in pixels. Example The following example creates two text fields that you can use to change the width and height of a third text field on the Stage. Add the following ActionScript to a FLA or AS file. this.createTextField("my_txt", this.getNextHighestDepth(), 10, 40, 160, 120); my_txt.background = true; my_txt.backgroundColor = 0xFF0000; my_txt.border = true; my_txt.
TextField.wordWrap Availability Flash Player 6. Usage my_txt.wordWrap:Boolean Description Property; a Boolean value that indicates if the text field has word wrap. If the value of wordWrap is true, the text field has word wrap; if the value is false, the text field does not have word wrap. Example The following example demonstrates how wordWrap affects long text in a text field that’s created at runtime. this.createTextField("my_txt", 99, 10, 10, 100, 200); my_txt.
coords_txt.border = true; var mouseListener:Object = new Object(); mouseListener.onMouseDown = function() { coords_txt.text = "X:"+Math.round(_xmouse)+", Y:"+Math.round(_ymouse); coords_txt._x = _xmouse; coords_txt._y = _ymouse; }; Mouse.addListener(mouseListener); See also TextField._xscale, TextField._y, TextField._yscale TextField._xmouse Availability Flash Player 6. Usage my_txt._xmouse:Number Description Read-only property; returns the x coordinate of the mouse position relative to the text field.
TextField._xscale Availability Flash Player 6. Usage my_txt._xscale:Number Description Property; determines the horizontal scale of the text field as applied from the registration point of the text field, expressed as a percentage. The default registration point is (0,0). Example The following example scales the my_txt instance when you click the scaleUp_btn and scaleDown_btn instances. this.createTextField("my_txt", 99, 10, 40, 100, 22); my_txt.autoSize = true; my_txt.border = true; my_txt.
Example See the example for TextField._x. See also TextField._x, TextField._xscale, TextField._yscale TextField._ymouse Availability Flash Player 6. Usage my_txt._ymouse:Number Description Read-only property; indicates the y coordinate of the mouse position relative to the text field. Example See the example for TextField._xmouse. See also TextField._xmouse TextField._yscale Availability Flash Player 6. Usage my_txt.
CHAPTER 7 ActionScript for Flash TextField.StyleSheet class Availability Flash Player 7. Description You can use the TextField.StyleSheet class to perform low-level text rendering. However, in Flex, you typically use the Label, Text, TextArea, and TextInput controls to process text. 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.
Returns A reference to a TextField.StyleSheet object. Description Constructor; creates a TextField.StyleSheet object. Example The following example loads in a style sheet and outputs the styles that load into the document. Add the following ActionScript to your AS or FLA file: var my_styleSheet:TextField.StyleSheet = new TextField.StyleSheet(); my_styleSheet.onLoad = function(success:Boolean) { if (success) { trace("Styles loaded:"); var styles_array:Array = my_styleSheet.
Example The following example loads a style sheet called styles.css into a SWF file, and writes the styles that are loaded to the log file. When you click clear_btn, all styles from the my_styleSheet object are removed. // Create a new style sheet object var my_styleSheet:TextField.StyleSheet = new TextField.StyleSheet(); my_styleSheet.onLoad = function(success:Boolean) { if (success) { trace("Styles loaded."); var styles_array:Array = my_styleSheet.getStyleNames(); for (var i = 0; i
Example The following example loads styles from a CSS file, parses the stylesheet and writes style names and property values to the log file. Create a new ActionScript file called StyleSheetTracer.as and enter the following code: import TextField.StyleSheet; class StyleSheetTracer { // StyleSheetTracer.displayFromURL // // This method displays the CSS style sheet at // URL "url" to the Output Panel.
font-family: Arial, Helvetica, sans-serif; font-size: 12px; font-weight: normal; } And finally, in a FLA or AS file, enter the following ActionScript to load the external style sheet, styles.css. StyleSheetTracer.displayFromURL("styles.css"); This writes the following information to the log file: Style .heading: fontWeight: bold fontSize: 24px fontFamily: Arial, Helvetica, sans-serif Style .mainBody: fontWeight: normal fontSize: 12px fontFamily: Arial, Helvetica, sans-serif See also TextField.StyleSheet.
var names_array:Array = my_styleSheet.getStyleNames(); trace(names_array.join("\n")); The following information is written to the log file: bodyText heading See also TextField.StyleSheet.getStyle() TextField.StyleSheet.load() Availability Flash Player 7. Usage styleSheet.load(url:String) : Void 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. url Returns Nothing.
news_txt.styleSheet = my_styleSheet; news_txt.htmlText = "
Heading goes here!
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.
"; } }; my_styleSheet.load("styles.css"); For the code contained in styles.css, see the entry for TextField.StyleSheet.getStyle(). See also TextField.StyleSheet.onLoad TextField.StyleSheet.onLoad Availability Flash Player 7.news_txt.htmlText = "
Heading goes here!
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.
"; } }; my_styleSheet.load("styles.css"); For the code contained in styles.css, see the entry for TextField.StyleSheet.getStyle(). For an example of asynchronously loading style sheets using ActionScript 2.0, see the entry for TextField.StyleSheet.getStyle().// function dumpStyles(styles:TextField.StyleSheet):Void { var styleNames_array:Array = styles.getStyleNames(); for (var i = 0; i
my_styleSheet.setStyle("emphasized", styleObj); delete styleObj; var styleNames_array:Array = my_styleSheet.getStyleNames(); for (var i=0;i
Example The following code subclasses this method: class advCSS extends TextField.StyleSheet { // override the transform method function transform(style:Object):TextFormat { for (var z in style) { if (z == "margin") { style.marginLeft = style[z]; style.marginRight = style[z]; delete style[z]; break; } } return super.transform(style); } } // end class definition TextField.StyleSheet.
CHAPTER 7 ActionScript for Flash TextFormat class Availability Flash Player 6. Description The TextFormat class represents character formatting information. You must use the constructor new TextFormat() to create a TextFormat object before calling its methods. You can set TextFormat parameters to null to indicate that they are undefined. When you apply a TextFormat object to a text field using TextField.setTextFormat(), only its defined properties are applied, as in the following example: this.
Property Description TextFormat.indent Indicates the indentation from the left margin to the first character in the paragraph. TextFormat.italic Indicates whether text is italicized. TextFormat.leading Indicates the amount of vertical space (called leading) between lines. TextFormat.leftMargin Indicates the left margin of the paragraph, in points. TextFormat.rightMargin Indicates the right margin of the paragraph, in points. TextFormat.size Indicates the point size of text. TextFormat.
leftMargin rightMargin Indicates the left margin of the paragraph, in points. Indicates the right margin of the paragraph, in points. indent An integer that indicates the indentation from the left margin to the first character in the paragraph. leading A number that indicates the amount of leading vertical space between lines. Returns A reference to a TextFormat object. Description Constructor; creates a TextFormat object with the specified properties.
Example The following example creates a text field with a border and uses TextFormat.align to center the text. var my_fmt:TextFormat = new TextFormat(); my_fmt.align = "center"; this.createTextField("my_txt", 1, 100, 100, 300, 100); my_txt.multiline = true; my_txt.wordWrap = true; my_txt.border = true; my_txt.text = "this is my first test field object text"; my_txt.setTextFormat(my_fmt); TextFormat.blockIndent Availability Flash Player 6. Usage my_fmt.
Description Property; a Boolean value that specifies whether the text is boldface. The default value is null, which indicates that the property is undefined. If the value is true, then the text is boldface. Example The following example creates a text field that includes characters in boldface. var my_fmt:TextFormat = new TextFormat(); my_fmt.bold = true; this.createTextField("my_txt", 1, 100, 100, 300, 100); my_txt.multiline = true; my_txt.wordWrap = true; my_txt.border = true; my_txt.
TextFormat.color Availability Flash Player 6. Usage my_fmt.color:Number Description Property; indicates the color of text. A number containing three 8-bit RGB components; for example, 0xFF0000 is red, and 0x00FF00 is green. Example The following example creates a text field and sets the text color to red. var my_fmt:TextFormat = new TextFormat(); my_fmt.blockIndent = 20; my_fmt.color = 0xFF0000; // hex value for red this.createTextField("my_txt", 1, 100, 100, 300, 100); my_txt.multiline = true; my_txt.
TextFormat.getTextExtent() Availability Flash Player 6. The optional width parameter is supported in Flash Player 7. Usage my_fmt.getTextExtent(text:String, [width:Number]) : Object Parameters text A string. An optional number that represents the width, in pixels, at which the specified text should wrap. width Returns An object with the properties width, height, ascent, descent, textFieldHeight, textFieldWidth.
The following figure illustrates these measurements. When setting up your TextFormat object, set all the attributes exactly as they will be set for the creation of the text field, including font name, font size, and leading. The default value for leading is 2. Example This example creates a single-line text field that’s just big enough to display a text string using the specified formatting. var my_str:String = "Small string"; // Create a TextFormat object, // and apply its properties.
// Create a TextFormat object. var my_fmt:TextFormat = new TextFormat(); // Specify formatting properties for the TextFormat object: my_fmt.font = "Arial"; my_fmt.bold = true; my_fmt.leading = 4; // The string of text to be displayed var textToDisplay:String = "Macromedia Flash Player 7, now with improved text metrics."; // Obtain text measurement information for the string, // wrapped at 100 pixels. var metrics:Object = my_fmt.
TextFormat.italic Availability Flash Player 6. Usage my_fmt.italic:Boolean Description Property; a Boolean value that indicates whether text in this text format is italicized. The default value is null, which indicates that the property is undefined. Example The following example creates a text field and sets the text style to italic. this.createTextField("mytext",1,100,100,100,100); mytext.multiline = true; mytext.wordWrap = true; mytext.
TextFormat.leftMargin Availability Flash Player 6. Usage my_fmt.leftMargin:Number Description Property; the left margin of the paragraph, in points. The default value is null, which indicates that the property is undefined. Example The following example creates a text field and sets the left margin to 20 points. this.createTextField("mytext",1,100,100,100,100); mytext.multiline = true; mytext.wordWrap = true; mytext.border = true; var myformat:TextFormat = new TextFormat(); myformat.
TextFormat.size Availability Flash Player 6. Usage my_fmt.size:Number Description Property; the point size of text in this text format. The default value is null, which indicates that the property is undefined. Example The following example creates a text field and sets the text size to 20 points. this.createTextField("mytext",1,100,100,100,100); mytext.multiline = true; mytext.wordWrap = true; mytext.border = true; var myformat:TextFormat = new TextFormat(); myformat.size = 20; mytext.
this.createTextField("mytext2",2,100,220,200,100); mytext2.multiline = true; mytext2.wordWrap = true; mytext2.border = true; var myformat2:TextFormat = new TextFormat(); myformat2.tabStops = [40,80,120,160]; mytext2.text ="ABCD"; mytext2.setTextFormat(myformat2); TextFormat.target Availability Flash Player 6. Usage my_fmt.target:String Description Property; indicates the target window where the hyperlink is displayed.
Description Property; a Boolean value that indicates whether the text that uses this text format is underlined (true) or not (false). This underlining is similar to that produced by the tag, but the latter is not “true” underlining, because it does not skip descenders correctly. The default value is null, which indicates that the property is undefined. Example The following example creates a text field and sets the text style to underline. this.createTextField("mytext",1,100,100,200,100); mytext.
CHAPTER 7 ActionScript for Flash 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. You don’t use a constructor to create a TextSnapshot object; it is returned by MovieClip.
textToFind A string specifying the text to search for. If you specify a string literal instead of a variable of type String, enclose the string in quotation marks. A Boolean value specifying whether the text in my_snap must match the case of the string in textToFind. caseSensitive Returns The zero-based index position of the first occurrence of the specified text, or -1.
Example The following example illustrates how you can output the number of characters in a specified TextSnapshot object. To use this code, create a static text field that contains the text “TextSnapshot Example”. // this example assumes that the movie clip contains // the static text "TextSnapshot Example" var my_mc:MovieClip = this; var my_snap:TextSnapshot = my_mc.getTextSnapshot(); var count:Number = my_snap.getCount(); var theText:String = my_snap.
Example The following example illustrates how to use this method. To use this code, create a static text field that contains the text “TextSnapshot Example”. // This example assumes that the movie clip contains // the static text "TextSnapshot Example" var my_mc:MovieClip = this; var my_snap:TextSnapshot = my_mc.getTextSnapshot(); var count:Number = my_snap.getCount(); var theText:String = my_snap.
TextSnapshot.getText() 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.getText(from:Number, to:Number [, includeLineEndings:Boolean ] ) : String Parameters An integer that indicates the position of the first character of my_snap to be included in the returned string. Valid values for from are 0 through TextSnapshot.getCount() - 1. If from is a negative value, 0 is used.
trace(count); // output: 20 trace(theText); // output: TextSnapshot Example See also TextSnapshot.getSelectedText() 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:Number, y:Number [, maxDistance:Number] ) : Number Parameters x A number that represents the x coordinate of the movie clip containing the text in my_snap.
Example The following example illustrates how to use this method. To use this code, place a static text field containing the text “TextSnapshot Example” on the Stage. To test the code, move the pointer over the static text field. Note: If characters don’t appear to be selected when you run the code, you must also place a dynamic text field on the Stage. See “Description” in this entry.
Example The following example illustrates how to use this method. To use this code, place a static text field containing the text “TextSnapshot Example” on the Stage. Add the following ActionScript to your AS or FLA file. Note: If characters don’t appear to be selected when you run the code, you must also place a dynamic text field on the Stage. See “Description” in this entry. // This example assumes that the movie clip contains // the static text "TextSnapshot Example" var my_snap:TextSnapshot = this.
Description Method; specifies a range of characters in a TextSnapshot object to be selected or deselected. Characters that are selected are drawn with a colored rectangle behind them, matching the bounding box of the character. The color of the bounding box is defined by TextSnapshot.setSelectColor(). To select or deselect all characters, pass a value of 0 for from and TextSnapshot.getCount() (or any very large number) for to. To specify a single character, pass a value of from+1 for to.
unloadMovie() CHAPTER 7 ActionScript for Flash Availability Flash Player 3. Usage unloadMovie(target:MovieClip) : Void unloadMovie(target:String) : Void Parameters target The target path of a movie clip. Returns None. Description Function; removes a movie clip that was loaded by means of loadMovie() from Flash Player. To unload a movie clip that was loaded by means of loadMovieNum(), use unloadMovieNum() instead of unloadMovie().
unloadMovieNum() CHAPTER 7 ActionScript for Flash Availability Flash Player 3. Usage unloadMovieNum(level:Number) : Void Parameters level The level (_levelN) of a loaded movie. Returns Nothing. Description Function; removes a SWF or image that was loaded by means of loadMovieNum() from Flash Player. To unload a SWF or image that was loaded with MovieClip.loadMovie(), use unloadMovie() instead of unloadMovieNum(). Example The following example loads an image into a SWF file.
updateAfterEvent() CHAPTER 7 ActionScript for Flash Availability Flash Player 5. Usage updateAfterEvent() : Void 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 onClipEvent() handler or as part of a function or method that you pass to setInterval(). Flash ignores calls to updateAfterEvent that are not within an onClipEvent() handler or part of a function or method passed to setInterval().
CHAPTER 7 ActionScript for Flash Video class Availability Flash Player 6; the ability to play Flash Video (FLV) files was added in Flash Player 7. Description The Video class lets you display live streaming video on the Stage without embedding it in your SWF file. You capture the video by using Camera.get(). In files published for Flash Player 7 and later, you can also use the Video class to play back Flash Video (FLV) files over HTTP or from the local file system.
Returns Nothing. Description Method; specifies a video stream (source) to be displayed within the boundaries of the Video object on the Stage. The video stream is either an FLV file being displayed by means of the NetStream.play() command, a Camera object, or null. If source is null, video is no longer played within the Video object. You don’t have to use this method if the FLV file contains only audio; the audio portion of an FLV files is played automatically when the NetStream.play() command is issued.
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. Example The following example pauses and clears video1.flv that is playing in a Video object (called my_video) when the user clicks the pause_btn instance. var pause_btn:Button; var my_video:Video; // my_video is a Video object on the Stage var my_nc:NetConnection = new NetConnection(); my_nc.
var my_video:Video; // my_video is a Video object on the Stage var my_nc:NetConnection = new NetConnection(); my_nc.connect(null); var my_ns:NetStream = new NetStream(my_nc); my_video.attachVideo(my_ns); my_ns.play("video1.flv"); deblocking_cb.addItem({data:0, label:'Auto'}); deblocking_cb.addItem({data:1, label:'No'}); deblocking_cb.addItem({data:2, label:'Yes'}); var cbListener:Object = new Object(); cbListener.change = function(evt:Object) { my_video.deblocking = evt.target.selectedItem.
my_mc._width = my_mc.my_video.width; my_mc._height = my_mc.my_video.height; break; } }; Usage 2: The following example lets the user press a button to set the height and width of a video stream being displayed in the Flash Player to be the same as the height and width at which the video stream was captured. var my_nc:NetConnection = new NetConnection(); my_nc.connect(null); var my_ns:NetStream = new NetStream(my_nc); my_mc.my_video.attachVideo(my_ns); my_ns.play("video1.flv"); resize_btn.
}; smoothing_btn.onRelease = function() { my_video.smoothing = !my_video.smoothing; updateSmoothing(); }; function updateSmoothing():Void { smoothing_txt.text = "smoothing = "+my_video.smoothing; } Video.width Availability Flash Player 6. Usage my_video.width:Number Description Property (read-only); an integer specifying the width of the video stream, in pixels. For live streams, this value is the same as the Camera.width property of the Camera object that is capturing the video stream.
Chapter 7: ActionScript for Flash
APPENDIX A Deprecated Flash 4 operators The following table lists Flash 4-only operators, which are deprecated in ActionScript 2.0. Do not use these operators unless you are publishing to Flash Player 4 and earlier.
Appendix A: Deprecated Flash 4 operators
APPENDIX B Keyboard Keys and Key Code Values The following tables list all the keys on a standard keyboard and the corresponding ASCII key code values that are used to identify the keys in ActionScript: • • • • “Letters A to Z and standard numbers 0 to 9” “Keys on the numeric keypad” on page 813 “Function keys” on page 813 “Other keys” on page 814 You can use key constants to intercept the built-in behavior of keypresses. For more information, see “Key class” on page 295.
Letter or number key Key code L 76 M 77 N 78 O 79 P 80 Q 81 R 82 S 83 T 84 U 85 V 86 W 87 X 88 Y 89 Z 90 0 48 1 49 2 50 3 51 4 52 5 53 6 54 7 55 8 56 9 57 Appendix B: Keyboard Keys and Key Code Values
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 96 Numbpad 1 97 Numbpad 2 98 Numbpad 3 99 Numbpad 4 100 Numbpad 5 101 Numbpad 6 102 Numbpad 7 103 Numbpad 8 104 Numbpad 9 105 Multiply 106 Add 107 Enter 13 Subtract 109 Decimal 110 Divide 111 Function keys The following table lists the function keys on a stand
Function key Key code F10 This key is reserved by the system and cannot be used in ActionScript.
Key Key code Num Lock 144 ;: 186 =+ 187 -_ 189 /? 191 `~ 192 [{ 219 \| 220 ]} 221 "' 222 Other keys 815
Appendix B: Keyboard Keys and Key Code Values
INDEX A accessing object properties 38 actions repeating 40 ActionScript classpath 64 interfaces 59 ActionScript 2.0 overview 45 adding notes to scripts 16 animation, symbols and 21 arguments.
classes, built-in extending 55 classpaths defined 64 combining operations 37 comments 16 communicating with the Flash Player 72 comparison operators 34 compile time, defined 6 concatenating strings 19 conditions, checking for 40 constants 11, 18 constructors defined 11 overview 52 conversion functions 18 converting data types 18 counters, repeating action with 40 curly braces 15, 16 custom functions 41 D data types 18 assigning to elements 23 automatically assigning 24 casting 25 converting 18 declaring 24
G getter/setter methods of classes 63 getting information from remote files 67 global variables 29 and strict data typing 25 grouping statements 15, 16 H HTTP protocol 67 communicating with server-side scripts 69 HTTPS protocol 67 I identifiers, defined 12 importing classes 65 information, passing between SWF files 67 inheritance 46 allowed from only one class 56 and subclasses 55, 57 instance members 60 instance names setting dynamically 38 instances defined 12 example of creating 50 interfaces 47 as data
O object properties accessing 38 object-oriented programming 45 objects and object-oriented programming 46 data type 21 defined 12 looping through children of 40 operators 12 array access 38 assignment 37 associativity 32 bitwise 36 combining with values 31 comparison 34 deprecated 809 dot 38 equality 37 logical 36 numeric 33 string 35 P packages 57 naming 57 parameters defined 13 in parentheses 16 passing to functions 42 parentheses 16 passing values by content 30 by reference 30 polymorphism 47 primitive
syntax case sensitivity 14 curly braces 15, 16 dot 14 parentheses 16 rules 13 semicolon 15 T target paths defined 13 TCP/IP connection sending information 68 with XMLSocket object 72 terminating statements 15 terminology 11 transferring variables between movie and server 70 typing variables 23 typographical conventions 6 X XML 70 DOM 70 hierarchy 70 sample variable conversion 71 sending information via TCP/IP socket 68 sending information with XML methods 68 XML class, methods of 71 XMLSocket object checki
Index
INDEX OF LANGUAGE ELEMENTS Symbols – (minus) 93 –– (decrement) 81 ! (logical NOT) 83 != (inequality) 84 !== (strict inequality) 86 " " (string delimiter) 207 #include 175 % (modulo) 87 %= (modulo assignment) 88 & (bitwise AND operator) 89 && (logical AND) 90 &= (bitwise AND assignment) 91 () (parentheses) 92 (array access) 103 * (multiplication) 94 *= (multiplication assignment) 95 + (addition) 113 ++ (increment) 82 += (addition assignment) 114 , (comma) 95 .
Array.sort() 248 Array.sortOn() 251 Array.splice() 254 Array.toString() 255 Array.unshift() 256 asfunction 491 B Boolean class 258 Boolean() 129 Boolean.toString() 258 Boolean.valueOf() 259 break 132 C Camera class 492 Camera.activityLevel 493 Camera.bandwidth 494 Camera.currentFps 495 Camera.fps 496 Camera.get() 496 Camera.height 498 Camera.index 499 Camera.motionLevel 500 Camera.motionTimeOut 501 Camera.muted 502 Camera.name 503 Camera.names 503 Camera.onActivity 504 Camera.onStatus 505 Camera.
do while 145 duplicateMovieClip() 531 dynamic 147 E else 149 else if 150 Error class 287 Error.message 288 Error.name 289 Error.toString() 289 escape 151 eval() 152 extends 153 F false 156 for 157 for..in 159 fscommand() 161 function 163 Function class 291 Function.apply() 291 Function.call() 293 G get 165 getProperty 533 getTimer 167 getURL() 168 getVersion 170 I if 172 implements 173 import 174 -Infinity 178 Infinity 177 instanceof 179 interface 180 isFinite 182 isNaN() 183 K Key class 295 Key.
Math.atan() 347 Math.atan2() 348 Math.ceil() 348 Math.cos() 349 Math.E 350 Math.exp() 350 Math.floor() 351 Math.LN10 352 Math.LN2 352 Math.log() 351 Math.LOG10E 353 Math.LOG2E 353 Math.max() 354 Math.min() 354 Math.PI 355 Math.pow() 356 Math.random() 357 Math.round() 357 Math.sin() 358 Math.sqrt() 359 Math.SQRT1_2 360 Math.SQRT2 360 Math.tan() 361 Microphone class 534 Microphone.activityLevel 535 Microphone.gain 536 Microphone.get() 537 Microphone.index 538 Microphone.muted 539 Microphone.
MovieClip.lineStyle() 587 MovieClip.lineTo() 588 MovieClip.loadMovie() 589 MovieClip.loadVariables() 591 MovieClip.localToGlobal() 591 MovieClip.menu 595 MovieClip.moveTo() 596 MovieClip.nextFrame() 597 MovieClip.onData 597 MovieClip.onDragOut 599 MovieClip.onDragOver 599 MovieClip.onEnterFrame 600 MovieClip.onKeyDown 601 MovieClip.onKeyUp 602 MovieClip.onKillFocus 603 MovieClip.onLoad 603 MovieClip.onMouseDown 605 MovieClip.onMouseMove 605 MovieClip.onMouseUp 606 MovieClip.onPress 606 MovieClip.
PrintJob.send() 395 PrintJob.start() 395 private 195 public 197 R removeMovieClip() 667 return 198 S Selection class 669 Selection.addListener() 669 Selection.getBeginIndex() 670 Selection.getCaretIndex() 671 Selection.getEndIndex() 672 Selection.getFocus() 673 Selection.onSetFocus 674 Selection.removeListener() 675 Selection.setFocus() 676 Selection.setSelection() 678 set 199 set variable 201 setInterval() 203 setProperty() 679 SharedObject class 398 SharedObject.clear() 399 SharedObject.
System.capabilities.os 436 System.capabilities.pixelAspectRatio 436 System.capabilities.playerType 437 System.capabilities.screenColor 437 System.capabilities.screenDPI 437 System.capabilities.screenResolutionX 438 System.capabilities.screenResolutionY 438 System.capabilities.serverString 439 System.capabilities.version 439 System.exactSettings 421 System.onStatus 422 System.security object 440 System.security.allowDomain() 440 System.security.allowInsecureDomain() 441 System.setClipboard() 423 System.
TextFormat.italic 785 TextFormat.leading 785 TextFormat.leftMargin 786 TextFormat.rightMargin 786 TextFormat.size 787 TextFormat.tabStops 787 TextFormat.target 788 TextFormat.underline 788 TextFormat.url 789 TextSnapshot object 790 TextSnapshot.findText() 790 TextSnapshot.getCount() 791 TextSnapshot.getSelected() 792 TextSnapshot.getSelectedText() 793 TextSnapshot.getText() 794 TextSnapshot.hitTestTextNearPos() 795 TextSnapshot.setSelectColor() 796 TextSnapshot.