MACROMEDIA FLEX-FLEX ACTIONSCRIPT LANGUAGE Reference
MACROMEDIA FLEX-FLEX ACTIONSCRIPT LANGUAGE Reference

MACROMEDIA FLEX-FLEX ACTIONSCRIPT LANGUAGE Reference

Actionscript language reference

Advertisement

Quick Links

Flex ActionScript Language Reference

Advertisement

Table of Contents
loading
Need help?

Need help?

Do you have a question about the FLEX-FLEX ACTIONSCRIPT LANGUAGE and is the answer not in the manual?

Questions and answers

Subscribe to Our Youtube Channel

Summary of Contents for MACROMEDIA FLEX-FLEX ACTIONSCRIPT LANGUAGE

  • Page 1 Flex ActionScript Language Reference...
  • Page 2 If you access a third-party website mentioned in this guide, then you do so at your own risk. Macromedia provides these links only as a convenience, and the inclusion of the link does not imply that Macromedia endorses or accepts any responsibility for the content on those third-party sites.
  • Page 3: Table Of Contents

    CONTENTS INTRODUCTION: Getting Started with ActionScript ..... . . 5 Intended audience ..........5 Using the documentation .
  • Page 4 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 .
  • Page 5: Introduction: Getting Started With Actionscript

    MXML. Intended audience This manual assumes that you already installed Macromedia Flex and know how to use it. If you have written programs before, ActionScript will seem familiar. But if you’re new to programming, ActionScript isn’t hard to learn.
  • Page 6: Typographical Conventions

    • 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.
  • Page 7: Part I: Welcome To Actionscript

    PART I Welcome to 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 .
  • Page 9: Chapter 1: Actionscript Basics

    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.
  • Page 10: Differences Between Actionscript And Javascript

    Macromedia Central does support the RegExp object. Unicode support for ActionScript Macromedia Flex supports Unicode text encoding for ActionScript. This means that you can include text in different languages in an ActionScript file. For example, you can include text in English, Japanese, and French in the same file.
  • Page 11: Terminology

    Terminology As with all scripting languages, ActionScript uses its own terminology. The following list provides an introduction to important ActionScript terms: Boolean is a value. true false Classes are data types that you can create to define a new type of object. To define a class, you use the keyword in a script file.
  • Page 12 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, is the name of a variable.
  • Page 13: Syntax

    Parameters (also called arguments) are placeholders that let you pass values to functions. For example, the following function uses two values it receives in the parameters welcome() firstName hobby function welcome(firstName:String, hobby:String):String { var welcomeText:String = "Hello, " + firstName + ". I see you enjoy " + hobby +".";...
  • Page 14 • “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 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.
  • Page 15 Curly braces ActionScript event handlers, class definitions, and functions are grouped together into blocks with curly braces ( ). You can put the opening brace on the same line as your declaration or on the next line, as shown in the following examples. To make your code easier to read, it’s a good idea to choose one format and use it consistently.
  • Page 16 Semicolons are required within 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...
  • Page 17 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.
  • Page 18: About Data Types

    Constants A constant is a property whose value never changes. ActionScript contains predefined constants. For example, the constants , and are properties of the Key object BACKSPACE ENTER SPACE 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?";...
  • Page 19 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, is a string assigned to the variable "L7"...
  • Page 20 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” “Number class” entries. The following example uses the (square root) method of the Math class to return the sqrt() square root of the number 100: Math.sqrt(100);...
  • Page 21 Stage: getURL() my_mc.startDrag(true); parent_mc.getURL("http://www.macromedia.com/support/" + product); The second example returns the width of a movie clip called on the Stage. The targeted my_mc instance must be a movie clip, and the returned value must be a numeric value.
  • Page 22 = function() { this.stopDrag(); The MovieClip class is the base class for Flex components. Although 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.
  • Page 23: Assigning Data Types To Elements

    Several methods and functions return if no value has been set. The following example null demonstrates how you can use to test if form fields currently have form focus: null if (Selection.getFocus() == null) { trace("no selection"); Undefined data type The undefined data type has one value, , and is automatically assigned to a variable to undefined...
  • Page 24 • “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. If you assign a value to a variable, as shown in the following example, Flash Player evaluates at runtime the element on the right side of the operator and determines that it is of the Number data type: var x = 3;...
  • Page 25 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 keyword when strictly typing variable, you can’t strictly type a global variable (see “Scoping and declaring variables” on page 28).
  • Page 26 The syntax for casting is , where you want the compiler to behave as if the data type type(item) . Casting is essentially a function call, and the function call returns if the cast item type null 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.
  • Page 27: About Variables

    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);...
  • Page 28 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 , the new object is undefined: new String() // This code works as expected...
  • Page 29 = 6; var squared:Number = x*x; trace(squared); // 36 Similar behavior occurs when you pass an undefined variable to a method or function: //does not work getURL(myWebSite); // no action var myWebSite = "http://www.macromedia.com"; //works About variables...
  • Page 30 = "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.
  • Page 31: Using Operators To Manipulate Values In Expressions

    In the following example, contains an Array object, so it is passed to function myArray by reference. The function accepts an Array object as a parameter zeroArray() zeroArray() and sets all the elements of that array to 0. It can modify the array because the array is passed by reference.
  • Page 32 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.
  • Page 33 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 Instance of (finds the class of which the object is an...
  • Page 34 This process is also known as a preincrement. In the following example, is incremented after the test is performed: if (age++ >= 30) This process is also known as a postincrement. The following table lists the ActionScript numeric operators: Operator Operation performed Addition Multiplication...
  • Page 35 The following table lists the ActionScript comparison operators: Operator Operation performed Less than: Returns if the left operand is mathematically smaller than the right < true operand. Returns if the left operand alphabetically precedes the right operand (for true example, a < b). Greater than: Returns if the left operand is mathematically larger than the right >...
  • Page 36 Logical operators Logical operators compare Boolean values ( ) and return a third Boolean value. true false For example, if both operands evaluate to , the logical AND ( ) operator returns . If true && true one or both of the operands evaluate to , the logical OR ( ) operator returns .
  • Page 37 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 ( ) value. If the operands are true false strings, numbers, or Boolean values, they are compared by value. If the operands are objects or arrays, they are compared by reference.
  • Page 38 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."); The following table lists the ActionScript assignment operators: Operator Operation performed Assignment...
  • Page 39: Using Condition Statements

    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"...
  • Page 40 Checking conditions Statements that check whether a condition is begin with the term . If the true false condition evaluates to , ActionScript executes the next statement. If the condition doesn’t true 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.
  • Page 41: Using Built-In Functions

    Children include other functions, objects, and variables. The following example uses the trace statement to print its results in the Output panel: var myObject:Object = { name:'Joe', age:25, city:'San Francisco' }; for (propertyName in myObject) { trace("myObject has the property: " + propertyName + ", with the value: " + myObject[propertyName]);...
  • Page 42 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. For more information, see the following topics: •...
  • Page 43 The parameter in the function is similar to a local variable; it initials fillOutScorecard() 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 .
  • Page 44 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 in the object , passes the parameter 3 to it, and stores the result in the sqr() mathLib variable...
  • Page 45: Chapter 2: Creating Custom Classes With Actionscript

    This section provides a brief introduction to principles involved in developing object-oriented programs. These principles are described in more depth in the rest of this chapter, along with details on how they are implemented in Macromedia Flex. To learn about object-oriented programming principles, see the following topics: •...
  • Page 46 (such as a chemical process). Note: The word “behaviors” is used generically here and does not refer to the Behaviors development panel in the Macromedia Flash interface. Classes and class members Continuing with the real-world analogy, consider that there are cats of different colors, ages, and names, with different ways of eating and purring.
  • Page 47 Interfaces Interfaces in object-oriented programming can be described as classes whose methods are not implemented (defined). Another class can implement the methods declared by the interface. An interface can also be thought of as a “programming contract” that can be used to enforce relationships between otherwise unrelated classes.
  • Page 48: Using Classes: A Simple Example

    For example, you might start with a class called Mammal that has methods. play() sleep() You then create Cat, Monkey, and Dog subclasses to extend the Mammal class. The subclasses override the method from the Mammal class, to reflect the habits of those particular kinds play() of animals.
  • Page 49 In your text editor, enter the following code (in this procedure, new code you type in each step bold class Person { This is called the class declaration. In its most basic form, a class declaration consists of the keyword, followed by the class name (Person, in this case), and then left and right curly class braces ( ).
  • Page 50 constructor function takes two parameters, , and assigns Person() myName myAge those parameters to the properties. The two function parameters are strictly name 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”...
  • Page 51: Creating And Using Classes

    This code invokes the Person class’s constructor function, passing as parameters the values "Nate" and 32. variable is typed as a Person object. Typing your objects in this way enables the newPerson compiler to ensure that you don’t try to access properties or methods that aren’t defined in the class.
  • Page 52 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.
  • Page 53 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.
  • Page 54 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;...
  • Page 55 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 When you initialize arrays inline, only one array is created for all instances of the class: class Bar { var foo:Array = new Array();...
  • Page 56: Creating Dynamic Classes

    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 {}...
  • Page 57: Using Packages

    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. This implementation provides you with more control over subclasses of the MovieClip class, because you can choose to make your subclasses dynamic or not: class A extends MovieClip {} // A is not dynamic...
  • Page 58: Creating And Using Interfaces

    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 statement (see the following section). import Creating and using interfaces An interface in object-oriented programming is like a class whose methods have been declared, but otherwise don’t “do”...
  • Page 59 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. function illegalMethod(){ You can also use the keyword to create subclasses of an interface:...
  • Page 60: Instance And Class Members

    For example, the following code first checks if the object name implements the Movable newBox interface before calling the method on the object: moveUp() if (Movable(newBox) != null) { newBox.moveUp(); For more information about casting, see “Casting objects” on page Instance and class members In object-oriented programming, members (properties or methods) of a class can be instance members or class members.
  • Page 61 For more information on the Singleton design pattern, see www.macromedia.com/devnet/mx/ coldfusion/articles/design_patterns.html. Often there are situations when you need exactly one object of a particular type in a system. For example, in a chess game, there is only one chessboard, and in a country, there is only one capitol city.
  • Page 62 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 method. This is typically called lazy getInstance creation and can help code efficiency in many circumstances.
  • Page 63: Implicit Getter/Setter Methods

    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 property, Widget.widgetCount but instead refer only to , the ActionScript 2.0 compiler ascertains that the reference widgetCount is actually to and correctly exports that property.
  • Page 64: Understanding The Classpath

    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 method attributes. You create methods that get or set the value of a property, and add the keyword before the method name, as shown in the following example:...
  • Page 65: Importing Classes

    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.
  • Page 66 Chapter 2: Creating Custom Classes with ActionScript 2.0...
  • Page 67: Chapter 3: Working With External Data

    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.
  • Page 68 . In the file myData.txt, you would have text similar to the following example: myData.txt lastSiteVisited=www.macromedia.com But if you used the following code, you could not trace the data that is loading: loadVariables("myData.txt", 0); trace(lastSiteVisited); If you use the...
  • Page 69 ). For example, the following phrase defines several variables: highScore1=54000&playerName1=RGoulet&highScore2=53455&playerName2= WNewton&highScore3=42885&playerName3=TJones Note: You might need to URL-encode certain characters, such as the plus (+) or ampersand (&) characters. For more information, see www.macromedia.com/support/flash/ts/documents/ url_encoding.htm. For more information, see , the LoadVars class entry, and “Using the LoadVars class”...
  • Page 70 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.
  • Page 71 In the following example, is the parent node; it has no attributes and contains the <portfolio> child node , which has the attributes , and <holding> symbol price value <portfolio> <holding symbol="rich" qty="75" price="245.50" value="18412.50" /> </portfolio> For more information on XML, see www.w3.org/XML. Using the XML class The methods of the ActionScript XML class (for example, , and...
  • Page 72: Sending Messages To And From Flash Player

    When you invoke the method, Flash Player opens a TCP/IP connection to the server connect() and keeps that connection open until one of the following events happens: • method of the XMLSocket class is called. close() • No more references to the XMLSocket object exist. •...
  • Page 73 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.
  • Page 74 , in Netscape 6.2 and later. Earlier versions do not support FSCommand these JavaScript methods and in Netscape 6.2 or later. For more information, see the FSCommand Macromedia Support Center article, “Scripting With Flash” at www.macromedia.com/support/ flash/publishexport/scriptingwithflash/. Chapter 3: Working with External Data...
  • Page 75 PART II Reference 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.”...
  • Page 77: Chapter 4: About The Actionscript Language Reference

    Chapter 7, “ActionScript for Flash,” on page 490 describes functions, properties, and classes of Macromedia Flash Player that you can use in a Macromedia Flex application, if appropriate. For additional elements that are available for Flex, see Flex ActionScript and MXML API Reference.
  • Page 78: Sample Entry For Classes

    Usage This section provides correct syntax for using the ActionScript element in your code. The required portion of the syntax is in , and the code that you provide is in code font italicized . Brackets ( ) indicate optional parameters. code font Parameters This section describes any parameters listed in the syntax.
  • Page 79 Method, property, and event handler listings The methods, properties, and event handlers of a class are listed alphabetically after the class entry. Sample entry for classes...
  • Page 80: 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,”...
  • Page 81 CHAPTER 5 ActionScript Core Language Elements –– (decrement) Availability Flash Player 4. Usage ––expression expression–– Parameters A number or a variable that evaluates to a number. expression Returns A number. Description Operator (arithmetic); a pre-decrement and post-decrement unary operator that subtracts 1 from .
  • Page 82 ++ (increment) Availability Flash Player 4. Usage ++expression expression++ Parameters A number or a variable that evaluates to a number. expression Returns A number. Description Operator (arithmetic); a pre-increment and post-increment unary operator that adds 1 to . The can be a variable, element in an array, or property of an object. expression expression The pre-increment form of the operator (...
  • Page 83 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 = [];...
  • Page 84 Parameters An expression or a variable that evaluates to a Boolean value. expression Returns A Boolean value. Description Operator (logical); inverts the Boolean value of a variable or expression. If is a expression variable with the absolute or converted value , the value of .
  • Page 85 Description Operator (inequality); tests for the exact opposite of the equality ( ) operator. If expression1 equal to , the result is . As with the equality ( ) operator, the definition of expression2 false equal depends on the data types being compared, as illustrated in the following list: •...
  • Page 86 true false The following example illustrates comparison by reference with two arrays: var a:Array = [ 1, 2, 3 ]; var b:Array = [ 1, 2, 3 ]; trace(a); // 1, 2, 3 trace(b); // 1, 2, 3 trace(a!=b); // true a = b;...
  • Page 87 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.
  • Page 88 Parameters None. Returns A number. Description Operator (arithmetic); calculates the remainder of divided by . If expression1 expression2 either of the parameters are non-numeric, the modulo ( ) operator attempts to expression convert them to numbers. The can be a number or string that converts to a numeric expression value.
  • Page 89 Example The following example assigns the value to the variable 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.
  • Page 90 In the numbers 13 and 11 the result is 9 because only the first and last positions in both numbers have the number 1. The following examples show the behavior of the return value conversion: trace(0xFFFFFFFF); // 4294967295 trace(0xFFFFFFFF & 0xFFFFFFFF); // -1 trace(0xFFFFFFFF &...
  • Page 91 Example The following example uses the logical AND ( ) operator to perform a test to determine if a && player has won the game. The variable and the variable are updated when a player turns score 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.
  • Page 92 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 Numbers, strings, variables, or text. expression1, expression2 The function to be performed on the contents of the parentheses.
  • Page 93 Usage 2: The following example evaluates the function , and then the function , and foo() bar() returns the result of the expression a + b var a:Number = 1; var b:Number = 2; function foo() { a += b; function bar() { b *= 10;...
  • Page 94 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...
  • Page 95 *= (multiplication assignment) Availability Flash Player 4. Usage expression1 *= expression2 Parameters None. Returns The value of . If an expression cannot be converted to a numeric expression1 * expression2 value, it returns (not a number). Description Operator (arithmetic compound assignment); assigns the value of expression1 expression1 *...
  • Page 96 Parameters None. Returns The value of , and so on. expression1 expression2 Description Operator; evaluates , then , and so on. This operator is primarily used expression1 expression2 with the loop statement and is often used with the parentheses () operator. For more information, see “Operator precedence and associativity”...
  • Page 97 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 object classes or a custom class.
  • Page 98 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.
  • Page 99 Usage 2: The following example shows how to specify a function’s parameter type by defining a function named that takes a parameter named of type Number: randomInt() integer function randomInt(integer:Number):Number { return Math.round(Math.random()*integer); trace(randomInt(8)); Usage 3: The following example defines a function named that takes a parameter squareRoot() named...
  • Page 100 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";...
  • Page 101 // (comment delimiter) Availability Flash 1. Usage // comment Parameters Any characters. comment 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.
  • Page 102 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 to identify // (comment delimiter) single-line comments.
  • Page 103 Description Operator (arithmetic compound assignment); assigns the value of expression1 expression1 / . For example, the following two statements are equivalent: expression2 x /= y x = x / y For more information, see “Operator precedence and associativity” on page Example The following code illustrates using the division assignment ( operator with variables and...
  • Page 104 Description Operator; initializes a new array or multidimensional array with the specified elements ( , and so on), or accesses elements in an array. The array access operator lets you dynamically set and retrieve instance, variable, and object names. It also lets you access object properties. Usage 1: An array is an object whose properties are called elements, which are each identified by a number called an index.
  • Page 105 The following example creates an array called and uses the statement employee_array trace() to send the elements to the log file. In the fourth line, an element in the array is changed, and the fifth line sends the newly modified array to the log file: var employee_array = ["Barbara", "George", "Mary"];...
  • Page 106 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. Negative numbers are converted to an unsigned hex value via the two’s complement notation, with the minimum being -2147483648 or 0x800000000;...
  • Page 107 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 &...
  • Page 108 , and with accompanying values: city state balance var account:Object = {name:"Macromedia, Inc.", address:"600 Townsend Street", city:"San Francisco", state:"California", zip:"94103", balance:"1000"}; for (i in account) { trace("account."+i+" = "+account[i]); The following example shows how array and object initializers can be nested within each other: var person:Object = {name:"Gina Vechio",...
  • Page 109 Returns A 32-bit integer. Description Operator (bitwise); converts to 32-bit unsigned integers, and expression1 expression2 returns a 1 in each bit position where the corresponding bits of either expression1 are 1. Floating-point numbers are converted to integers by discarding any digits expression2 after the decimal point.
  • Page 110 Returns A Boolean value. Description Operator (logical); evaluates (the expression on the left side of the operator) and expression1 returns if the expression evaluates to . If evaluates to true true expression1 false (the expression on the right side of the operator) is evaluated. If expression2 expression2 evaluates to...
  • Page 111 See also ! (logical NOT) != (inequality) !== (strict inequality) && (logical AND) (equality) === (strict equality) |= (bitwise OR assignment) Availability Flash Player 5. Usage expression1 |= expression2 Parameters A number or variable. expression1,expression2 Returns An integer. Description Operator (bitwise compound assignment); assigns the value of expression1 expression1 |...
  • Page 112 Parameters A number. expression Returns A 32-bit integer. Description Operator (bitwise); also known as the one’s complement operator or the bitwise complement operator. Converts the to a 32-bit signed integer, and then applies a bitwise one’s expression 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.
  • Page 113 /* 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 read- only flag.
  • Page 114 This statement adds the floating-point numbers 2.5 and 3.25 and writes the resulting floating- point 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 = 3 + 10 + "asdf";...
  • Page 115 See also + (addition) < (less than) Availability Flash Player 5. Usage expression1 < expression2 Parameters A number or string. expression1,expression2 Returns A Boolean value. Description Operator (comparison); compares two expressions and determines whether is less expression1 than ; if so, the operator returns .
  • Page 116 Returns A 32-bit integer. Description Operator (bitwise); converts to 32-bit integers, and shifts all the expression1 expression2 bits in to the left by the number of places specified by the integer resulting from the expression1 conversion of . The bit positions that are emptied as a result of this operation are expression2 filled in with 0 and bits shifted off the left end are discarded.
  • Page 117 <<= (bitwise left shift and assignment) Availability Flash Player 5. Usage expression1 <<= expression2 Parameters A number or expression to be shifted left. expression1 A number or expression that converts to an integer from 0 to 31. expression2 Returns A 32-bit integer. Description Operator (bitwise compound assignment);...
  • Page 118 Parameters A number or string. expression1,expression2 Returns A Boolean value. Description Operator (comparison); compares two expressions and determines whether is less expression1 than or equal to ; if it is, the operator returns . If is greater than expression2 true expression1 , the operator returns .
  • Page 119 Description Operator; assigns the value of (the parameter on the right) to the variable, array expression2 element, or property in . Assignment can be either by value or by reference. expression1 Assignment by value copies the actual value of and stores it in expression2 expression1 Assignment by value is used when a variable is assigned a number or string literal.
  • Page 120 -= (subtraction assignment) Availability Flash Player 4. Usage expression1 -= expression2 Parameters A number or expression that evaluates to a number. expression1,expression2 Returns A number. Description Operator (arithmetic compound assignment); assigns the value of expression1 expression1 - . For example, the following two statements are equivalent: expression2 x -= y;...
  • Page 121 Parameters A number, string, Boolean value, variable, object, array, expression1,expression2 or function. Returns A Boolean value. Description Operator (equality); tests two expressions for equality. The result is if the expressions true are equal. The definition of equal depends on the data type of the parameter: •...
  • Page 122 The following examples show comparison by reference. The first example compares two arrays with identical length and elements. The equality operator will return for these two arrays. false Although the arrays appear equal, comparison by reference requires that they both refer to the same array.
  • Page 123 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);...
  • Page 124 > (greater than) Availability Flash Player 4. Usage expression1 >expression2 Parameters A number or string. expression1,expression2 Returns A Boolean value. Description Operator (comparison); compares two expressions and determines whether expression1 greater than ; if it is, the operator returns . If is less than or equal expression2 true...
  • Page 125 For more information, see “Operator precedence and associativity” on page 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");...
  • Page 126 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.
  • Page 127 The following two expressions are equivalent: A >>= B A = (A >> B) For more information, see “Operator precedence and associativity” on page Example The following commented code uses the bitwise right shift and assignment ( ) operator. >>= function convertToBinary(numberToConvert:Number):String { var result:String = "";...
  • Page 128 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.
  • Page 129 CHAPTER 5 ActionScript Core Language Elements Boolean() Availability Flash Player 5; behavior changed in Flash Player 7. Usage Boolean(expression) : Boolean Parameters An expression to convert to a Boolean value. expression Returns A Boolean value. Description Function; converts the parameter to a Boolean value and returns a value as described expression in the following list:...
  • Page 130 // 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);...
  • Page 131 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 One or more elements to place in the array. element Returns An array.
  • Page 132 CHAPTER 5 ActionScript Core Language Elements break Availability Flash Player 4. Usage break Parameters None. Returns Nothing. Description Statement; appears within a loop ( ) or within a block of for..in do while while statements associated with a particular case within a statement.
  • Page 133 See also for..in do while while switch case continue throw try..catch..finally break...
  • Page 134 CHAPTER 5 ActionScript Core Language Elements case Availability Flash Player 4. Usage case expression: statement(s) Parameters Any expression. expression Any statement or sequence of statements. statement(s) Returns Nothing. Description Statement; defines a condition for the statement. If the parameter equals the switch expression parameter of the...
  • Page 135 See also break default === (strict equality) switch case...
  • Page 136 CHAPTER 5 ActionScript Core Language Elements class Availability Flash Player 6. Usage [dynamic] class className [ extends superClass ] [ implements interfaceName [, interfaceName... ] ] // class definition here Parameters The fully qualified name of the class. className The name of the class that extends (inherits from).
  • Page 137 class C implements Interface_i, Interface_j // OK class C extends Class_d implements Interface_i, Interface_j // OK class C extends Class_d, Class_e // not OK For more information, see “Creating and using classes” in Using ActionScript in Flash.For more information, see “Creating and using classes”...
  • Page 138 In your script, use the 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 Object.registerClass() Chapter 5: ActionScript Core Language Elements...
  • Page 139 CHAPTER 5 ActionScript Core Language Elements clearInterval() Availability Flash Player 6. Usage clearInterval( intervalID:Number ) : Void Parameters A numeric (integer) identifier returned from a call to intervalID 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:...
  • Page 140 CHAPTER 5 ActionScript Core Language Elements continue 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.
  • Page 141 if (i%3 == 0) { continue; trace(i); In the following loop, causes the Flash interpreter to skip the rest of the loop for..in continue 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;...
  • Page 142 CHAPTER 5 ActionScript Core Language Elements default Availability Flash Player 6. Usage default: statements Parameters Any statements. statements Returns Nothing. Description Statement; defines the default case for a statement. The statements execute if the switch parameter of the statement doesn’t equal (using the strict equality [ expression switch operation) any of the...
  • Page 143 CHAPTER 5 ActionScript Core Language Elements delete Availability Flash Player 5. Usage delete reference Parameters The name of the variable or object to eliminate. reference Returns A Boolean value. Description Operator; destroys the object reference specified by the parameter, and returns reference true the reference is successfully deleted;...
  • Page 144 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];...
  • Page 145 CHAPTER 5 ActionScript Core Language Elements do while Availability Flash Player 4. Usage do { statement(s) } while (condition) Parameters The condition to evaluate. condition The statement(s) to execute as long as the parameter evaluates statement(s) condition true Returns Nothing. Description Statement;...
  • Page 146 See also break, continue, while Chapter 5: ActionScript Core Language Elements...
  • Page 147 CHAPTER 5 ActionScript Core Language Elements dynamic 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.
  • Page 148 If you add an undeclared function, , an error is generated, as shown in the following dance 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'.
  • Page 149 CHAPTER 5 ActionScript Core Language Elements else Availability Flash Player 4. Usage if (condition){ statement(s); } else { statement(s); Parameters An expression that evaluates to condition true false An alternative series of statements to run if the condition specified in the statement(s) statement is false...
  • Page 150 CHAPTER 5 ActionScript Core Language Elements else if Availability Flash Player 4. Usage if (condition){ statement(s); } else if (condition){ statement(s); Parameters An expression that evaluates to condition true false An alternative series of statements to run if the condition specified in the statement(s) statement is false...
  • Page 151 CHAPTER 5 ActionScript Core Language Elements escape() Availability Flash Player 5. Usage escape(expression:String) : String Parameters The expression to convert into a string and encode in a URL-encoded format. expression 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.
  • Page 152 CHAPTER 5 ActionScript Core Language Elements eval() Availability Flash Player 5. Usage eval(expression:String) : Object Parameters A string containing the name of a variable, property, object, or movie clip expression to retrieve. Returns A value, reference to an object or movie clip, or undefined Description Function;...
  • Page 153 CHAPTER 5 ActionScript Core Language Elements extends Availability Flash Player 6. Usage class className extends otherClassName {} interface interfaceName extends otherInterfaceName {} Parameters The name of the class you are defining. className The name of the class on which is based. otherClassName className The name of the interface you are defining.
  • Page 154 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 to track whether the car object has a full-size spare tire. Second, it adds a new fullSizeSpare method specific to cars, , that activates the car’s anti-theft alarm.
  • Page 155 The following example instantiates a Truck object, calls a method overridden by the Truck class ), then calls a method defined in the Vehicle class ( reverse() stop() var myTruck:Truck = new Truck(2, "White", 18); myTruck.reverse(); // output: [Truck] make beeping sound [Vehicle] reverse myTruck.stop();...
  • Page 156 CHAPTER 5 ActionScript Core Language Elements false Availability Flash Player 5. Usage false Description Constant; a unique Boolean value that represents the opposite of . When automatic data true typing converts to a number, it becomes 0; when it converts to a string, it becomes false false...
  • Page 157 CHAPTER 5 ActionScript Core Language Elements Availability Flash Player 5. Usage for(init; condition; next) { statement(s); Parameters An expression to evaluate before beginning the looping sequence; usually an assignment init expression. A statement is also permitted for this parameter. An expression that evaluates to .
  • Page 158 The following example uses to perform the same action repeatedly. In the code, the 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;...
  • Page 159 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 variableIterant object or element in an array. The name of an object to be iterated. object An instruction to execute for each iteration.
  • Page 160 The following example shows using to iterate over the elements of an array: for..in 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 operator with to iterate over a particular type of...
  • Page 161 Player, such as a web browser. You can also use the function to pass messages to fscommand() Macromedia Director, or to Visual Basic, Visual C++, and other programs that can host ActiveX controls. Usage 1: To send a message to Flash Player, you must use predefined commands and parameters.
  • Page 162 Usage 3: The function can send messages to Macromedia Director that are fscommand() interpreted by Lingo (Director’s scripting language) as strings, events, or executable Lingo code. If the message is a string or an event, you must write the Lingo code to receive the message from the function and carry out an action in Director.
  • Page 163 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 The name of the new function. This parameter is optional. functionname An identifier that represents a parameter to pass to the function. This parameter is parameter optional.
  • Page 164 Example The following example defines the function , 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);...
  • Page 165 CHAPTER 5 ActionScript Core Language Elements Availability Flash Player 6. Usage function get property() { // your statements here Parameters The word you use to refer to the property that accesses; this value must be the property same as the value used in the corresponding command.
  • Page 166 San Fran San Francisco When you trace giants.name, you use the get method to return the value of the property. See also Object.addProperty(), Chapter 5: ActionScript Core Language Elements...
  • Page 167 CHAPTER 5 ActionScript Core Language Elements getTimer() 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 functions are used to create a...
  • Page 168 CHAPTER 5 ActionScript Core Language Elements getURL() Availability Flash 2. The options are available only in Flash Player 4 and later versions. POST Usage getURL(url:String [, window:String [, "variables":String]]) : Void Parameters The URL from which to obtain the document. An optional parameter specifying the window or HTML frame into which the window document should load.
  • Page 169 = "Gus"; var lastName:String = "Richardson"; var age:Number = 92; myBtn_btn.onRelease = function() { getURL("http://www.macromedia.com", "_blank", "GET"); The following ActionScript uses to send variables in the HTTP header. Make sure you test POST your documents in a browser window, because otherwise your variables are sent using var firstName:String = "Gus";...
  • Page 170 CHAPTER 5 ActionScript Core Language Elements getVersion() 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. Example The following examples trace the version number of the Flash Player playing the SWF file: var flashVersion:String = getVersion();...
  • Page 171 CHAPTER 5 ActionScript Core Language Elements _global object 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.
  • Page 172 CHAPTER 5 ActionScript Core Language Elements Availability Flash Player 4. Usage if(condition) { statement(s); Parameters An expression that evaluates to condition true false The instructions to execute if or when the condition evaluates to statement(s) true Returns Nothing. Description Statement; evaluates a condition to determine the next action in a SWF file. If the condition is , Flash runs the statements that follow the condition inside curly braces ( ).
  • Page 173 CHAPTER 5 ActionScript Core Language Elements implements 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”...
  • Page 174 CHAPTER 5 ActionScript Core Language Elements import Availability Flash Player 6. Usage import className import packageName.* Parameters The fully qualified name of a class you have defined in an external class file. className A directory in which you have stored related class files. packageName Description Keyword;...
  • Page 175 CHAPTER 5 ActionScript Core Language Elements #include 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 [path] filename.as script;...
  • Page 176 // 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"...
  • Page 177 CHAPTER 5 ActionScript Core Language Elements Infinity Availability Flash Player 5. Usage Infinity Description Constant; specifies the IEEE-754 value representing positive infinity. The value of this constant is the same as Number.POSITIVE_INFINITY Infinity...
  • Page 178 CHAPTER 5 ActionScript Core Language Elements -Infinity Availability Flash Player 5. Usage -Infinity Description Constant; specifies the IEEE-754 value representing negative infinity. The value of this constant is the same as Number.NEGATIVE_INFINITY Chapter 5: ActionScript Core Language Elements...
  • Page 179 CHAPTER 5 ActionScript Core Language Elements instanceof Availability Flash Player 6. Usage object instanceof class Parameters An ActionScript object. object A reference to an ActionScript constructor function, such as String or Date. class Returns is an instance of returns otherwise. Also, object class instanceof...
  • Page 180 CHAPTER 5 ActionScript Core Language Elements interface 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.
  • Page 181 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()); // 15 trace(mvar.n(7)); // 49 trace(mvar.o()); // "o" interface Ic extends Ia function p():Void; class E implements Ib, Ic function k():Number {return 25;} function n(x:Number):Number {return x+5;}...
  • Page 182 CHAPTER 5 ActionScript Core Language Elements isFinite() Availability Flash Player 5. Usage isFinite(expression:Object) : Boolean Parameters A Boolean value, variable, or other expression to be evaluated. expression Returns A Boolean value. Description Function; evaluates and returns if it is a finite number or if it is infinity expression true...
  • Page 183 CHAPTER 5 ActionScript Core Language Elements isNaN() Availability Flash Player 5. Usage isNaN(expression:Object) : Boolean Parameters A Boolean, variable, or other expression to be evaluated. expression Returns A Boolean value. Description Function; evaluates the parameter and returns if the value is (not a number).
  • Page 184 CHAPTER 5 ActionScript Core Language Elements Availability Flash Player 5. Usage Description Variable; a predefined variable with the IEEE-754 value for (not a number). To determine if a number is , use isNaN() See also isNaN(), Number.NaN Chapter 5: ActionScript Core Language Elements...
  • Page 185 CHAPTER 5 ActionScript Core Language Elements Availability Flash Player 5. Usage new constructor() Parameters A function followed by any optional parameters in parentheses. The function is constructor usually the name of the object type (for example, Array, Number, or Object) to be constructed. Returns Nothing.
  • Page 186 CHAPTER 5 ActionScript Core Language Elements newline Availability Flash Player 4. Usage newline Parameters None. Returns Nothing. Description Constant; inserts a carriage return character ( ) that generates a blank line in text output generated by your code. Use to make space for information that is retrieved by a newline function or statement in your code.
  • Page 187 CHAPTER 5 ActionScript Core Language Elements null Availability Flash Player 5. Usage null Parameters None. Returns Nothing. Description Constant; a special value that can be assigned to variables or returned by a function if no data was provided. You can use to represent values that are missing or that do not have a defined null data type.
  • Page 188 CHAPTER 5 ActionScript Core Language Elements Number() Availability Flash Player 4; behavior changed in Flash Player 7. Usage Number(expression) : Number Parameters An expression to convert to a number. expression Returns A number or (not a number). Description Function; converts the parameter to a number and returns a value as described in the expression following list:...
  • Page 189 Example In the following example, a new empty object is created, and then the object is populated with values: var company:Object = new Object(); company.name = "Macromedia, Inc."; company.address = "600 Townsend Street"; company.city = "San Francisco"; company.state = "CA";...
  • Page 190 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 The instructions to execute when the occurs. statement(s) mouseEvent is a trigger called an event. When the event occurs, the statements following it mouseEvent within curly braces ({ }) execute.
  • Page 191 Example In the following script, the function executes when the mouse is pressed, and the startDrag() 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._y); stopDrag(); See also onClipEvent() on()
  • Page 192 CHAPTER 5 ActionScript Core Language Elements parseFloat() Availability Flash Player 5. Usage parseFloat(string:String) : Number Parameters The string to read and convert to a floating-point number. string Returns A number or (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.
  • Page 193 CHAPTER 5 ActionScript Core Language Elements parseInt() Availability Flash Player 5. Usage parseInt(expression:String [, radix:Number]) : Number Parameters A string to convert to an integer. expression An integer representing the radix (base) of the number to parse. Legal values are from 2 radix to 36.
  • Page 194 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() Chapter 5: ActionScript Core Language Elements...
  • Page 195 CHAPTER 5 ActionScript Core Language Elements private Availability Flash Player 6. Usage class someClassName{ private var name; private function name() { // your statements here Parameters The name of the variable or function that you want to specify as private. name Description Keyword;...
  • Page 196 Because is a private variable, you cannot access it from outside the Login.as class loginPassword file. Attempts to access the private variable generate an error message. See also public, static Chapter 5: ActionScript Core Language Elements...
  • Page 197 CHAPTER 5 ActionScript Core Language Elements public Flash Player 6. Usage class someClassName{ public var name; public function name() { // your statements here Parameters The name of the variable or function that you want to specify as public. name Description Keyword;...
  • Page 198 CHAPTER 5 ActionScript Core Language Elements return Availability Flash Player 5. Usage return[expression] Parameters A string, number, Boolean, array, or object to evaluate and return as a value of the expression function. This parameter is optional. Returns The evaluated parameter, if provided. expression Description Statement;...
  • Page 199 CHAPTER 5 ActionScript Core Language Elements Availability Flash Player 6. Usage function set property(varName) { // your statements here Parameters Word that refers to the property that will access; this value must be the same as property the value used in the corresponding command.
  • Page 200 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 function executes when the value is traced.
  • Page 201 CHAPTER 5 ActionScript Core Language Elements set variable Availability Flash Player 4. Usage set("variableString", expression) Parameters A string that names a variable to hold the value of the parameter. variableString expression A value assigned to the variable. expression Returns Nothing. Description Statement;...
  • Page 202 The following code loops three times and creates three new variables, called caption0 caption1 caption2 for (var i = 0; i<3; i++) { set("caption"+i, "this is caption "+i); trace(caption0); trace(caption1); trace(caption2); See also Chapter 5: ActionScript Core Language Elements...
  • Page 203 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 A function name or a reference to an anonymous function. functionName The time in milliseconds between calls to the interval...
  • Page 204 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");...
  • Page 205 See also clearInterval() setInterval()
  • Page 206 CHAPTER 5 ActionScript Core Language Elements static Availability Flash Player 6. Usage class someClassName{ static var name; static function name() { // your statements here Parameters The name of the variable or function that you want to specify as static. name Description Keyword;...
  • Page 207 CHAPTER 5 ActionScript Core Language Elements " " (string delimiter) Availability Flash Player 4. Usage "text" Parameters A sequence of zero or more characters. text 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.
  • Page 208 CHAPTER 5 ActionScript Core Language Elements String() Availability Flash Player 4; behavior changed in Flash Player 7. Usage String(expression) Parameters An expression to convert to a string. expression Returns A string. Description Function; returns a string representation of the specified parameter, as described in the following list: •...
  • Page 209 CHAPTER 5 ActionScript Core Language Elements super Availability Flash Player 6. Usage super.method([arg1, ..., argN]) super([arg1, ..., argN]) Parameters The method to invoke in the superclass. method Optional parameters that are passed to the superclass version of the method (syntax 1) or arg1 to the constructor function of the superclass (syntax 2).
  • Page 210 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");...
  • Page 211 CHAPTER 5 ActionScript Core Language Elements switch Availability Flash Player 4. Usage switch (expression){ caseClause: [defaultClause:] Parameters Any expression. expression keyword followed by an expression, a colon, and a group of statements to caseClause case execute if the expression matches the switch parameter using strict equality ( expression keyword followed by statements to execute if none of the case...
  • Page 212 case "i" : trace("you pressed I or i"); break; default : trace("you pressed some other key"); Key.addListener(listenerObj); See also === (strict equality), break, case, default, Chapter 5: ActionScript Core Language Elements...
  • Page 213 CHAPTER 5 ActionScript Core Language Elements this 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 identifier.
  • Page 214 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 references the Circle object:...
  • Page 215 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 code block. catch{} If an exception is not caught by a block, the string representation of the catch finally...
  • Page 216 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();...
  • Page 217 CHAPTER 5 ActionScript Core Language Elements trace() Availability Flash Player 4. Usage trace(expression) Parameters An expression to evaluate. expression Returns Nothing. Description You can use Flash Debug Player to capture output from the function and write that trace() output to the log file. Statement;...
  • Page 218 CHAPTER 5 ActionScript Core Language Elements true Availability Flash Player 5. Usage true Description Constant; a unique Boolean value that represents the opposite of . When automatic data false typing converts to a number, it becomes 1; when it converts to a string, it becomes true true...
  • Page 219 CHAPTER 5 ActionScript Core Language Elements try..catch..finally Availability Flash Player 7. Usage try { // ... try block ... } finally { // ... finally block ... try { // ... try block ... } catch(error[:ErrorType1]) { // ... catch block ... } [catch(error[:ErrorTypeN]) { // ...
  • Page 220 If an error is thrown within a function, and the function does not include a handler, then catch the ActionScript interpreter exits that function, as well as any caller functions, until a block catch is found. During this process, handlers are called at all levels. finally Example The following example shows how to create a...
  • Page 221 The following example demonstrates a statement. The code within the block is try..catch executed. If an exception is thrown by any code within the block, control passes to the catch block, which shows the error message in a text field using the method.
  • Page 222 function randomNum():Number { return Math.round(Math.random()*10)%3; Finally, in another AS file or FLA script, the following code invokes the method on sortRows() an instance of the RecordSet class. It defines blocks for each type of error that is thrown by catch sortRows() import RecordSet;...
  • Page 223 CHAPTER 5 ActionScript Core Language Elements typeof Availability Flash Player 5. Usage typeof(expression) : String Parameters A string, movie clip, button, object, or function. expression Description Operator; a unary operator placed before a single parameter. The operator causes the typeof Flash interpreter to evaluate ;...
  • Page 224 CHAPTER 5 ActionScript Core Language Elements undefined Availability Flash Player 5. Usage undefined Parameters None. Returns Nothing. Description A special value, usually used to indicate that a variable has not yet been assigned a value. A reference to an undefined value returns the special value .
  • Page 225 CHAPTER 5 ActionScript Core Language Elements unescape() Availability Flash Player 5. Usage unescape(x:String) : String Parameters A string with hexadecimal sequences to escape. Returns A string decoded from a URL-encoded parameter. Description Function; evaluates the parameter as a string, decodes the string from URL-encoded format (converting all hexadecimal sequences to ASCII characters), and returns the string.
  • Page 226 CHAPTER 5 ActionScript Core Language Elements Availability Flash Player 5. Usage var variableName [= value1] [...,variableNameN [=valueN]] Parameters An identifier. variableName The value assigned to the variable. value 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.
  • Page 227 CHAPTER 5 ActionScript Core Language Elements void Availability Flash Player 5. Usage void (expression) function functionName():Void {} Description Usage 1: Operator; a unary operator that discards the value and returns an undefined expression value. The operator is often used in comparisons using the equality ( ) operator to test for void undefined values.
  • Page 228 CHAPTER 5 ActionScript Core Language Elements while Availability Flash Player 4. Usage while(condition) { statement(s); Parameters An expression that evaluates to condition true false The instructions to execute if the condition evaluates to statement(s) true Returns Nothing. Description Statement; evaluates a condition and if the condition evaluates to , runs a statement or series true of statements before looping back to evaluate the condition again.
  • Page 229 i += 3; The following result is written to the log file. See also while, continue, for, for..in while...
  • Page 230 CHAPTER 5 ActionScript Core Language Elements with Availability Flash Player 5. Usage with (object:Object) { statement(s); Parameters An instance of an ActionScript object or movie clip. object An action or group of actions enclosed in curly braces ({}). statement(s) Returns Nothing.
  • Page 231 Instead of using , you can use direct paths. If you find that paths are long and with() 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;...
  • Page 232: 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.
  • Page 233 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.
  • Page 234 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).
  • Page 235 CHAPTER 6 ActionScript Core Classes _accProps Availability Flash Player 6.65. Usage _accProps.propertyName instanceName._accProps.propertyName Parameters An accessibility property name (see the following description for valid names). propertyName The instance name assigned to an instance of a movie clip, button, dynamic text instanceName field, or input text field.
  • Page 236 To refer to the object that represents the entire Flash document, omit the _accProps parameter. The value of must be an object. This means that if no instanceName _accProps object already exists, you must create one, as shown in the following example, before _accProps you can assign values to the properties of the object:...
  • Page 237 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.
  • Page 238 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 if the current function null was not called by another function. Example The following example defines two functions—a caller function, named function1, which calls a another function, named function2: // define the caller function, named function1 var function1:Function = function () {...
  • Page 239 Description Property; the number of parameters actually passed to a function. Example The following ActionScript includes a function called , which returns the number getArgLength 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.length);...
  • Page 240 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.
  • Page 241 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 An integer that specifies the number of elements in the array. length A list of two or more arbitrary values. The values can be of type element0...elementN Boolean, Number, String, Object, or Array.
  • Page 242 Usage 3: The following example creates the new Array object with an initial go_gos_array 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.join(", ")); // displays elements The initial elements of the array are identified, as shown in the following example: go_gos_array go_gos_array[0] = "Belinda";...
  • Page 243 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. The elements in a nested array are not broken into separate elements in array , as shown in the following example: x_array...
  • Page 244 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());...
  • Page 245 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);...
  • Page 246 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 with two elements, . The myPets_array second line adds two elements to the array.
  • Page 247 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 and then removes the first element from the myPets_array array and assigns it to the variable shifted...
  • Page 248 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 element and all elements up start to, but not including, the element. If you don’t pass any parameters, a duplicate of is created.
  • Page 249 One or more numbers or names of defined constants, separated by the option | (bitwise OR) operator, that change the behavior of the sort from the default. The following values are acceptable for option • 1 or Array.CASEINSENSITIVE • 2 or Array.DESCENDING •...
  • Page 250 Example Usage 1: The following example shows the use of with and without a value passed Array.sort() 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.DESCENDING); trace(fruits_array); // writes strawberries,pineapples,oranges,cherries,apples Usage 2: The following example uses with a compare function:...
  • Page 251 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 |...
  • Page 252 By default, works as described in the following list: Array sortOn() • 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.
  • Page 253 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);...
  • Page 254 Example The following example creates a new array and sorts it according to the fields : The name city first sort uses as the first sort value and as the second. The second sort uses as the name city city first sort value and as the second.
  • Page 255 An integer that specifies the number of elements to be deleted. This number deleteCount includes the element specified in the parameter. If no value is specified for start deleteCount the method deletes all the values from the element to the last element in the array. If the start value is 0, no elements are deleted.
  • Page 256 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 , is my_array.length-1 converted to a concatenated string and separated by commas. To specify a custom separator, use Array.join() Example The following example creates...
  • Page 257 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.unshift()
  • Page 258 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.
  • Page 259 Usage myBoolean.toString() : String Parameters None. Returns A string; "true" "false" Description Method; returns the string representation ( ) of the Boolean object. "true" "false" Example This example creates a variable of type Boolean and uses to convert the value to a toString() string for use in the trace statement: var myBool:Boolean = true;...
  • Page 260 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.
  • Page 261 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. Sets the hour according to local time. Returns the new time Date.setHours() in milliseconds.
  • Page 262 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 year be specified.
  • Page 263 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.
  • Page 264 Example The following example creates a new Date object and uses to determine the current day getDay() 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);...
  • Page 265 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 method to display hour values from that object: getHours()
  • Page 266 Example The following example uses the constructor to create a Date object based on the current time and uses the method to return the milliseconds value from that object: getMilliseconds() var my_date:Date = new Date(); trace(my_date.getMilliseconds()); Date.getMinutes() Availability Flash Player 5. Usage my_date.getMinutes() : Number Parameters...
  • Page 267 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 method to return the month value from that object: getMonth()
  • Page 268 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.
  • Page 269 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();...
  • Page 270 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() .
  • Page 271 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() .
  • Page 272 Example The following example creates a new Date object and uses to return the getUTCMilliseconds() 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;...
  • Page 273 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() . The value returned by can differ from the value Date.getMonth() Date.getUTCMonth() returned by...
  • Page 274 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.
  • Page 275 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 year years; for example, 99 is not the year 1999, but the year 99. An integer from 0 (January) to 11 (December).
  • Page 276 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 to change the time to 4:00 p.m.: Date.setHours()
  • Page 277 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.
  • Page 278 Example The following example initially creates a new Date object, setting the date to May 15, 2004, and uses to change the date to June 15, 2004: Date.setMonth() 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.
  • Page 279 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 to change the time to 8:30 a.m.: Date.setTime()
  • Page 280 Date.setUTCFullYear() Availability Flash Player 5. Usage my_date.setUTCFullYear(year:Number [, month:Number [, date:Number]]) : Number Parameters An integer that represents the year specified as a full four-digit year, such as 2000. year An integer from 0 (January) to 11 (December). This parameter is optional. month An integer from 1 to 31.
  • Page 281 Parameters A number; an integer from 0 (midnight) to 23 (11 p.m.). hour A number; an integer from 0 to 59. This parameter is optional. minute A number; an integer from 0 to 59. This parameter is optional. second A number; an integer from 0 to 999. This parameter is optional. millisecond Returns An integer.
  • Page 282 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() change the milliseconds value to 575: var my_date:Date = new Date(2004,4,15,8,30,0,250); trace(my_date.getUTCMilliseconds());...
  • Page 283 Parameters An integer from 0 (January) to 11 (December). month An integer from 1 to 31. This parameter is optional. date 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.
  • Page 284 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 is an integer between 0–99, sets the year year setYear year at 1900 + ; otherwise, the year is the value of the parameter.
  • Page 285 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 Date object as a string: dateOfBirth_date var dateOfBirth_date:Date = new Date(74, 7, 12, 18, 15); trace (dateOfBirth_date);...
  • Page 286 Example The following example creates a new Date object defined in universal time. maryBirthday_date This is the universal time variation of the example used for the constructor method. new Date var maryBirthday_date:Date = new Date(Date.UTC(1974, 7, 12)); trace(maryBirthday_date); // output will be in local time and will vary accordingly // for Pacific Daylight Time the output will be seven hours earlier than UTC: // Sun Aug 11 17:00:00 GMT-0700 1974 Chapter 6: ActionScript Core Classes...
  • Page 287 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 constructor function. Typically, you throw a new Error object from within a code Error block that is then caught by a...
  • Page 288 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 "...
  • Page 289 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)) {...
  • Page 290 Returns A string. Description Method; returns the string by default or the value contained in "Error" 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.");...
  • Page 291 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.
  • Page 292 The following simple example shows how passes an array of parameters: apply() 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");...
  • Page 293 Function.call() Availability Flash Player 6. Usage myFunction.call(thisObject:Object, parameter1, ..., parameterN) Parameters An object that specifies the value of within the function body. thisObject this A parameter to be passed to the . You can specify zero or parameter1 myFunction more parameters. parameterN Returns Nothing.
  • Page 294 var obj:Object = new myObject(); myMethod.call(obj, obj); statement displays: trace() statement sends the following code to the log file: trace() this == obj? true See also Function.apply() Chapter 6: ActionScript Core Classes...
  • Page 295 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.
  • Page 296 Property Description Key code Key.PGUP The key code value for the Page Up key. The key code value for the Right Arrow key. Key.RIGHT The key code value for the Shift key. Key.SHIFT Key.SPACE The key code value for the Spacebar. Key.TAB The key code value for the Tab key.
  • Page 297 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 and makes information about the shortcut available to screen readers (see my_btn ). In this example, when you press Control+7 the function writes the text _accProps myOnPress...
  • Page 298 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 . The onKeyDown last line uses to register the listener with the Key object so that it can receive addListener()
  • Page 299 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.DELETEKEY:Number Description...
  • Page 300 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 a constant distance (10) when you press car_mc the arrow keys.
  • Page 301 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 a constant distance (10) when you press car_mc the arrow keys.
  • Page 302 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();...
  • Page 303 Example The following example calls the method any time a key is pressed. The example getAscii() creates a listener object named and defines a function that responds to the keyListener event by calling . The object is then registered to the onKeyDown Key.getAscii() keyListener...
  • Page 304 Example The following example calls the method any time a key is pressed. The example getCode() creates a listener object named and defines a function that responds to the keyListener event by calling . The object is then registered to the onKeyDown Key.getCode() keyListener...
  • Page 305 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;...
  • Page 306 Parameters The key code value assigned to a specific key or a Key class property associated with a keycode specific key. To match the returned key code value with the key on a standard keyboard, see Appendix B, “Keyboard Keys and Key Code Values,” on page 811.
  • Page 307 Information is written to the log file when you press the Caps Lock key. The log file writes either , depending on whether the Caps Lock is activated using the isToggled method. true false The following example creates two text fields that update when the Caps Lock and Num Lock keys are toggled.
  • Page 308 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 you must create a listener object. You onKeyDown, can then define a function for and use...
  • Page 309 Description Listener; notified when a key is released. To use you must create a listener object. You onKeyUp, can then define a function for and use to register the listener with the onKeyUp addListener() Key object, as shown in the following example: var keyListener:Object = new Object();...
  • Page 310 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 when you press the Page Down and car_mc Page Up keys. var keyListener:Object = new Object();...
  • Page 311 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 a constant distance (10) when you press...
  • Page 312 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 when you press Shift. car_mc var keyListener:Object = new Object(); keyListener.onKeyDown = function() { if (Key.isDown(Key.SHIFT)) { car_mc._xscale *= 2;...
  • Page 313 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.
  • Page 314 Description Property; constant associated with the key code value for the Up Arrow key (38). Example The following example moves a movie clip called a constant distance (10) when you press car_mc the arrow keys. A sound plays when you press the Spacebar. Give a sound in the library a linkage identifier of for this example.
  • Page 315 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.
  • Page 316 Property summary for the LoadVars class Property Description A string that indicates the MIME type of the data. LoadVars.contentType LoadVars.loaded A Boolean value that indicates whether a load 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...
  • Page 317 Parameters A string that represents an HTTP request header name. headerName A string that represents the value associated with headerValue headerName Returns Nothing. Description Method; adds or changes HTTP request headers (such as ) sent Content-Type SOAPAction with actions. In the first usage, you pass two strings to the method: POST headerName .
  • Page 318 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() . The default is application/x-www-form-urlencoded. LoadVars.sendAndLoad() Example The following example creates a LoadVars object and displays the default content type of the data that is sent to the server.
  • Page 319 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() .
  • Page 320 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.
  • Page 321 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.load() Availability Flash Player 6;...
  • Page 322 } 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.loaded:Boolean...
  • Page 323 LoadVars.onData Availability Flash Player 6. Usage my_lv.onData = function(src:String) { // your statements here Parameters A string or ; the raw (unparsed) data from a undefined LoadVars.load() 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.
  • Page 324 LoadVars.onLoad Availability Flash Player 6. Usage my_lv.onLoad = function(success:Boolean) { // your statements here Parameters A Boolean value that indicates whether the load operation ended in success ( ) or success true failure ( false Returns A Boolean value. Description Event handler;...
  • Page 325 Returns A Boolean value; if no parameters are specified, otherwise. false true Description Method; sends the variables in the object to the specified URL. All enumerable variables in my_lv are concatenated into a string in the format by my_lv application/x-www-form-urlencoded default, and the string is posted to the URL using the HTTP method.
  • Page 326 Parameters A string; the URL to which to upload variables. If the SWF file issuing this call is running in a web browser, must be in the same domain as the SWF file; for details, see “Description”. LoadVars; the LoadVars object that receives the downloaded variables. targetObject A string;...
  • Page 327 Example The following example instantiates a new object, creates two properties, and uses LoadVars() to return a string containing both properties in URL encoded format: toString() var my_lv:LoadVars = new LoadVars(); my_lv.name = "Gary"; my_lv.age = 26; trace (my_lv.toString()); //output: age=26&name=Gary LoadVars.toString()
  • Page 328 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 or JavaScript. LocalConnection objects can communicate only fscommand() 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.
  • Page 329 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 Invoked whenever the current (receiving) LocalConnection LocalConnection.allowDomain object receives a request to invoke a method from a sending LocalConnection object.
  • Page 330 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.allowDomain = function([sendingDomain:String]) : Boolean { // Your statements here return true or false...
  • Page 331 In files authored for Flash Player 6, the parameter contains the superdomain of sendingDomain the caller. In files authored for Flash Player 7 or later, the parameter contains the sendingDomain 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.
  • Page 332 += aString+newline; aLocalConn.allowDomain = function(sendingDomain) { return (sendingDomain == this.domain() || sendingDomain == "www.macromedia.com"); aLocalConn.connect("_mylc"); When published for Flash Player 7 or later, exact domain matching is used. This means that the example will fail if the SWF files are located at www.thatDomain.com but will work if the files are located at thatDomain.com.
  • Page 333 SWF files published for Flash Player 7 or later. Example The following example allows connections from the current domain or from www.macromedia.com, or allows insecure connections only from the current domain. this.createTextField("welcome_txt", this.getNextHighestDepth(), 10, 10, 100, 20);...
  • Page 334 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. Issue this command when you no longer want the object to accept commands—for example, when you want to issue a command using the same parameter in...
  • Page 335 close_button.addEventListener("click", closeListener); See also LocalConnection.connect() LocalConnection.connect() Availability Flash Player 6. Usage receiving_lc.connect(connectionName:String) : Boolean Parameters A string that corresponds to the connection name specified in the connectionName command that wants to communicate with LocalConnection.send() receiving_lc Returns A Boolean value: if no other process running on the same client computer has already issued true this command using the same value for the parameter;...
  • Page 336 If you are implementing communication between SWF files in different domains, specifying a string for that begins with an underscore (_) will make the SWF with the connectionName receiving LocalConnection object more portable between domains. Here are the two possible cases: •...
  • Page 337 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.onEnterFrame = function() { playback_pb.setProgress(my_sound.position, my_sound.duration);...
  • Page 338 Method; returns a string representing the domain of the location of the current SWF file. In SWF files published for Flash Player 6, the returned string is the superdomain of the current SWF file. For example, if the SWF file is located at www.macromedia.com, this command returns "macromedia.com"...
  • Page 339 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 (line 11). "sum" The Flash Player resolves the name of this connection to (see "mydomain.com:sum"...
  • Page 340 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...
  • Page 341 If the information object returned by this event handler contains a value of , Flash level error 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 command that invoked this handler.
  • Page 342 A string specifying the name of the method to be invoked in the receiving method LocalConnection object. The following method names cause the command to fail: send , and connect close domain onStatus allowDomain Optional parameters to be passed to the specified method. p1,...pN Returns A Boolean value:...
  • Page 343 See also LocalConnection.allowDomain, LocalConnection.connect(), LocalConnection.domain(), LocalConnection.onStatus LocalConnection.send()
  • Page 344 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.
  • Page 345 Method Description Math.pow() Computes raised to the power of the Returns a pseudo-random number between 0.0 and 1.0. Math.random() Rounds to the nearest integer. Math.round() Math.sin() Computes a sine. Math.sqrt() Computes a square root. Computes a tangent. Math.tan() Property summary for the Math class All the following properties for the Math class are constants: Property Description...
  • Page 346 Example The following example shows how returns the absolute value of a number and does Math.abs() not affect the value of the parameter (called 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.
  • Page 347 Parameters 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 in radians. Example The following example displays the arc sine for several values.
  • Page 348 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.
  • Page 349 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()
  • Page 350 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;...
  • Page 351 Description Method; returns the value of the base of the natural logarithm (e), to the power of the exponent specified in the parameter . The constant can provide the value of e. Math.E Example The following example displays the logarithm for two number values. trace(Math.exp(1));...
  • Page 352 Parameters A number or expression with a value greater than 0. Returns The logarithm of parameter Description Method; returns the logarithm of parameter 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));...
  • Page 353 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.
  • Page 354 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 A number or expression.
  • Page 355 Description Method; evaluates and returns the smaller value. Example The following example displays , which is the smaller of Sat Dec 25 00:00:00 GMT-0700 2004 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());...
  • Page 356 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.
  • Page 357 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.
  • Page 358 Returns A number; an integer. Description Method; rounds the value of the parameter up or down to the nearest integer and returns the value. If parameter 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.
  • Page 359 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.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); See also Math.acos(), Math.asin(), Math.atan(), Math.atan2(), Math.cos(), Math.tan() Math.sqrt() Availability...
  • Page 360 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.addListener(mouseListener); Math.SQRT1_2 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.
  • Page 361 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...
  • Page 362 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.
  • Page 363 Description Method; registers an object to receive notifications of the onMouseDown onMouseMove , and listeners. (The listener is supported only in onMouseUp onMouseWheel onMouseWheel Windows.) parameter should contain an object that has a defined method for at least one newListener of the listeners.
  • Page 364 Description Listener; notified when the mouse is pressed. To use the listener, you must create a onMouseDown listener object. You can then define a function for and use onMouseDown addListener() register the listener with the Mouse object, as shown in the following code: var someListener:Object = new Object();...
  • Page 365 Mouse.onMouseMove Availability Flash Player 6. Usage someListener.onMouseMove Parameters None. Returns Nothing. Description Listener; notified when the mouse moves. To use the listener, you must create a onMouseMove listener object. You can then define a function for and use onMouseMove addListener() register the listener with the Mouse object, as shown in the following code: var someListener:Object = new Object();...
  • Page 366 Mouse.onMouseUp Availability Flash Player 6. Usage someListener.onMouseUp Parameters None. Returns Nothing. Description Listener; notified when the mouse is released. To use the listener, you must create a onMouseUp listener object. You can then define a function for and use to register onMouseUp addListener() the listener with the Mouse object, as shown in the following code:...
  • Page 367 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 delta user rolls the mouse wheel.
  • Page 368 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 An object. listener Returns If the object is successfully removed, the method returns ;...
  • Page 369 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.addEventListener("click", clearListener);...
  • Page 370 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 . Give a movie clip a Linkage identifier of , and add the following my_mc cursor_help_id...
  • Page 371 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.
  • Page 372 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 value a number. The default value is 0 if is not provided.
  • Page 373 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);...
  • Page 374 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.
  • Page 375 Parameters Specifies the numeric base (from 2 to 36) to use for the number-to-string conversion. If radix you do not specify the 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...
  • Page 376 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.
  • Page 377 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 property. constructor Example The following example creates a generic object named myObject: var myObject:Object = new Object(); Object.addProperty() Availability Flash Player 6.
  • Page 378 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).
  • Page 379 The previous example works, but the properties are added to every bookcount bookname instance of the object, which requires having two properties for every instance of the object. Book If there are many properties, such as in a class, they could consume a bookcount bookname, great deal of memory.
  • Page 380 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 object.
  • Page 381 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 symbolID ActionScript class. A reference to the constructor function of the ActionScript class or theClass null unregister the symbol.
  • Page 382 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 property. To aid understanding, key statements that differ from the __resolve previous usage are in bold typeface.
  • Page 383 // 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;...
  • Page 384 // 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;...
  • Page 385 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();...
  • Page 386 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 A string; the name of the object property that should no longer be watched. prop Returns A Boolean value: if the watchpoint is successfully removed, otherwise.
  • Page 387 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());...
  • Page 388 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 as the myObject containing object. Your can use the statement in your method definition to affect the value of the return callback...
  • Page 389 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"...
  • Page 390 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 method, lets you render print() dynamic content offscreen, prompt users with a single Print dialog box, and print an unscaled...
  • Page 391 // 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++;...
  • Page 392 Parameters A number or string; the level or instance name of the movie clip to print. Pass a number target to specify a level (for example, 0 is the movie), or a string (in quotation marks [""]) to _root specify the instance name of a movie clip. An optional object that specifies the area to print, in the following format: printArea {xMin:topLeft, xMax:topRight, yMin:bottomLeft, yMax:bottomRight}...
  • Page 393 Returns A Boolean value: if the page is successfully sent to the print spooler; otherwise. true false Description Method; sends the specified level or movie clip as a single page to the print spooler. Before using this method, you must use ;...
  • Page 394 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++; // 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 if (my_pj.addPage(5, {xMin:50,xMax:550,yMin:70,yMax:670},null, 4)){...
  • Page 395 PrintJob.send() Availability Flash Player 7. Usage my_pj.send() : Void Parameters None. Returns Nothing. Description Method; used following to send spooled pages to PrintJob.start() PrintJob.addPage() the printer. Because calls to will not be successful if related calls to PrintJob.send() failed, you should check that calls to PrintJob.start() PrintJob.addpage() were successful before calling...
  • Page 396 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 method returns PrintJob.start() successfully, the following read-only properties are populated, representing the user’s print settings: Property Type Units Notes...
  • Page 397 // 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".
  • Page 398 CHAPTER 6 ActionScript Core Classes SharedObject class 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 to create a shared object, such as a calculator with memory, in the SharedObject.getLocal() player.
  • Page 399 • If the user selects None (moves the slider all the way to the left), all SharedObject.flush() commands issued for the object return and the player asks the user if additional "pending", disk space can be allotted to make room for the object. •...
  • Page 400 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 is still active, and is now empty. my_so my_so Example The following example sets data in the shared object, and then empties all of the data from the shared object.
  • Page 401 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.data[prop]); All attributes of a shared object’s property are saved if the object is persistent, and the shared data object contains the following information: userName: Ramona adminPrivileges: true itemNumbers: 101,346,483...
  • Page 402 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 minimumDiskSpace for this object. The default value is 0. Returns A Boolean value: , or a string value of , as described in the following list: true false...
  • Page 403 Example The following function gets a shared object, and fills writable properties with user- my_so, provided settings. Finally, is called to save the settings and allot a minimum flush() 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.com/app/sys");...
  • Page 404 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 is specified.
  • Page 405 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;...
  • Page 406 SharedObject.onStatus Availability Flash Player 6. Usage myLocalSharedObject.onStatus = function(infoObject:Object) { // your statements here Parameters A parameter defined according to the status message. infoObject Returns Nothing. Description Event handler; invoked every time an error, warning, or informational note is posted for a shared object.
  • Page 407 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.htmlText = "<textformat tabStops='[50]'>";...
  • Page 408 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.
  • Page 409 Method Description String.substring() Returns the characters between two indexes in a string. Converts the string to lowercase and returns the result; does not change String.toLowerCase() 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.
  • Page 410 Parameters A number; an integer specifying the position of a character in the string. The first index character is indicated by , and the last character is indicated by my_str.length-1 Returns A character. Description Method; returns the character in the position specified by the parameter .
  • Page 411 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 Zero or more values to be concatenated.
  • Page 412 Description Method; returns a string comprising the characters represented by the ASCII values in the parameters. Example The following example uses to insert an character in the e-mail address: fromCharCode() var address_str:String = "dog"+String.fromCharCode(64)+"house.net"; trace(address_str); // output: dog@house.net String.indexOf() Availability Flash Player 5.
  • Page 413 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 String; the string for which to search. substring Number; an optional integer specifying the starting point from which to search for startIndex substring Returns...
  • Page 414 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.length - 1 Example The following example creates a new String object and uses...
  • Page 415 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 is a negative start start number, the starting point is determined from the end of the string, where -1 is the last character. A number;...
  • Page 416 // 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 A string; the character or string at which splits.
  • Page 417 The following example shows that if you use an empty string ( ) for the parameter, delimiter "" 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;...
  • Page 418 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 used to start my_str create the substring. Valid values for are 0 through - 1. If is a start String.length...
  • Page 419 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 uppercase characters and then creates a copy of that string using to convert all uppercase characters to lowercase characters: toLowerCase()
  • Page 420 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: "...
  • Page 421 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...
  • Page 422 If this value is , the settings and data for a SWF file hosted at here.xyz.com are stored in a true 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 , the settings and data false for SWF files hosted at here.xyz.com, there.xyz.com, and xyz.com are shared, and are all stored in...
  • Page 423 In addition to these specific methods, Flash also provides a super function called onStatus , which serves as a secondary error message handler. If an instance of the System.onStatus LocalConnection, NetStream, or SharedObject class passes an information object with a level property of “error”, but you have not defined an function for that particular instance, onStatus...
  • Page 424 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 onto the system Clipboard: "Hello World"...
  • Page 425 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 •...
  • Page 426 If you load external text files that are not Unicode-encoded, you should set System.useCodepage . Add the following code as the first line of code in the SWF file that is loading the data: true 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.
  • Page 427 MP3 support, 1600 x 1200 pixel resolution, is running Windows XP, and Flash Player 7 (7.0.19.0): "A=t&SA=t&SV=t&EV=t&MP3=t&AE=t&VE=t&ACC=f&PR=t&SP=t&SB=f&DEB=t&V=WIN%207%2C0%2 C19%2C0&M=Macromedia%20Windows&R=1600x1200&DP=72&COL=color&AR=1.0&OS=Window s%20XP&L=en&PT=External&AVD=f&LFD=f&WD=f" Property summary for the System.capabilities object All properties of the System.capabilities object are read-only.
  • Page 428 Property Description Server string Indicates whether the player supports the System.capabilities.hasScreenBroadcast development of screen broadcast applications to be run through the Flash Communication Server. System.capabilities.hasScreenPlayback Indicates whether the player supports the playback of screen broadcast applications that are being run through the Flash Communication Server.
  • Page 429 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 ( ) or allowed ( ). The server string is true false Example The following example traces the value of this read-only property: trace(System.capabilities.avHardwareDisable);...
  • Page 430 Description Read-only property: a Boolean value that is if the player is running on a system that has true audio capabilities; otherwise. The server string is false Example The following example traces the value of this read-only property: trace(System.capabilities.hasAudio); System.capabilities.hasAudioEncoder Availability Flash Player 6.
  • Page 431 System.capabilities.hasMP3 Availability Flash Player 6. Usage System.capabilities.hasMP3:Boolean Description Read-only property: a Boolean value that is if the player is running on a system that has an true MP3 decoder; otherwise. The server string is false Example The following example traces the value of this read-only property: trace(System.capabilities.hasMP3);...
  • Page 432 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 if the player supports the playback of screen true broadcast applications that are being run through the Flash Communication Server; false otherwise.
  • Page 433 Description Read-only property: a Boolean value that is if the player can play streaming video; true false otherwise. The server string is 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.hasVideoEncoder:Boolean Description Read-only property: a Boolean value that is...
  • Page 434 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.
  • Page 435 Language Russian Simplified Chinese zh-CN Spanish Swedish Traditional Chinese zh-TW Turkish 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.localFileReadDisable:Boolean Description Read-only property; a Boolean value that indicates whether read access to the user’s hard disk has been administratively prohibited ( ) or allowed ( ).
  • Page 436 Description Read-only property; a string that indicates the manufacturer of Flash Player, in the format could be , or "Macromedia OSName" OSName "Windows" "Macintosh" "Linux" "Other OS ). The server string is Name" Example The following example traces the value of this read-only property: trace(System.capabilities.manufacturer);...
  • Page 437 System.capabilities.playerType Availability Flash Player 7. Usage System.capabilities.playerType;String Description Read-only property; a string that indicates the type of player. This property can have one of the following values: • for the Flash StandAlone Player "StandAlone" • for the Flash Player version used by test movie mode, "External"...
  • Page 438 Description Read-only property; a number that indicates the dots-per-inch (dpi) resolution of the screen, in pixels. The server string is 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;...
  • Page 439 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.0&OS=Windows%20 XP&L=en&PT=External&AVD=f&LFD=f&WD=f Example The following example traces the value of this read-only property: trace(System.capabilities.serverString); System.capabilities.version Availability Flash Player 6.
  • Page 440 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.
  • Page 441 SWF file to load; the parent will already be loaded by the time the child loads. Example The SWF file located at www.macromedia.com/MovieA.swf contains the following lines: System.security.allowDomain("www.shockwave.com"); loadMovie("http://www.shockwave.com/MovieB.swf", my_mc); Because MovieA contains the...
  • Page 442 HTTPS protocol. This implementation maintains the integrity provided by the HTTPS protocol. Macromedia does not recommend using this method to override the default behavior because it compromises HTTPS security. However, you might need to do so, for example, if you must permit access to HTTPS files published for Flash Player 7 or later from HTTP files published for Flash Player 6.
  • Page 443 Parameters 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 parameter. Flash Player uses policy files as a permission mechanism to permit Flash movies to load data from servers other than their own.
  • Page 444 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.
  • Page 445 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.
  • Page 446 Property summary for the XML class Property Description The MIME type transmitted to the server. XML.contentType XML.docTypeDecl Sets and returns information about an XML document’s declaration. DOCTYPE Read-only; references the first child in the list for the specified node. XML.firstChild When set to , discards, during the parsing process, text nodes that XML.ignoreWhite...
  • Page 447 Constructor for the XML class Availability Flash Player 5. Usage new XML([source:String]) : XML Parameters A string; the XML text parsed to create the new XML object. source 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.
  • Page 448 Returns Nothing. Description Method; adds or changes HTTP request headers (such as ) sent Content-Type SOAPAction with actions. In the first usage, you pass two strings to the method: POST headerName . In the second usage, you pass an array of strings, alternating header names and headerValue header values.
  • Page 449 Description Method; appends the specified node to the XML object’s child list. This method operates directly on the node referenced by the parameter; it does not append a copy of the node. If the childNode node to be appended already exists in another tree structure, appending the node to the new location will remove it from its current location.
  • Page 450 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 associative array, the key index is a string representing the name of XML.attributes the attribute.
  • Page 451 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() methods to manipulate child nodes.
  • Page 452 Parameters A Boolean value; if set to , the children of the specified XML object will be deep true 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.
  • Page 453 // </rootNode> // 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, to rootNode rootNode.appendChild(rootClone); trace(rootNode); // output (with line breaks added): // <rootNode> <oldest />...
  • Page 454 XML.createElement() Availability Flash Player 5. Usage my_xml.createElement(name:String) : XMLNode Parameters The tag name of the XML element being created. name 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.
  • Page 455 Parameters A string; the text used to create the new text node. text 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.
  • Page 456 XML.docTypeDecl Availability Flash Player 5. Usage my_xml docTypeDecl:String Description Property; specifies information about the XML document’s declaration. After the XML DOCTYPE text has been parsed into an XML object, the property of the XML object is XML.docTypeDecl set to the text of the XML document’s declaration (for example, DOCTYPE <!DOCTYPE greeting...
  • Page 457 Example The following example shows how to use to loop through a node’s child nodes: XML.firstChild // 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");...
  • Page 458 Description Method; returns the number of bytes loaded (streamed) for the XML document. You can compare the value of with the value of to determine what getBytesLoaded() getBytesTotal() percentage of an XML document has loaded. Example The following example shows how to use the method with the XML.getBytesLoaded() method to trace the progress of an...
  • Page 459 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 if the specified XML object has child nodes; otherwise, returns true false Example...
  • Page 460 XML.ignoreWhite Availability Flash Player 5. Usage my_xml.ignoreWhite:boolean XML.prototype.ignoreWhite:boolean Parameters A Boolean ( ) value. boolean true false Description Property; default setting is . When set to , text nodes that contain only white space are false true discarded during the parsing process. Text nodes with leading or trailing white space are unaffected.
  • Page 461 /* output (line breaks added for clarity): <house> <kitchen> ceramic tile </kitchen> <bathroom>linoleum</bathroom> <foyer /> </house> If you then change the setting of , or simply remove that line of flooring.ignoreWhite false code entirely, the fourteen space characters in the tag will be preserved: foyer // set the ignoreWhite property to false (default value)
  • Page 462 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 property is if the node does not have children. This property cannot be XML.lastChild null used to manipulate child nodes;...
  • Page 463 <oldest /> The following example creates a new XML packet and uses the property to XML.lastChild iterate through the child nodes of the root node: // create a new XML document var doc:XML = new XML("<rootNode><oldest /><middle /><youngest /></ rootNode>"); var rootNode:XMLNode = doc.firstChild;...
  • Page 464 The value you pass for the 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 cross- domain policy file on the server that is hosting the SWF file.
  • Page 465 Example The following example uses the property in a simple script: XML.loaded 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 handler invokes. If the call completes onLoad successfully, writes to the log file for the...
  • Page 466 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 ( == 1), is the name of the tag that represents the node in the XML nodeType nodeName file.
  • Page 467 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 value, either 1 for an XML element or 3 for a text node. nodeType is a numeric value from the NodeType enumeration in the W3C DOM Level 1 nodeType...
  • Page 468 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);...
  • Page 469 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.
  • Page 470 XML.onData Availability Flash Player 5. Usage my_xml.onData = function(src:String) { // your statements here Parameters A string or ; the raw data, usually in XML format, that is sent by the server. undefined Returns Nothing. Description Event handler; invoked when XML text has been completely downloaded from the server, or when an error occurs downloading XML text from a server.
  • Page 471 Parameters A Boolean value that evaluates to if the XML object is successfully loaded with a success true operation; otherwise, it is XML.load() XML.sendAndLoad() false Returns Nothing. Description Event handler; invoked by Flash Player when an XML document is received from the server. If the XML document is received successfully, the parameter is .
  • Page 472 Description Read-only property; an XMLNode value that references the parent node of the specified XML object, or returns if the node has no parent. This is a read-only property and cannot be used null to manipulate child nodes; use the , and appendChild() insertBefore()
  • Page 473 Description Method; parses the XML text specified in the parameter, and populates the specified source 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 = "<state name=\"California\">...
  • Page 474 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 = "<state name=\"California\">...
  • Page 475 Parameters String; the destination URL for the specified XML object. String; the browser window to show data that the server returns: window • specifies the current frame in the current window. _self • specifies a new window. _blank • specifies the parent of the current frame. _parent •...
  • Page 476 Returns Nothing. Description Method; encodes the specified XML object into an XML document, sends it to the specified URL using the method, downloads the server’s response, and loads it into the POST specified in the parameters. The server response loads in the same manner targetXMLobject used by the method.
  • Page 477 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. •...
  • Page 478 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;...
  • Page 479 For top-level XML objects (those created with the constructor), the method XML.toString() outputs the document’s XML declaration (stored in the property), followed by the XML.xmlDecl document’s declaration (stored in the property), followed by the text DOCTYPE XML.docTypeDecl representation of all XML nodes in the object. The XML declaration is not output if the property is .
  • Page 480 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.text = "Unable to load remote XML."+newline+newline; my_txt.text += "loaded in: "+elapsedTime+"...
  • Page 481 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.
  • Page 482 CHAPTER 6 ActionScript Core Classes XMLSocket class 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.
  • Page 483 Method summary for the XMLSocket class Method Description Closes an open socket connection. XMLSocket.close() XMLSocket.connect() Establishes a connection to the specified server. Sends an XML object to the server. XMLSocket.send() Event handler summary for the XMLSocket class Event handler Description XMLSocket.onClose Invoked when an XMLSocket connection is closed.
  • Page 484 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();...
  • Page 485 If you specify for the parameter, the host contacted is the one where the SWF file null host calling resides. For example, if the SWF file was downloaded from XMLSocket.connect() www.yoursite.com, specifying for the host parameter is the same as entering the IP address null for www.yoursite.com.
  • Page 486 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.
  • Page 487 Description Event handler; invoked by Flash Player when a connection request initiated through has succeeded or failed. If the connection succeeded, the XMLSocket.connect() success parameter is ; otherwise the parameter is true success false The default implementation of this method performs no actions. To override the default implementation, you must assign a function containing custom actions.
  • Page 488 XMLSocket.onXML Availability Flash Player 5. Usage myXMLSocket.onXML = function(object:XML) { // your statements here Parameter An XML object that contains a parsed XML document received from a server. object Returns Nothing. Description Event handler; invoked by Flash Player when the specified XML object containing an XML document arrives over an open XMLSocket connection.
  • Page 489 XMLSocket.send() Availability Flash Player 5. Usage myXMLSocket.send(object:XML) : Void Parameters An XML object or other data to transmit to the server. object Returns Nothing. Description Method; converts the XML object or data specified in the parameter to a string and object transmits it to the server, followed by a zero (0) byte.
  • Page 490: 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.
  • Page 491 CHAPTER 7 ActionScript for Flash asfunction Availability Flash Player 5. Usage asfunction:function:Function,"parameter":String Parameters An identifier for a function. function A string that is passed to the function named in the parameter. parameter function Returns Nothing. Description Protocol; a special protocol for URLs in HTML text fields. In HTML text fields, text can be linked using the HTML tag.
  • Page 492 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...
  • Page 493 Property (read-only) Description Camera.motionLevel The amount of motion required to invoke Camera.onActivity(true) The number of milliseconds between the time when the camera stops Camera.motionTimeOut detecting motion and the time is invoked. Camera.onActivity(false) Camera.muted A Boolean value that specifies whether the user has allowed or denied access to the camera.
  • Page 494 Example The following example detects the amount of motion the camera detects using the property: activityLevel // 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);...
  • Page 495 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. This property cannot be set;...
  • Page 496 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.
  • Page 497 Parameters An optional zero-based integer that specifies which camera to get, as determined from index the array returned by the property. To get the default camera (which is Camera.names recommended for most applications), omit this parameter. Returns • is not specified, this method returns a reference to the default camera or, if it is in use index by another application, to the first available camera.
  • Page 498 returns , either the camera is in use by another application, or there are no Camera.get null cameras installed on the system. To determine whether any cameras are installed, use . To display the Flash Player Camera Settings panel, which lets the user Camera.names.length choose the camera to be referenced by , use...
  • Page 499 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.index:Number Description Read-only property;...
  • Page 500 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 . Acceptable values range from 0 to 100. The default value is 50. Camera.onActivity(true) Video can be displayed regardless of the value of the property.
  • Page 501 /* 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.
  • Page 502 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. Usage active_cam.muted:Boolean Description Read-only property; a Boolean value that specifies whether the user has denied access to the camera ( ) or allowed access ( ) in the Flash Player Privacy Settings panel.
  • Page 503 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.
  • Page 504 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;...
  • Page 505 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 A parameter defined according to the status message. infoObject Returns Nothing. Description Event handler; invoked when the user allows or denies access to the camera. If you want to respond to this event handler, you must create a function to process the information object generated by the camera.
  • Page 506 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.
  • Page 507 Camera.setMode() Availability Flash Player 6. Usage active_cam.setMode(width:Number, height:Number, fps:Number [,favorSize:Boolean]) : Void Parameters The requested capture width, in pixels. The default value is 160. width The requested capture height, in pixels. The default value is 120. height The requested rate at which the camera should capture data, in frames per second. The default value is 15.
  • Page 508 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. Usage active_cam.setMotionLevel(sensitivity:Number [, timeout:Number]) : Void Parameters...
  • Page 509 • To determine the amount of motion the camera is currently detecting, use the property. Camera.activityLevel 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;...
  • Page 510 Parameters An integer that specifies the maximum amount of bandwidth that the current bandwidth 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 , pass 0 for .
  • Page 511 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, 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.
  • Page 512 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 to create a Color object before calling its methods.
  • Page 513 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 call. setRGB() Example The following code retrieves the RGB value for the Color object , converts the value to my_color a hexadecimal string, and assigns it to the...
  • Page 514 Example The following example gets the transform object, and then sets new percentages for colors and alpha of relative to their current values: my_mc 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);...
  • Page 515 Color.setTransform() Availability Flash Player 5. Usage my_color.setTransform(colorTransformObject:Object) : Void Parameters An object created with the constructor. This instance of colorTransformObject new Object Object class must have the following properties that specify color transform values: . These properties are explained below. Returns Nothing.
  • Page 516 Example This example creates a new Color object for a target SWF file, creates a generic object called with the properties defined above, and uses the method to myColorTransform setTransform() pass the to a Color object. colorTransformObject // Create a color object called my_color for the target my_mc var my_color:Color = new Color(my_mc);...
  • Page 517 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.
  • Page 518 Property summary for the ContextMenu class Property Description An object whose members correspond to built-in context ContextMenu.builtInItems menu items. An array, undefined by default, that contains ContextMenu.customItems ContextMenuItem objects. Event handler summary for the ContextMenu class Property Description Invoked before the menu is displayed. ContextMenu.onSelect Constructor for the ContextMenu class Availability...
  • Page 519 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...
  • Page 520 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.
  • Page 521 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 array (for example, using ).
  • Page 522 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.
  • Page 523 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: "...
  • Page 524 Menu items are compared without regard to case, punctuation, or white space. None of the following words can appear in a custom item: Macromedia, Flash Player, or Settings. Method summary for the ContextMenuItem class...
  • Page 525 Constructor for the ContextMenuItem class Availability Flash Player 7. Usage new ContextMenuItem(caption:String, callbackFunction:Function, [ separatorBefore:Boolean, [ enabled:Boolean, [ visible:Boolean] ] ] ) : ContextMenuItem Parameters A string that specifies the text associated with the menu item. caption A function that you define, which is called when the menu item is selected. callbackFunction A Boolean value that indicates whether a separator bar should appear above separatorBefore...
  • Page 526 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();...
  • Page 527 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.
  • Page 528 ContextMenuItem.onSelect Availability Flash Player 7. Usage menuItem_cmi.onSelect = function (obj:Object, menuItem:ContextMenuItem) : Void // your statements here Parameters A reference to the movie clip (or Timeline), button, or selectable text field that the user right-clicked or Control-clicked. A reference to the selected ContextMenuItem object. menuItem Returns Nothing.
  • Page 529 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.
  • Page 530 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.
  • Page 531 , and this new clip is moved on the Stage so it does not overlap the original clip, and newImg_mc the same image is loaded into the second clip. this.createEmptyMovieClip("img_mc", this.getNextHighestDepth()); img_mc.loadMovie("http://www.macromedia.com/images/shared/product_boxes/ 112x112/box_studio_112x112.jpg"); duplicateMovieClip(img_mc, "newImg_mc", this.getNextHighestDepth()); newImg_mc._x = 200; newImg_mc.loadMovie("http://www.macromedia.com/images/shared/product_boxes/ 112x112/box_studio_112x112.jpg");...
  • Page 532 CHAPTER 7 ActionScript for Flash _focusrect 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 is set to its default value of , then a yellow rectangle _focusrect true...
  • Page 533 CHAPTER 7 ActionScript for Flash getProperty() Availability Flash Player 4. Usage getProperty(my_mc:Object, property:Object) : Object Parameters The instance name of a movie clip for which the property is being retrieved. my_mc A property of a movie clip. property Returns The value of the specified property. Description Function;...
  • Page 534 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.
  • Page 535 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. The sound capture rate, in kHz. Microphone.rate The amount of sound required to activate the microphone. Microphone.silenceLevel The number of milliseconds between the time the Microphone.silenceTimeOut...
  • Page 536 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.onActivity = function(active:Boolean) { if (active) { var haloTheme_str:String = "haloGreen"; } else { var haloTheme_str:String = "0xFF0000"; activityLevel_pb.setStyle("themeColor", haloTheme_str); See also Microphone.setGain() Microphone.gain...
  • Page 537 Microphone.get() Availability Flash Player 6. Usage Microphone.get([index:Number]) : Microphone Note: The correct syntax is . To assign the Microphone object to a variable, use Microphone.get() syntax like active_mic = Microphone.get() Parameters An optional zero-based integer that specifies which microphone to get, as determined index from the array that contains.
  • Page 538 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 .
  • Page 539 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. Usage active_mic.muted:Boolean Description Read-only property;...
  • Page 540 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+"...
  • Page 541 status_ta.text += "You have "+microphone_array.length+" device(s) installed."+newline+newline; for (var i = 0; i<microphone_array.length; i++) { status_ta.text += "["+i+"] "+microphone_array[i]+newline; For example, the following information could be displayed: The default device is: Logitech USB Headset You have 2 device(s) installed. [0] Logitech USB Headset [1] YAMAHA AC-XG WDM Audio See also Array...
  • Page 542 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.onStatus = function(infoObject:Object) : Void { // your statements here...
  • Page 543 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...
  • Page 544 Example The following code lets you use a ComboBox instance, called , to change the rate at rate_cb 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);...
  • Page 545 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 to display and a gain_pb...
  • Page 546 Example The following example sets the microphone rate to the user’s preference (which you have assigned to the variable) if it is one of the following values: 5, 8, 11, 22, or 44. If it is not, the userRate value is rounded to the nearest acceptable value that the sound capture device supports. active_mic.setRate(userRate);...
  • Page 547 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 is never invoked.
  • Page 548 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.label = "Activity level: %3"; } else { silenceLevel_pb.indeterminate = true; silenceLevel_pb.setStyle("themeColor", "0xFF0000");...
  • Page 549 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) 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.
  • Page 550 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.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);...
  • Page 551 Example The following example enables the user to control the amount of time between when the microphone stops detecting sound and when is invoked. The Microphone.onActivity(false) user controls this value using a NumericStepper instance called . The silenceTimeOut_nstep ProgressBar instance called modifies its appearance depending on whether the silenceLevel_pb audio stream is considered silent.
  • Page 552 Description Property (read-only); a Boolean value of if echo suppression is enabled, otherwise. true false The default value is unless the user has selected Reduce Echo in the Flash Player false Microphone Settings panel. Example The following example turns on echo suppression if the user selects a CheckBox instance called .
  • Page 553 Frame 1 of your file, the command executes when the SWF file MMExecute() is loaded. For more information on the JSAPI, see www.macromedia.com/go/jsapi_info_en. Example The following command will output the number of items in the library of the current document to the trace window.
  • Page 554 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.
  • Page 555 Method Description MovieClip.globalToLocal() Converts Stage coordinates to the local coordinates of the specified movie clip. Sends the playhead to a specific frame in the movie clip and MovieClip.gotoAndPlay() plays the movie clip. Sends the playhead to a specific frame in the movie clip and MovieClip.gotoAndStop() stops the movie clip.
  • Page 556 Method Description MovieClip.lineStyle() Defines the stroke of lines created with the methods. MovieClip.lineTo() MovieClip.curveTo() Draws a line using the current line style. MovieClip.lineTo() MovieClip.moveTo() Moves the current drawing position to specified coordinates. Property summary for the MovieClip class Property Description MovieClip._alpha The transparency value of a movie clip instance.
  • Page 557 Property Description MovieClip._target Read-only; the target path of a movie clip instance. Read-only; the total number of frames in a movie clip instance. MovieClip._totalframes A Boolean value that indicates whether other movie clips can MovieClip.trackAsMenu receive mouse release events. Read-only; the URL of the SWF file from which a movie clip MovieClip._url was downloaded.
  • Page 558 Event handler Description MovieClip.onLoad Invoked when the movie clip is instantiated and appears in the Timeline. Invoked when the left mouse button is pressed. MovieClip.onMouseDown MovieClip.onMouseMove Invoked every time the mouse is moved. Invoked when the left mouse button is released. MovieClip.onMouseUp Invoked when the mouse is pressed while the pointer is over MovieClip.onPress...
  • Page 559 // 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.
  • Page 560 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.getVolume(); The following example specifies a microphone as the audio source for a dynamically created movie clip instance called audio_mc var active_mic:Microphone = Microphone.get();...
  • Page 561 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 . Use to remove a SWF my_mc MovieClip.removeMovieClip() MovieClip.unloadMovie() file attached with attachMovie() You can extend the methods and event handlers of the MovieClip class by creating a subclass.
  • Page 562 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.beginGradientFill(fillType:String, colors:Array, alphas:Array, ratios:Array, matrix:Object) : Void Parameter Either the string...
  • Page 563 moveTo(100, 100); lineTo(100, 300); lineTo(300, 300); lineTo(300, 100); lineTo(100, 100); endFill(); If a property does not exist then the remaining parameters are all required; the matrixType function fails if any of them are missing. This matrix scales, translates, rotates, and skews the unit gradient, which is defined at (-1,-1) and (1,1).
  • Page 564 If a property exists then it must equal and the remaining parameters are all matrixType "box" 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 or if undefined, no parameters are passed, the path has no fill.
  • Page 565 moveTo(100, 310); lineTo(100, 510); lineTo(600, 510); lineTo(600, 310); lineTo(100, 310); endFill(); 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 .
  • Page 566 You can extend the methods and event handlers of the MovieClip class by creating a subclass. Example The following ActionScript creates a new movie clip at runtime and loads a JPEG image into the movie clip. this.createEmptyMovieClip("logo_mc", this.getNextHighestDepth()); logo_mc.loadMovie("http://www.macromedia.com/images/shared/product_boxes/ 80x92/studio_flashpro.jpg"); See also MovieClip.attachMovie() Chapter 7: ActionScript for Flash...
  • Page 567 MovieClip.createTextField() Availability Flash Player 6. Usage my_mc.createTextField(instanceName:String, depth:Number, x:Number, y:Number, width:Number, height:Number) : Void Parameters A string that identifies the instance name of the new text field. instanceName A positive integer that specifies the depth of the new text field. depth An integer that specifies the x coordinate of the new text field.
  • Page 568 variable = null maxChars = null styleSheet = undefined tabInded = undefined A text field created with receives the following default TextFormat object: createTextField() font = "Times New Roman" size = 12 color = 0x000000 bold = false italic = false underline = false url = ""...
  • Page 569 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 property to direct the playhead of the movie clip _currentframe to advance five frames ahead of its current location: actionClip_mc actionClip_mc.gotoAndStop(actionClip_mc._currentframe + 5);...
  • Page 570 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);...
  • Page 571 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 was dropped. The property always returns a path that starts with a my_mc _droptarget slash ( ).
  • Page 572 Parameters A unique identifier for the duplicate movie clip. newname A unique number specifying the depth at which the SWF file specified is to be placed. depth (Supported for Flash Player 6 and later.) An object containing properties with initObject which to populate the duplicated movie clip.
  • Page 573 Description Property; a Boolean value that indicates whether a movie clip is enabled. The default value of . If is set to , the movie clip’s callback methods and enabled true enabled false on action event handlers are no longer invoked, and the Over, Down, and Up frames are disabled. The property does not affect the Timeline of the movie clip;...
  • Page 574 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 , a movie clip cannot receive input focus unless it is a undefined false button. If the property value is , a movie clip can receive input focus even if it focusEnabled...
  • Page 575 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 , and , and add the following ActionScript: mc1_mc mc2_mc mc3_mc...
  • Page 576 Parameters The target path of the Timeline whose coordinate system you want targetCoordinateSpace to use as a reference point. Returns An object with the properties , and xMin xMax yMin yMax. Description Method; returns properties that are the minimum and maximum x and y coordinate values of the instance specified by for the parameter.
  • Page 577 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 . You can compare this value with the value returned by my_mc to determine what percentage of a movie clip has loaded.
  • Page 578 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) {...
  • Page 579 You can extend the methods and event handlers of the MovieClip class by creating a subclass. Example The following example writes the depth occupied by the movie clip instance to the log logo_mc file: this.createEmptyMovieClip("logo_mc", 1); logo_mc.loadMovie("http://www.macromedia.com/devnet/mx/blueprint/articles/ nielsen/spotlight_jnielsen.jpg"); trace(this.getInstanceAtDepth(1)); // output: _level0.logo_mc See also MovieClip.getDepth(), MovieClip.getNextHighestDepth(), MovieClip.swapDepths() MovieClip.getNextHighestDepth() Availability Flash Player 7.
  • Page 580 = 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.getSWFVersion() : Number Parameters None. Returns An integer that specifies the Flash Player version that was targeted when the SWF file loaded into was published.
  • Page 581 Note: You can’t specify a tab index value for static text in Flash. However, other products may do so (for example, Macromedia FlashPaper). The contents of the TextSnapshot object aren’t dynamic; that is, if the movie clip moves to a different frame, or is altered in some way (for example, objects in the movie clip are added or removed), the TextSnapshot object might not represent the current text in the movie clip.
  • Page 582 text_mc.textSnapshot_txt.htmlText += "<b>"+i+"</b>\t"+textSnap[i]; text_mc.textSnapshot_txt.htmlText += "</textformat>"; 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. Usage my_mc.getURL(URL:String [,window:String, variables:String]) : Void Parameters...
  • Page 583 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”); method also allows you to send variables to a remove server-side script, as seen in getURL() the following code: this.createEmptyMovieClip("loader_mc", this.getNextHighestDepth());...
  • Page 584 var mouseListener:Object = new Object(); mouseListener.onMouseMove = function() { var point:Object = {x:_xmouse, y:_ymouse}; target_mc.globalToLocal(point); var rowHeaders = "<b> &nbsp; \t</b><b>_x\t</b><b>_y</b>"; var row_1 = "_root\t"+_xmouse+"\t"+_ymouse; var row_2 = "target_mc\t"+point.x+"\t"+point.y; coords_txt.htmlText = "<textformat tabstops='[100, 150]'>"; coords_txt.htmlText += rowHeaders; coords_txt.htmlText += row_1; coords_txt.htmlText += row_2;...
  • Page 585 The following code example writes the height and width of a movie clip to the log file : this.createEmptyMovieClip("image_mc", this.getNextHighestDepth()); var image_mcl:MovieClipLoader = new MovieClipLoader(); var mclListener:Object = new Object(); mclListener.onLoadInit = function(target_mc:MovieClip) { trace(target_mc._name+" = "+target_mc._width+" X "+target_mc._height+" pixels"); image_mcl.addListener(mclListener); image_mcl.loadClip("http://www.macromedia.com/devnet/mx/blueprint/articles/ nielsen/spotlight_jnielsen.jpg", image_mc); See Also MovieClip._width MovieClip.hitArea Availability Flash Player 6. Usage my_mc.hitArea:Object...
  • Page 586 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 , the movie clip itself is used as the hit area. The null undefined value of the property may be a reference to a movie clip object.
  • Page 587 Returns A Boolean value of overlaps with the specified hit area, otherwise. true my_mc false Description Method; evaluates the instance specified by to see if it overlaps or intersects with the hit my_mc area identified by the coordinate parameters. target Usage 1: Compares the coordinates to the shape or bounding box of the specified instance, according to the...
  • Page 588 An integer that indicates the alpha value of the line’s color; valid values are 0–100. If a alpha 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.
  • Page 589 Description Method; draws a line using the current line style from the current drawing position to ( ); the current drawing position is then set to ( ). If the movie clip that you are drawing in contains content that was created with the Flash drawing tools, calls to are drawn underneath lineTo() the content.
  • Page 590 // creates a child movie clip inside of "mc_1" // this is the movie clip the image will replace logo_mc.createEmptyMovieClip("container_mc",0); logo_mc.container_mc.loadMovie("http://www.macromedia.com/images/shared/ product_boxes/80x92/studio_flashpro.jpg"); // put event handler on the parent movie clip mc_1 logo_mc.onPress = function() { trace("It works");...
  • Page 591 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, must be in the same domain as the SWF file;...
  • Page 592 Parameters The name or identifier of an object created with the Object class, specifying the x and y point coordinates as properties. Returns Nothing. Description Method; converts the object from the movie clip’s (local) coordinates to the Stage point (global) coordinates. You can extend the methods and event handlers of the MovieClip class by creating a subclass.
  • Page 593 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 movie clip. You want to make game_mc sure that, if is used in Chess.swf, it still refers to in Chess.swf after being loaded into _root _root...
  • Page 594 The lockroot.swf file has _ applied to it, and nolockroot.swf does not. After the files are lockroot loaded, each file dumps variables from their scopes. Place the following ActionScript on _root the main Timeline of a FLA document: this.createEmptyMovieClip("lockroot_mc", this.getNextHighestDepth()); lockroot_mc.loadMovie("lockroot.swf");...
  • Page 595 from lockroot.swf myOtherVar -> 2 myVar -> 1 MovieClip.menu Availability Flash Player 7. Usage my_mc.menu:ContextMenu = contextMenu Parameters A ContextMenu object. contextMenu Description Property; associates the specified ContextMenu object with the movie clip . The my_mc ContextMenu class lets you modify the context menu that appears when the user right-clicks (Windows) or Control-clicks (Macintosh) in Flash Player.
  • Page 596 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. An integer indicating the vertical position relative to the registration point of the parent movie clip.
  • Page 597 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();...
  • Page 598 Parameters None. Returns Nothing. Description Event handler; invoked when a movie clip receives data from a MovieClip.loadVariables() call. You must define a function that executes when the event handler MovieClip.loadMovie() 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.
  • Page 599 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.
  • Page 600 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.
  • Page 601 MovieClip.onKeyDown Availability Flash Player 6. Usage my_mc.onKeyDown = function() { // your statements here Parameters None. Returns Nothing. Description Event handler; invoked when a movie clip has input focus and a key is pressed. The onKeyDown event handler is invoked with no parameters. You can use the Key.getAscii() methods to determine which key was pressed.
  • Page 602 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 event handler is invoked with no onKeyUp parameters. You can use the methods to determine which Key.getAscii() Key.getCode()
  • Page 603 MovieClip.onKillFocus Availability Flash Player 6. Usage my_mc.onKillFocus = function (newFocus:Object) { // your statements here Parameters The object that is receiving the keyboard focus. newFocus Returns Nothing. Description Event handler; invoked when a movie clip loses keyboard focus. The method onKillFocus receives one parameter, , which is an object that represents the new object receiving the...
  • Page 604 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.
  • Page 605 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.
  • Page 606 Example The following example defines a function for the method that writes the results of a onMouseMove method to the log file: trace() my_mc.onMouseMove = function () { trace ("onMouseMove called"); MovieClip.onMouseUp Availability Flash Player 6. Usage my_mc.onMouseUp = function() { // your statements here Parameters None.
  • Page 607 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.
  • Page 608 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.
  • Page 609 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.
  • Page 610 MovieClip.onSetFocus Availability Flash Player 6. Usage my_mc.onSetFocus = function(oldFocus){ // your statements here Parameters The object to lose focus. oldFocus Returns Nothing. Description Event handler; invoked when a movie clip receives keyboard focus. The parameter is oldFocus 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, contains the movie clip instance.
  • Page 611 MovieClip.onUnload Availability Flash Player 6. Usage my_mc.onUnload = function() { // your statements here Parameters None. Returns Nothing. Description Event handler; invoked in the first frame after the movie clip is removed from the Timeline. Flash processes the actions associated with the event handler before attaching any actions to onUnload the affected frame.
  • Page 612 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 , and add it to the main Timeline. my_mc Add the following ActionScript to your FLA or AS file: my_mc.onRelease = function() { trace("You clicked the movie clip: "+this);...
  • Page 613 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.
  • Page 614 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(), 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.
  • Page 615 = 450 my_mc._rotation = 90 Example The following example creates a movie clip instance dynamically, rotates, and loads an image into the instance. this.createEmptyMovieClip("image_mc", 1); image_mc._rotation = 15; image_mc.loadMovie("http://www.macromedia.com/devnet/mx/blueprint/articles/ nielsen/spotlight_jnielsen.jpg"); See also TextField._rotation MovieClip.setMask() Availability Flash Player 6. Usage my_mc.setMask(mask_mc:Object) : Void...
  • Page 616 To cancel a mask created with ActionScript, pass the value to the method. The null setMask() 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 to mask the movie clip...
  • Page 617 = 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. You can extend the methods and event handlers of the MovieClip class by creating a subclass.
  • Page 618 1); var mclListener:Object = new Object(); mclListener.onLoadInit = function(target_mc:MovieClip) { target_mc.onPress = function() { this.startDrag(); target_mc.onRelease = function() { this.stopDrag(); 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, MovieClip.startDrag(), stopDrag() MovieClip.swapDepths() Availability Flash Player 5. Usage my_mc.swapDepths(depth:Number)
  • Page 619 Description Method; swaps the stacking, or z-order (depth level), of the specified instance ( ) with the my_mc movie clip specified by the parameter, or with the movie clip that currently occupies the target depth level specified in the parameter. Both movie clips must have the same parent movie depth clip.
  • Page 620 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 in the automatic tab ordering.
  • Page 621 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 property is tabIndex by default. You can set on a button, movie clip, or text field instance. undefined tabIndex If an object in a SWF file contains a property, automatic tab ordering is disabled, and tabIndex...
  • Page 622 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 parameter.
  • Page 623 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 property on trackAsMenu any button or movie clip object. If the property does not exist, the default behavior trackAsMenu false...
  • Page 624 Example The following example unloads a movie clip instance called when a user clicks the image_mc instance. unloadMC_btn 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...
  • Page 625 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.
  • Page 626 The following code example writes the height and width of a movie clip to the log file: this.createEmptyMovieClip("image_mc", this.getNextHighestDepth()); var image_mcl:MovieClipLoader = new MovieClipLoader(); var mclListener:Object = new Object(); mclListener.onLoadInit = function(target_mc:MovieClip) { trace(target_mc._name+" = "+target_mc._width+" X "+target_mc._height+" pixels"); image_mcl.addListener(mclListener); image_mcl.loadClip("http://www.macromedia.com/devnet/mx/blueprint/articles/ nielsen/spotlight_jnielsen.jpg", image_mc); See also MovieClip._height Chapter 7: ActionScript for Flash...
  • Page 627 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).
  • Page 628 Example The following example returns the current coordinates of the mouse on the Stage ) and in relation to a movie clip on the Stage called _level0 my_mc this.createTextField("mouse_txt", this.getNextHighestDepth, 0, 0, 150, 66); mouse_txt.html = true; mouse_txt.multiline = true; var row1_str:String = "&nbsp;\t<b>_xmouse\t</b><b>_ymouse</b>";...
  • Page 629 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.
  • Page 630 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 coordinates of the mouse on the Stage ) and in relation to a movie clip on the Stage called _level0 my_mc this.createTextField("mouse_txt", this.getNextHighestDepth, 0, 0, 150, 66);...
  • Page 631 Example The following example creates a movie clip at runtime called . The Drawing API is used to box_mc 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.
  • Page 632 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 instead of to load MovieClipLoader.loadClip()
  • Page 633 Listener summary for the MovieClipLoader class Listener Description Invoked when a file loaded with MovieClipLoader.onLoadComplete MovieClipLoader.loadClip() has completely downloaded. Invoked when a file loaded with MovieClipLoader.onLoadError MovieClipLoader.loadClip() has failed to load. MovieClipLoader.onLoadInit Invoked when the actions on the first frame of the loaded clip have been executed.
  • Page 634 = target_mc._height; target_mc.lineStyle(4, 0x000000); target_mc.moveTo(0, 0); target_mc.lineTo(w, 0); target_mc.lineTo(w, h); target_mc.lineTo(0, h); target_mc.lineTo(0, 0); target_mc._rotation = 3; 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.onLoadComplete, MovieClipLoader.onLoadError, MovieClipLoader.onLoadInit, MovieClipLoader.onLoadProgress, MovieClipLoader.onLoadStart, MovieClipLoader.removeListener() MovieClipLoader.getProgress() Availability Flash Player 7.
  • Page 635 = image_mcl.getProgress(target_mc); target_mc.createTextField("filesize_txt", target_mc.getNextHighestDepth(), 0, target_mc._height, target_mc._width, 22); target_mc.filesize_txt.text = mclProgress.bytesLoaded+" of "+mclProgress.bytesTotal+" bytes loaded"; 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.onLoadProgress MovieClipLoader.loadClip() Availability Flash Player 7. Usage my_mcl.loadClip(url:String, target:Object ) : Boolean Parameters The absolute or relative URL of the SWF file or JPEG file to be loaded.
  • Page 636 The target path of a movie clip, or an integer specifying the level in Flash Player into target 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 if the URL request was sent successfully;...
  • Page 637 = "+target_mc+"\n"); my_mcl.addListener(myListener); // Now load the files into their targets. // loads into movie clips this.createEmptyMovieClip("clip1_mc", this.getNextHighestDepth()); clip1_mc._x = 400; this.createEmptyMovieClip("clip2_mc", this.getNextHighestDepth()); my_mcl.loadClip("http://www.macromedia.com/software/drk/images/box_drk5.jpg", clip1_mc); my_mcl.loadClip("http://www.macromedia.com/devnet/images/160x160/ ben_forta.jpg", clip2_mc); clip2_mc._x = 200; // loads into _level1 my_mcl.loadClip("http://www.macromedia.com/devnet/images/160x160/ mike_chambers.jpg", 1);...
  • Page 638 = "+target_mc+"\n"); another_mcl.addListener(myListener2); /* Now load the files into their targets (using the second instance of MovieClipLoader) */ another_mcl.loadClip("http://www.macromedia.com/devnet/images/160x160/ flex_logo.jpg", this.createEmptyMovieClip("clip4_mc", this.getNextHighestDepth())); clip4_mc._y = 200; // Issue the following statements after the download is complete, // and after my_mcl.onLoadInit has been called.
  • Page 639 = getTimer(); mclListener.onLoadInit = function(target_mc:MovieClip) { var timerMS:Number = target_mc.completeTimer-target_mc.startTimer; target_mc.createTextField("timer_txt", target_mc.getNextHighestDepth(), 0, target_mc._height, target_mc._width, 22); target_mc.timer_txt.text = "loaded in "+timerMS+" ms."; 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.addListener(), MovieClipLoader.onLoadStart, MovieClipLoader.onLoadError MovieClipLoader.onLoadError Availability Flash Player 7.
  • Page 640 // your statements here Parameters A listener object that was added using listenerObject MovieClipLoader.addListener() A movie clip loaded by a method. target_mc MovieClipLoader.loadClip() A string that explains the reason for the failure. errorCode Returns One of two strings: "URLNotFound" "LoadNeverCompleted" Description Listener;...
  • Page 641 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 A listener object that was added using listenerObject MovieClipLoader.addListener() A movie clip loaded by a method. This parameter target_mc MovieClipLoader.loadClip() is optional. Returns Nothing.
  • Page 642 = 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.onLoadProgress = function([target_mc:Object [, loadedBytes:Number [, totalBytes:Number ] ] ] // your statements here Parameters A listener object that was added using listenerObject MovieClipLoader.addListener()
  • Page 643 Example The following example creates a progress bar using the Drawing API. The progress bar displays the loading progress of an image using the listener. When the image finishes onLoadProgress loading, the progress bar is removed from the Stage. You must replace the URL parameter of the command so that the parameter refers to a valid JPEG file using HTTP.
  • Page 644 = function(target_mc:MovieClip) { target_mc.completeTimer = getTimer(); mclListener.onLoadInit = function(target_mc:MovieClip) { var timerMS:Number = target_mc.completeTimer-target_mc.startTimer; target_mc.createTextField("timer_txt", target_mc.getNextHighestDepth(), 0, target_mc._height, target_mc._width, 22); target_mc.timer_txt.text = "loaded in "+timerMS+" ms."; 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); Chapter 7: ActionScript for Flash...
  • Page 645 See also MovieClipLoader.onLoadError, MovieClipLoader.onLoadInit, MovieClipLoader.onLoadComplete MovieClipLoader.removeListener() Availability Flash Player 7. Usage my_mcl.removeListener(listenerObject:Object) : Void Parameters A listener object that was added using listenerObject MovieClipLoader.addListener() Returns Nothing. Description Method; removes the listener that was used to receive notification when a MovieClipLoader event handler was invoked.
  • Page 646 = 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 The string or integer passed to the corresponding call to target my_mcl.loadClip() Returns Nothing.
  • Page 647 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.
  • Page 648 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.
  • Page 649 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.
  • Page 650 Event handler summary for the NetStream class Event handler Description Invoked every time a status change or error is posted for the NetStream.onStatus 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.
  • Page 651 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 to estimate how close the buffer is to NetStream.bufferTime being full—for example, to display feedback to a user who is waiting for data to be loaded into the buffer.
  • Page 652 Description Read-only property; the number of seconds assigned to the buffer by . The default value is .1(one-tenth of a second). To determine NetStream.setBufferTime() 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.
  • Page 653 Example The following example creates a progress bar using the Drawing API and the bytesLoaded properties that displays the loading progress of video1.flv into the video object bytesTotal instance called . A text field called is dynamically created to display my_video loaded_txt information about the loading progress as well.
  • Page 654 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 properties that displays the loading progress of video1.flv into the video object bytesTotal instance called .
  • Page 655 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.
  • Page 656 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. If you are exporting FLV files to be played back on a number of systems, you can check this value during testing to help you determine how much compression to apply when exporting the file.
  • Page 657 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 property containing a string that describes the result of the code handler, and a...
  • Page 658 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 A Boolean value specifying whether to pause play ( ) or resume play (...
  • Page 659 Parameters The name of an FLV file to play, in quotation marks. Both http:// and file:// formats fileName are supported; the file:// location is always relative to the location of the SWF file. Returns Nothing. Description Method; begins playback of an external video (FLV) file. To view video data, you must call a method;...
  • Page 660 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 The approximate time value, in seconds, to move to in an FLV file. The numberOfSeconds playhead moves to the keyframe of the video that’s closest to numberOfSeconds...
  • Page 661 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 The number of seconds of data to be buffered before Flash begins displaying numberOfSeconds data.
  • Page 662 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.floor(ns_seconds%60); if (seconds<10) { seconds = "0"+seconds;...
  • Page 663 CHAPTER 7 ActionScript for Flash onClipEvent() Availability Flash Player 5. Usage onClipEvent(movieEvent){ // your statements here Parameters is a trigger called an event. When the event occurs, the statements following it movieEvent within curly braces ({}) are executed. Any of the following values can be specified for the parameter: movieEvent •...
  • Page 664 Example The following example uses with the movie event and is designed to be onClipEvent() keyDown attached to a movie clip or button. The movie event is usually used with one or more keyDown methods and properties of the Key object. The following script uses to find out Key.getCode() which key the user has pressed;...
  • Page 665 CHAPTER 7 ActionScript for Flash onUpdate Availability Flash Player 6. Usage function onUpdate() { ...statements...; Parameters None. Returns Nothing. Description Event handler; is defined for a Live Preview used with a component. When an instance onUpdate of a component on the Stage has a Live Preview, the authoring tool invokes the Live Preview’s function whenever the component parameters of the component instance change.
  • Page 666 CHAPTER 7 ActionScript for Flash _parent 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 .
  • Page 667 . Images are loaded into both movie clips. When a newClip_mc button, , is clicked, the duplicated movie clip is removed from the Stage. button_mc this.createEmptyMovieClip("myClip_mc", this.getNextHighestDepth()); myClip_mc.loadMovie("http://www.macromedia.com/devnet/mx/blueprint/articles/ server_side/jeremy_gray.jpg"); duplicateMovieClip(this.myClip_mc, "newClip_mc", this.getNextHighestDepth()); newClip_mc.loadMovie("http://www.macromedia.com/devnet/mx/blueprint/articles/ performance/spotlight_speterson.jpg"); newClip_mc._x = 200; this.button_mc.onRelease = function() { removeMovieClip(this._parent.newClip_mc);...
  • Page 668 CHAPTER 7 ActionScript for Flash _root Availability Flash Player 5. Usage _root.movieClip _root.action _root.property Parameters The instance name of a movie clip. movieClip An action or method. action A property of the MovieClip object. property 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.
  • Page 669 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).
  • Page 670 Parameters An object with an method. newListener onSetFocus Returns None. Description Method; registers an object to receive keyboard focus change notifications. When the focus changes (for example, whenever is invoked), all listening objects Selection.setFocus() registered with have their method invoked. Multiple objects may addListener() onSetFocus listen for focus change notifications.
  • Page 671 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.
  • Page 672 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.
  • Page 673 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 &&...
  • Page 674 • 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.
  • Page 675 // 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);...
  • Page 676 Returns was successfully removed, the method returns a value. If was not listener true listener successfully removed—for example, if was not on the Selection object’s listener list— listener 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.
  • Page 677 Returns A Boolean value; if the focus attempt is successful, if it fails. true false Description Method; gives focus to the selectable (editable) text field, button, or movie clip specified by . The parameter must be a string literal of the path to the instanceName instancePathName instance.
  • Page 678 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 The ending index of the selection span. Returns Nothing. Description Method; sets the selection span of the currently focused text field. The new selection span will begin at the index specified in the parameter, and end at the index specified in the start...
  • Page 679 . When you click the button called setProperty() , the coordinate of a movie clip named is incremented by 20 pixels. right_btn params_mc this.createEmptyMovieClip("params_mc", 999); params_mc.loadMovie("http://www.macromedia.com/devnet/mx/blueprint/articles/ nielsen/spotlight_jnielsen.jpg"); setProperty(this.params_mc, _y, 20); setProperty(this.params_mc, _x, 20); this.right_btn.onRelease = function() { setProperty(params_mc, _x, getProperty(params_mc, _x)+20); See also getProperty()
  • Page 680 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.
  • Page 681 Event handler summary for the Sound class Event handler Description Invoked each time new ID3 data is available. Sound.onID3 Sound.onLoad Invoked when a sound loads. Invoked when a sound stops playing. Sound.onSoundComplete Constructor for the Sound class Availability Flash Player 5. Usage new Sound([target:Object]) : Sound Parameters...
  • Page 682 Parameters The identifier of an exported sound in the library. The identifier is located in the idName Linkage Properties dialog box. Returns Nothing. Description Method; attaches the sound specified in the parameter to the specified Sound object. The idName sound must be in the library of the current SWF file and specified for export in the Linkage Properties dialog box.
  • Page 683 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;...
  • Page 684 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;...
  • Page 685 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.position+" of "+the_sound.duration+" milliseconds ("+pos+"%)"+newline; See also Sound.getBytesTotal() Sound.getBytesTotal() Availability Flash Player 6.
  • Page 686 Parameters None. Returns An integer. Description Method; returns the pan level set in the last call as an integer from -100 (left) to 100 setPan() (right). (0 sets the left and right channels equally.) The pan setting controls the left-right balance of the current and future sounds in a SWF file.
  • Page 687 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.getPan(); See also Sound.setPan() Sound.getTransform() Availability...
  • Page 688 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", "ll_mc", transform_mc.getNextHighestDepth(), {_x:0, _y:30}); var knob_lr:MovieClip = transform_mc.attachMovie("knob_id", "lr_mc", transform_mc.getNextHighestDepth(), {_x:30, _y:30}); var knob_rl:MovieClip = transform_mc.attachMovie("knob_id", "rl_mc", transform_mc.getNextHighestDepth(), {_x:60, _y:30}); var knob_rr:MovieClip = transform_mc.attachMovie("knob_id", "rr_mc", transform_mc.getNextHighestDepth(), {_x:90, _y:30}); knob_ll.top = knob_ll._y;...
  • Page 689 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 = "<textformat tabStops='[0,30,60,90]'>"; transform_mc.transform_txt.htmlText += ll_num+"\t"+lr_num+"\t"+rl_num+"\t"+rr_num; transform_mc.transform_txt.htmlText += "</textformat>"; See Also Sound.setTransform() Sound.getVolume() Availability...
  • Page 690 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;...
  • Page 691 Flash Player 6 (6.0.40.0) and later use the property to support ID3 1.0 and ID3 1.1 Sound.id3 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 , and so on.
  • Page 692 Property Description TPOS Part of a set Publisher TPUB Track number/position in set TRCK TRDA Recording dates TRSN Internet radio station name Internet radio station owner TRSO Size TSIZ TSRC ISRC (international standard recording code) Software/hardware and settings used for encoding TSSE Year TYER...
  • Page 693 Sound.loadSound() Availability Flash Player 6. Usage my_sound.loadSound(url:String, isStreaming:Boolean) : Void Parameters The location on a server of an MP3 sound file. A Boolean value that indicates whether the sound is a streaming sound ( ) or isStreaming true an event sound ( false Returns Nothing.
  • Page 694 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 . This handler provides access to ID3 data Sound.attachSound() Sound.loadSound() without polling.
  • Page 695 Sound.onLoad Availability Flash Player 6. Usage my_sound.onLoad = function(success:Boolean){ // your statements here Parameters A Boolean value of has been loaded successfully, false otherwise. success true my_sound Returns Nothing. Description Event handler; invoked automatically when a sound loads. You must create a function that executes when the this handler is invoked.
  • Page 696 Sound.onSoundComplete Availability Flash Player 6. Usage my_sound.onSoundComplete = function(){ // your statements here Parameters None. Returns Nothing. Description Event handler; invoked automatically when a sound finishes playing. You can use this handler to trigger events in a SWF file when a sound finishes playing. You must create a function that executes when this handler is invoked.
  • Page 697 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 for a sample usage of this property. Sound.duration See Also Sound.duration...
  • Page 698 Sound.setTransform() Availability Flash Player 5. Usage my_sound.setTransform(soundTransformObject:Object) : Void Parameters An object created with the constructor for the generic Object class. soundTransformObject Returns Nothing. Description Method; sets the sound transform (or balance) information, for a Sound object. parameter is an object that you create using the constructor soundTransformObject method of the generic Object class with parameters specifying how the sound is distributed to the left and right channels (speakers).
  • Page 699 Mono sounds play all sound input in the left speaker and have the following transform settings by default: ll = 100 lr = 100 rr = 0 rl = 0 Example The following example illustrates a setting that can be achieved by using , but setTransform() cannot be achieved by using...
  • Page 700 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 volume. The default setting is 100. Returns Nothing. Description Method; sets the volume for the Sound object. Example for a sample usage of this method.
  • Page 701 Example The following example creates a new Sound object, and loads a sound. Loading the sound is handled by the handler, which allows you to start the song after it’s successfully loaded. onLoad Then the sound starts playing using the method.
  • Page 702 Example The following example uses two buttons, , to control the playback of a stop_btn play_btn 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();...
  • Page 703 CHAPTER 7 ActionScript for Flash _soundbuftime Availability Flash Player 4. Usage _soundbuftime:Number = integer Parameters The number of seconds before the SWF file starts to stream. integer Description Property (global); establishes the number of seconds of streaming sound to buffer. The default value is 5 seconds.
  • Page 704 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.
  • Page 705 Returns Nothing. Description Method; detects when a SWF file is resized (but only if ). The Stage.scaleMode = "noScale" method doesn’t work with the default movie clip scaling setting ( ) or addListener() showAll other scaling settings ( exactFit noBorder To use , you must first create a listener object.
  • Page 706 Value Vertical Horizontal "TL" left right "TR" bottom left "BL" "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 . Add the following stageAlign_cb ActionScript to your FLA or AS file: var stageAlign_cb:mx.controls.ComboBox;...
  • Page 707 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 is set to and the SWF file is resized. You can Stage.scaleMode noScale use this event handler to write a function that lays out the objects on the Stage when a SWF file is...
  • Page 708 Parameters An object added to an object’s callback list with myListener 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.
  • Page 709 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);...
  • Page 710 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.scaleMode Chapter 7: ActionScript for Flash...
  • Page 711 An image is startDrag() stopDrag() loaded into using the MovieClipLoader class. pic_mc var pic_mcl:MovieClipLoader = new MovieClipLoader(); pic_mcl.loadClip("http://www.macromedia.com/devnet/mx/blueprint/articles/ qa_petmarket/spotlight_thale.jpg", this.createEmptyMovieClip("pic_mc", this.getNextHighestDepth())); var listenerObject:Object = new Object(); listenerObject.onLoadInit = function(target_mc) { target_mc.onPress = function() { startDrag(this);...
  • Page 712 CHAPTER 7 ActionScript for Flash stop() 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.gotoAndStop() Chapter 7: ActionScript for Flash...
  • Page 713 CHAPTER 7 ActionScript for Flash stopAllSounds() 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.
  • Page 714 CHAPTER 7 ActionScript for Flash stopDrag() 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 when the user releases the mouse button: my_mc my_mc.onPress = function () {...
  • Page 715 CHAPTER 7 ActionScript for Flash targetPath() Availability Flash Player 5. Usage targetpath(movieClipObject:MovieClip) : String Parameters Reference (for example, ) to the movie clip for which the movieClipObject _root _parent target path is being retrieved. Returns A string containing the target path of the specified movie clip. Description Function;...
  • Page 716 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.
  • Page 717 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.
  • Page 718 Property Description TextField.textHeight The height of the text field’s bounding box. The width of the text field’s bounding box. TextField.textWidth Indicates whether a text field is an input text field or dynamic TextField.type text field. Read-only; the URL of the SWF file that created the text field TextField._url instance.
  • Page 719 TextField.addListener() Availability Flash Player 6. Usage my_txt.addListener(listener:Object) : Void Parameters An object with an event handler. listener onChanged onScroller Returns Nothing. Description Method; registers an object to receive notification when the event onChanged onScroller handlers have been invoked. When a text field changes or is scrolled, the TextField.onChanged event handlers are invoked, followed by the TextField.onScroller...
  • Page 720 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 . Valid my_txt 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.
  • Page 721 The values of determine whether a text field expands or autoSize TextField.wordWrap contracts to the left side, right side, or bottom side. The default value for each of these properties false is set to (the default) or , then no resizing will occur. autoSize "none"...
  • Page 722 // 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;...
  • Page 723 Description Property; the color of the text field background. Default is (white). This property may 0xFFFFFF 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...
  • Page 724 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 . Think of the text field as a “window” onto a block of text. The my_txt property is the one-based index of the topmost visible line in the window.
  • Page 725 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 , you must use standard HTML commands such as true <BR>...
  • Page 726 Example In this example, you need to create a dynamic text field called , and then use the following my_txt ActionScript to embed fonts and rotate the text field. The reference to refers to a Font my font symbol in the library, with linkage set to my font var my_fmt:TextFormat = new TextFormat();...
  • Page 727 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 ) when you call this method. This method returns names of fonts on the player’s host my_txt system as an array.
  • Page 728 Description Method; returns a TextFormat object containing a copy of the text field’s text format object. The text format object is the format that newly inserted text, such as text inserted with the method or text entered by a user, receives. When replaceSel() getNewTextFormat() invoked, the TextFormat object returned has all of its properties defined.
  • Page 729 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]);...
  • Page 730 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.
  • Page 731 Example The following example creates a text field that sets the property to . HTML-formatted html true text displays in the text field. this.createTextField("my_txt", this.getNextHighestDepth(), 10, 10, 160, 22); my_txt.html = true; my_txt.htmlText = "<b> this is bold text </b>"; See also TextField.htmlText TextField.htmlText...
  • Page 732 Example The following example outputs the number of characters in the text field, which date_txt 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...
  • Page 733 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 . Create two my_txt buttons, to scroll the text field. Add the following scrollUp_btn scrollDown_btn, ActionScript to your FLA or AS file.
  • Page 734 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.
  • Page 735 Example The following example creates two text fields. The scrollable_txt field has the property set to true, so scrolls when you click the field mouseWheelEnabled scrollable_txt and roll the mouse wheel. The field does not scroll if you click the field and nonscrollable_txt roll the mouse wheel.
  • Page 736 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.
  • Page 737 A reference to the text field instance is passed as a parameter to the handler. You can onChanged capture this data by putting a parameter in the event handler method. For example, the following code uses as the parameter that is passed to the event handler.
  • Page 738 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 = function(textFieldInstance:TextField){ // your statements here...
  • Page 739 is called whether the scroll position changed because of a users interaction with the onScroller text field, or programmatic changes. The handler fires only if a user interaction causes onChanged 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.
  • Page 740 Returns Nothing. Description Event handler; invoked when a text field receives keyboard focus. The parameter is the oldFocus object that loses the focus. For example, if the user presses the Tab key to move the input focus from a button to a text field, contains the text field instance.
  • Page 741 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 , the text field is a password text field and hides the password true input characters using asterisks instead of the actual characters.
  • Page 742 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 property. _quality 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()
  • Page 743 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 .
  • Page 744 Returns Nothing. Description Method; replaces the current selection with the contents of the parameter. The text is text 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.
  • Page 745 Description Method; replaces a range of characters, specified by the parameters, in beginIndex endIndex the specified text field with the contents of the parameter. text Example The following example creates a text field called and assigns the text dog@house.net to my_txt the field.
  • Page 746 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.
  • Page 747 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 property is useful for scroll directing users to a specific paragraph in a long passage, or creating scrolling text fields. This property can be retrieved and modified.
  • Page 748 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 property controls whether a text field is selectable selectable, and not whether a text field is editable. A dynamic text field can be selectable even if it's not editable.
  • Page 749 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 method or text entered by a replaceSel() user. When text is inserted, the newly inserted text is assigned the default new text format. The new default text format is specified by , which is a TextFormat object.
  • Page 750 Description Method; applies the text formatting specified by textFormat to some or all of the text in a text field. must be a TextFormat object that specifies the text formatting changes desired. textFormat Only the non-null properties of textFormat are applied to the text field. Any property of that is set to null will not be applied.
  • Page 751 See also TextFormat class TextField.setNewTextFormat() TextField.styleSheet Availability Flash Player 7. Usage my_txt.styleSheet = TextField StyleSheet Description Property; attaches a style sheet to the text field specified by . For information on creating my_txt style sheets, see the TextField.StyleSheet class entry. The style sheet associated with a text field may be changed at any time.
  • Page 752 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. Save the following two CSS files in the same directory as the FLA or AS file you created previously: /* in styles.css */ .important {...
  • Page 753 TextField.tabEnabled Availability Flash Player 6. Usage my_txt.tabEnabled:Boolean Description Property; specifies whether is included in automatic tab ordering. It is my_txt undefined by default. If the property is , the object is included in automatic tab tabEnabled undefined true ordering. If the property is also set to a value, the object is included in custom tab tabIndex ordering as well.
  • Page 754 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 by default. undefined If any currently displayed object in the SWF file contains a property, automatic tab tabIndex ordering is disabled, and the tab ordering is calculated from the...
  • Page 755 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. _self target specifies the current frame in the current window, specifies a new window, _blank _parent specifies the parent of the current frame, and specifies the top-level frame in the current _top window.
  • Page 756 htmlText: <P ALIGN="LEFT"><FONT FACE="Times New Roman" SIZE="12" COLOR="#000000"><B>Remember to always update your help panel.</B></FONT></P> 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.
  • Page 757 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;...
  • Page 758 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;...
  • Page 759 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 and associates the variable my_txt today_date with the text field. When you change the variable , then the text that displays in today_date updates.
  • Page 760 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);...
  • Page 761 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 , the text field has word wrap; if the value is , the text field does not have word wrap. true false Example...
  • Page 762 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. Example The following example creates three text fields on the Stage.
  • Page 763 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 instance when you click the my_txt scaleUp_btn...
  • Page 764 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...
  • Page 765 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.
  • Page 766 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();...
  • Page 767 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 , all styles from the clear_btn my_styleSheet object are removed. // Create a new style sheet object var my_styleSheet:TextField.StyleSheet = new TextField.StyleSheet();...
  • Page 768 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"...
  • Page 769 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:...
  • Page 770 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.
  • Page 771 news_txt.styleSheet = my_styleSheet; news_txt.htmlText = "<p class=\"heading\">Heading goes here!</p><p class=\"mainBody\">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p>"; my_styleSheet.load("styles.css"); For the code contained in styles.css, see the entry for TextField.StyleSheet.getStyle() See also TextField.StyleSheet.onLoad...
  • Page 772 news_txt.htmlText = "<p class=\"heading\">Heading goes here!</p><p class=\"mainBody\">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p>"; my_styleSheet.load("styles.css"); For the code contained in styles.css, see the entry for . For TextField.StyleSheet.getStyle() an example of asynchronously loading style sheets using ActionScript 2.0, see the entry for TextField.StyleSheet.getStyle()
  • Page 773 function dumpStyles(styles:TextField.StyleSheet):Void { var styleNames_array:Array = styles.getStyleNames(); for (var i = 0; i<styleNames_array.length; i++) { var styleName_str:String = styleNames_array[i]; var styleObject:Object = styles.getStyle(styleName_str); trace(styleName_str); for (var prop in styleObject) { trace("\t"+prop+": "+styleObject[prop]); trace(""); TextField.StyleSheet.setStyle() Availability Flash Player 7. Usage styleSheet.setStyle(name:String, style:Object) : Void Parameters A string that specifies the name of the style to add to the style sheet.
  • Page 774 my_styleSheet.setStyle("emphasized", styleObj); delete styleObj; var styleNames_array:Array = my_styleSheet.getStyleNames(); for (var i=0;i<styleNames_array.length;i++) { var styleName:String = styleNames_array[i]; var thisStyle:Object = my_styleSheet.getStyle(styleName); trace(styleName); for (var prop in thisStyle) { trace("\t"+prop+": "+thisStyle[prop]); trace(""); This writes the following information to the log file: emphasized fontWeight: bold color: #000000 Note: The line of code...
  • Page 775 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);...
  • Page 776 CHAPTER 7 ActionScript for Flash TextFormat class Availability Flash Player 6. Description The TextFormat class represents character formatting information. You must use the constructor to create a TextFormat object before calling new TextFormat() its methods. You can set TextFormat parameters to to indicate that they are undefined.
  • Page 777 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.
  • Page 778 Indicates the left margin of the paragraph, in points. leftMargin Indicates the right margin of the paragraph, in points. rightMargin An integer that indicates the indentation from the left margin to the first character in indent the paragraph. A number that indicates the amount of leading vertical space between lines. leading Returns A reference to a TextFormat object.
  • Page 779 Example The following example creates a text field with a border and uses to center TextFormat.align 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";...
  • Page 780 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 , then the text is boldface. true Example The following example creates a text field that includes characters in boldface. var my_fmt:TextFormat = new TextFormat();...
  • Page 781 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();...
  • Page 782 TextFormat.getTextExtent() Availability Flash Player 6. The optional parameter is supported in Flash Player 7. width Usage my_fmt.getTextExtent(text:String, [width:Number]) : Object Parameters A string. text An optional number that represents the width, in pixels, at which the specified text width should wrap. Returns An object with the properties width...
  • Page 783 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.
  • Page 784 = "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.
  • Page 785 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 , which indicates that the property is undefined. null Example The following example creates a text field and sets the text style to italic. this.createTextField("mytext",1,100,100,100,100);...
  • Page 786 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 , which indicates null 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);...
  • Page 787 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 , which indicates that null 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);...
  • Page 788 , you can get or set this property, but the property will have no effect. null Example The following example creates a text field with a hyperlink to the Macromedia website. The example uses to display the Macromedia website in a new browser window.
  • Page 789 The default value is , which indicates that null the property is undefined. Example This example creates a text field that is a hyperlink to the Macromedia website. var myformat:TextFormat = new TextFormat(); myformat.url = "http://www.macromedia.com"; this.createTextField("mytext",1,100,100,200,100); mytext.multiline = true;...
  • Page 790 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.
  • Page 791 A string specifying the text to search for. If you specify a string literal instead of a textToFind variable of type String, enclose the string in quotation marks. A Boolean value specifying whether the text in must match the case caseSensitive my_snap of the string in...
  • Page 792 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"...
  • Page 793 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;...
  • Page 794 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 to be included in from my_snap...
  • Page 795 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 A number that represents the...
  • Page 796 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.
  • Page 797 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.
  • Page 798 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...
  • Page 799 It is loaded using the MovieClipLoader class. When you click the image, the movie clip unloads from the SWF file: var pic_mcl:MovieClipLoader = new MovieClipLoader(); pic_mcl.loadClip("http://www.macromedia.com/devnet/mx/blueprint/articles/ performance/spotlight_speterson.jpg", this.createEmptyMovieClip("pic_mc", this.getNextHighestDepth())); var listenerObject:Object = new Object(); listenerObject.onLoadInit = function(target_mc) { target_mc.onRelease = function() {...
  • Page 800 CHAPTER 7 ActionScript for Flash unloadMovieNum() Availability Flash Player 3. Usage unloadMovieNum(level:Number) : Void Parameters The level ( ) of a loaded movie. level _levelN Returns Nothing. Description Function; removes a SWF or image that was loaded by means of from Flash loadMovieNum() Player.
  • Page 801 CHAPTER 7 ActionScript for Flash updateAfterEvent() 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 handler or as part of a function or method that you pass to onClipEvent() .
  • Page 802 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.
  • Page 803 Returns Nothing. Description Method; specifies a video stream ( ) to be displayed within the boundaries of the Video source object on the Stage. The video stream is either an FLV file being displayed by means of the command, a Camera object, or .
  • Page 804 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 ) when the user clicks the instance.
  • Page 805 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.data; deblocking_cb.addEventListener("change", cbListener);...
  • Page 806 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.
  • Page 807 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 property of the Camera object that is Camera.width capturing the video stream.
  • Page 808 Chapter 7: ActionScript for Flash...
  • Page 809: Appendix A: Deprecated Flash 4 Operators

    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. Operator Description Associativity Logical NOT Right to left Logical AND Left to right Logical OR (Flash 4)
  • Page 810 Appendix A: Deprecated Flash 4 operators...
  • Page 811: Appendix B: Keyboard Keys And Key Code Values

    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” •...
  • Page 812 Letter or number key Key code Appendix B: Keyboard Keys and Key Code Values...
  • Page 813: Keys On The Numeric Keypad

    Keys on the numeric keypad The following table lists the keys on a numeric keypad, with the corresponding ASCII key code values that are used to identify the keys in ActionScript: Numeric keypad key Key code Numbpad 0 Numbpad 1 Numbpad 2 Numbpad 3 Numbpad 4...
  • Page 814: Other Keys

    Function key Key code This key is reserved by the system and cannot be used in ActionScript. Other keys The following table lists keys on a standard keyboard other than letters, numbers, numeric keypad keys, or function keys, with the corresponding ASCII key code values that are used to identify the keys in ActionScript: Key code Backspace...
  • Page 815 Key code Num Lock " ' Other keys...
  • Page 816 Appendix B: Keyboard Keys and Key Code Values...
  • Page 817: Index

    INDEX accessing object properties 38 calling methods 21 actions casting data types 25 repeating 40 character sequences. See strings ActionScript child classpath 64 node 70 interfaces 59 class files, creating 48 ActionScript 2.0 class members overview 45 and Singleton design pattern 61 adding notes to scripts 16 and subclasses 62 animation, symbols and 21...
  • Page 818 classes, built-in extending 55 ECMA-262 classpaths specification 10 defined 64 encapsulation 47 combining operations 37 equality operators 37 comments 16 different from assignment operators 37 communicating with the Flash Player 72 strict 37 comparison operators 34 errors compile time, defined 6 name conflict 28 concatenating strings 19 escape sequences 19...
  • Page 819 getter/setter methods of classes 63 languages, using multiple in scripts 10 getting information from remote files 67 loaded data, checking for 68 global variables 29 LoadVars object 70 and strict data typing 25 local variables 28 grouping statements 15, 16 and strict data typing 29 in functions 43 sample 28...
  • Page 820 object properties reference data types 18 accessing 38 referencing variables 28 object-oriented programming 45 remote objects files, communicating with 67 and object-oriented programming 46 sites, continuous connection 71 data type 21 repeating actions 40 defined 12 reserved words looping through children of 40 See keywords operators 12 resources, additional 6...
  • Page 821 syntax case sensitivity 14 XML 70 curly braces 15, 16 DOM 70 dot 14 hierarchy 70 parentheses 16 sample variable conversion 71 rules 13 sending information via TCP/IP socket 68 semicolon 15 sending information with XML methods 68 XML class, methods of 71 XMLSocket object target paths checking for data 68...
  • Page 822 Index...
  • Page 823: Index Of Language Elements

    INDEX OF LANGUAGE ELEMENTS Symbols >> (bitwise right shift) 125 >>= (bitwise right shift and assignment) 126 – (minus) 93 >>> (bitwise unsigned right shift) 127 –– (decrement) 81 >>>= (bitwise unsigned right shift and assignment) 128 ! (logical NOT) 83 ?: (conditional) 99 != (inequality) 84 ^ (bitwise XOR) 105...
  • Page 824 Array.sort() 248 ContextMenuItem class 524 Array.sortOn() 251 ContextMenuItem.caption 526 Array.splice() 254 ContextMenuItem.copy() 526 Array.toString() 255 ContextMenuItem.enabled 527 Array.unshift() 256 ContextMenuItem.onSelect 528 asfunction 491 ContextMenuItem.separatorBefore 529 ContextMenuItem.visible 529 continue 140 Boolean class 258 Boolean() 129 Boolean.toString() 258 Date class 260 Boolean.valueOf() 259 Date.getDate() 263 break 132 Date.getDay() 263...
  • Page 825 do while 145 Key.DELETEKEY 299 duplicateMovieClip() 531 Key.DOWN 300 dynamic 147 Key.END 300 Key.ENTER 301 Key.ESCAPE 302 Key.getAscii() 302 else 149 Key.getCode() 303 else if 150 Key.INSERT 305 Error class 287 Key.isDown() 305 Error.message 288 Key.isToggled() 306 Error.name 289 Key.LEFT 307 Error.toString() 289 Key.onKeyDown 308 escape 151...
  • Page 826 Math.atan() 347 Mouse.show() 369 Math.atan2() 348 MovieClip class 554 Math.ceil() 348 MovieClip._alpha 558 Math.cos() 349 MovieClip._currentframe 568 Math.E 350 MovieClip._droptarget 571 Math.exp() 350 MovieClip._focusrect 574 Math.floor() 351 MovieClip._framesloaded 575 Math.LN10 352 MovieClip._height 585 Math.LN2 352 MovieClip._highquality 585 Math.log() 351 MovieClip._lockroot 592 Math.LOG10E 353 MovieClip._name 596 Math.LOG2E 353...
  • Page 827 MovieClip.lineStyle() 587 MovieClip.lineTo() 588 NaN 184 MovieClip.loadMovie() 589 NetConnection class 647 MovieClip.loadVariables() 591 NetConnection.connect() 648 MovieClip.localToGlobal() 591 NetStream class 649 MovieClip.menu 595 NetStream.bufferLength 650 MovieClip.moveTo() 596 NetStream.bufferTime 651 MovieClip.nextFrame() 597 NetStream.bytesLoaded 652 MovieClip.onData 597 NetStream.bytesTotal 654 MovieClip.onDragOut 599 NetStream.close() 655 MovieClip.onDragOver 599 NetStream.currentFps 656 MovieClip.onEnterFrame 600...
  • Page 828 PrintJob.send() 395 Sound.stop() 701 PrintJob.start() 395 Stage class 704 private 195 Stage.addListener() 704 public 197 Stage.align 705 Stage.height 706 Stage.onResize 707 Stage.removeListener() 707 removeMovieClip() 667 Stage.scaleMode 708 return 198 Stage.showMenu 708 Stage.width 709 startDrag() 711 Selection class 669 static 206 Selection.addListener() 669 stop() 712 Selection.getBeginIndex() 670...
  • Page 829 System.capabilities.os 436 TextField.hscroll 729 System.capabilities.pixelAspectRatio 436 TextField.html 730 System.capabilities.playerType 437 TextField.htmlText 731 System.capabilities.screenColor 437 TextField.length 731 System.capabilities.screenDPI 437 TextField.maxChars 732 System.capabilities.screenResolutionX 438 TextField.maxhscroll 732 System.capabilities.screenResolutionY 438 TextField.maxscroll 733 System.capabilities.serverString 439 TextField.menu 733 System.capabilities.version 439 TextField.mouseWheelEnabled 734 System.exactSettings 421 TextField.multiline 735 System.onStatus 422 TextField.onChanged 736 System.security object 440...
  • Page 830 TextFormat.italic 785 TextFormat.leading 785 XML class 445 TextFormat.leftMargin 786 XML.addRequestHeader() 447 TextFormat.rightMargin 786 XML.appendChild() 448 TextFormat.size 787 XML.attributes 450 TextFormat.tabStops 787 XML.childNodes 450 TextFormat.target 788 XML.cloneNode() 451 TextFormat.underline 788 XML.contentType 453 TextFormat.url 789 XML.createElement() 454 TextSnapshot object 790 XML.createTextNode() 454 TextSnapshot.findText() 790 XML.docTypeDecl 456 TextSnapshot.getCount() 791...

This manual is also suitable for:

Flex

Table of Contents