background image

on()

191

Example

In the following script, the 

startDrag()

 function executes when the mouse is pressed, and the 

conditional script is executed when the mouse is released and the object is dropped:

on (press) {

startDrag(this);

}
on (release) {

trace("X:"+this._x);
trace("Y:"+this._y);
stopDrag();

}

See also

onClipEvent()

Summary of Contents for FLEX-FLEX ACTIONSCRIPT LANGUAGE

Page 1: ...Flex ActionScript Language Reference...

Page 2: ...including internationally Other product names logos designs titles words or phrases mentioned within this publication may be trademarks service marks or trade names of Macromedia Inc or other entities...

Page 3: ...data types 18 Assigning data types to elements 23 About variables 27 Using operators to manipulate values in expressions 31 Using condition statements 39 Using built in functions 41 Creating function...

Page 4: ...ntry for most ActionScript elements 77 Sample entry for classes 78 CHAPTER 5 ActionScript Core Language Elements 80 CHAPTER 6 ActionScript Core Classes 232 CHAPTER 7 ActionScript for Flash 490 APPENDI...

Page 5: ...etails on the syntax and usage of every language element The following list summarizes the contents of this manual Chapter 1 ActionScript Basics on page 9 describes the terminology and basic concepts...

Page 6: ...The user refers to the person who is running your scripts and applications Compile time is the time at which you publish export test or debug your document Runtime is the time at which your script is...

Page 7: ...g 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 wit...

Page 8: ......

Page 9: ...for the rules for a specific term see its entry in Part II Reference Applying the basics of ActionScript in a way that creates elegant programs can be a challenge for users who are new to ActionScrip...

Page 10: ...Java language but are useful for understanding concepts that you can apply to ActionScript Some of the differences between ActionScript and JavaScript are described in the following list ActionScript...

Page 11: ...nstructor functions for the built in Array class and the custom Circle class var my_array Array new Array var my_circle Circle new Circle 9 Data types describe the kind of information a variable or Ac...

Page 12: ...st of keywords see Keywords and reserved words on page 17 Methods are functions associated with a class For example sortOn is a built in method associated with the Array class You can also create func...

Page 13: ...ucture for ActionScript statements Target paths are hierarchical addresses of movie clip instance names variables and objects in a SWF file You can use a target path to direct an action at a movie cli...

Page 14: ...sion of Flash Player you should review both external script files and scripts in FLA files to confirm that you used consistent capitalization Case sensitivity is implemented on a per movie basis If a...

Page 15: ...te getMonth Class Circle as class Circle radius Function circleArea function radius Number return radius radius Math PI The following examples show code with opening brace on the next line Event handl...

Page 16: ...ent the parentheses cause new Color this to evaluate and create a Color object new Color this setRGB 0xffffff If you don t use parentheses you must add a statement to evaluate the expression as shown...

Page 17: ...x Number 15 var y Number 20 The following code doesn t run create new Date object var myDate Date new Date var currentMonth Number myDate getMonth convert month number to month name var monthName Str...

Page 18: ...on page 23 Void data type on page 23 ActionScript also has built in classes such as Array and Date that can be considered complex data types If you are an advanced developer you might create custom cl...

Page 19: ...ot be represented in ActionScript except by special escape sequences The following table provides all the ActionScript escape characters Strings in ActionScript are immutable the same as Java Any oper...

Page 20: ...to control the flow of a script The following example checks that users enter values into two TextInput component instances Two Boolean variables are created userNameEntered and isPasswordCorrect and...

Page 21: ...called user and creates three properties name age and phone which are String and Numeric data types var user Object new Object user name Irving user age 32 user phone 555 1234 For more information see...

Page 22: ...e 1 0x000000 100 square_mc beginFill 0xFF0000 100 square_mc moveTo 100 100 square_mc lineTo 200 100 square_mc lineTo 200 200 square_mc lineTo 100 200 square_mc lineTo 100 100 square_mc endFill square_...

Page 23: ...e frames the code does not execute a second time because the init variable is no longer undefined Void data type The void data type has one value void and is used in a function definition to indicate...

Page 24: ...data types as needed in the following example when used with a string the addition operator expects the other operand to be a string Next in line number 7 ActionScript converts the number 7 to the str...

Page 25: ...tch errors at compile time For example suppose you type the following code in the Student as class file class Student var status Boolean property of Student objects in a script var studentMaryLago Stu...

Page 26: ...rk myAnimal Animal var foo Dog Dog myAnimal if foo foo bark You can cast an expression to an interface If the expression is an object that implements the interface or has a base class that implements...

Page 27: ...eferenced Initializing a variable helps you track and compare the variable s value as the SWF file plays Variables can hold any type of data see About data types on page 18 The type of data a variable...

Page 28: ...able scopes For more information see Controlling member access on page 53 and Creating class members on page 60 Local variables To declare local variables use the var statement inside the body of a fu...

Page 29: ...r 2 counter local variable trace counter accesses local variable and displays 0 through 2 count trace counter accesses global variable and displays 100 This example simply shows that the global variab...

Page 30: ...umber x x return x var inValue Number 3 var out Number sqr inValue trace inValue 3 trace out 9 The value of the variable inValue does not change even though the value of x in the function changes The...

Page 31: ...calling a function Operators are characters that specify how to combine compare or modify the values of an expression The elements that the operator performs on are called operands For example in the...

Page 32: ...the order in which they are performed Associativity can be either left to right or right to left For example the multiplication operator has an associativity of left to right therefore the following...

Page 33: ...us Right to left Bitwise left shift Left to right Bitwise right shift Left to right Bitwise right shift unsigned Left to right instanceof Instance of finds the class of which the object is an instance...

Page 34: ...score 100 highScore else lowScore In the following example if the user s entry a string variable userEntry matches their stored password the playhead moves to a named frame called welcomeUser if user...

Page 35: ...r lowercase before comparing them Operator Operation performed Less than Returns true if the left operand is mathematically smaller than the right operand Returns true if the left operand alphabetical...

Page 36: ...ll be greater than 50 consider putting the condition i 50 first the condition i 50 will be checked first and the second condition doesn t need to be checked in most cases The following table lists the...

Page 37: ...the strict equality operator returns false The strict inequality operator returns the opposite of the strict equality operator The following table lists the ActionScript equality operators Assignment...

Page 38: ...t must be an identifier The following examples use the dot operator year month June year month day 9 The dot operator and the array access operator perform the same role but the dot operator takes an...

Page 39: ...ally set and retrieve instance names and variables as shown in the following example eval mc i The array access operator can also be used on the left side of an assignment statement This lets you dyna...

Page 40: ...ression and executes the code in the body of the loop if the expression is true After each statement in the body is executed the expression is evaluated again You can use the do while statement to cre...

Page 41: ...where in a SWF file If you pass values as parameters to a function the function will operate on those values A function can also return values Flash has built in functions that let you access certain...

Page 42: ...atement You can use a function literal to define a function return its value and assign it to a variable in one expression as shown in the following example area function return Math PI radius radius...

Page 43: ...ction Use the return statement to return values from functions The return statement stops the function and replaces it with the value of the return statement The following rules govern how to use the...

Page 44: ...y and pass any required parameters inside parentheses For example the following statement invokes the function sqr in the object mathLib passes the parameter 3 to it and stores the result in the varia...

Page 45: ...ace and packages that will be familiar to you if you ve programmed with Java Strict data typing ActionScript 2 0 also lets you explicitly specify data types for variables function parameters and funct...

Page 46: ...re jointly referred to as members of that class The characteristics in the cat example name age and color are called properties of the class and are represented as variables the behaviors eating sleep...

Page 47: ...rface that declares the chaseTail and eatCatNip methods A Cat class or any other class could then implement this interface and provide definitions for those methods Unlike Java interfaces ActionScript...

Page 48: ...in another script or creating a subclass based on the original class This section also discusses a feature in ActionScript 2 0 called strict data typing which lets you specify the data type for a var...

Page 49: ...perties are defined at the top of the class body which makes the code easier to understand but this isn t required The colon syntax var age Number and var name String used in the variable declarations...

Page 50: ...tring return Hello my name is this name and I m this age years old This code is the completed code for this class The return value of the getInfo function is strictly typed optional but recommended as...

Page 51: ...s in more detail Creating and using classes As discussed in Using classes a simple example on page 48 a class consists of two parts the declaration and the body The class declaration consists minimall...

Page 52: ...classes see the following topics Constructor functions on page 52 Creating properties and methods on page 53 Controlling member access on page 53 Initializing properties inline on page 54 Creating su...

Page 53: ...ethod definition The this keyword is not required in ActionScript 2 0 class definitions because the compiler resolves the reference and adds it into the bytecode However using this can improve your co...

Page 54: ...or public members The this keyword is not required in ActionScript 2 0 class definitions because the compiler resolves the reference and adds it into the bytecode However using this can improve your c...

Page 55: ...erties or methods that you have declared to be private using the private keyword For more information on private variables see Controlling member access on page 53 You can extend your own custom class...

Page 56: ...r For example the following code creates a new instance of the Person class a_person and then tries to assign a value to a property named hairColor which doesn t exist var a_person Person new Person a...

Page 57: ...d subpackages each with its own class files Package names must be identifiers that is the first character must be a letter underscore _ or dollar sign and each subsequent character must be a letter nu...

Page 58: ...methods these classes will use to communicate and then have each class implement provide its own definitions for those methods You can usually program successfully without using interfaces When used...

Page 59: ...the interface This is useful for determining if a given object implements a given interface For example consider the following interface interface Movable function moveUp Void function moveDown Void N...

Page 60: ...own in the following example ClassName classMember For example the ActionScript Math class consists only of static methods and properties To call any of its methods you don t create an instance of the...

Page 61: ...n design pattern The Singleton design pattern makes sure that a class has only one instance and provides a way of globally accessing the instance For more information on the Singleton design pattern s...

Page 62: ...in the Output panel To create an instance counter using a class variable 1 Create a new ActionScript AS file 2 Add the following code to the file class Widget static var widgetCount Number 0 initializ...

Page 63: ...ractice discourages direct access to properties within a class Classes typically define getter methods that provide read access and setter methods that provide write access to a given property For exa...

Page 64: ...es getter and setter methods named user you could not also have a property named user in the same class Unlike ordinary methods getter setter methods are invoked without any parentheses or arguments F...

Page 65: ...e a class s abbreviated name rather than its fully qualified name You can also use the wildcard character to import all the classes in a package For example suppose you created a class named UserClass...

Page 66: ...66 Chapter 2 Creating Custom Classes with ActionScript 2 0...

Page 67: ...g Flex Security in Developing Flex Applications Sending and loading variables to and from a remote source A SWF file is a window for capturing and displaying information much like an HTML page However...

Page 68: ...ck to see if it has been loaded For example you can t load variables and manipulate their values in the same script because the data to manipulate doesn t exist in the file until it is loaded In the f...

Page 69: ...ariables to load them into the SWF file each time someone played the game The function call might look like the following example loadVariables http www mySite com scripts high_score cfm scoreClip GET...

Page 70: ...onLoad instead of the obsolete deprecated onClipEvent data approach required for loadVariables There are error notifications You can add custom HTTP request headers You must create a LoadVars object t...

Page 71: ...ActionScript provides a built in XMLSocket class which lets you open a continuous connection with a server A socket connection lets the server publish or push information to the client as soon as tha...

Page 72: ...lhost 12345 displays text regarding connection theSocket onConnect function myStatus if myStatus conn_txt text connection successful else conn_txt text no connection made data to send function sendDat...

Page 73: ...table shows the values you can specify for the command and arguments parameters of fscommand to control the playback and appearance of a SWF file playing in the stand alone player including projector...

Page 74: ...sends a VB event with two strings that can be handled in the environment s programming language For more information use the keywords Flash method to search the Flash Support Center at www macromedia...

Page 75: ...view as you write your scripts For an overview of how to use ActionScript see Part I Welcome to ActionScript Chapter 4 About the ActionScript Language Reference 77 Chapter 5 ActionScript Core Language...

Page 76: ......

Page 77: ...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...

Page 78: ...lasses are listed in Chapter 5 ActionScript Core Language Elements on page 80 Classes that are specific to Flash are listed alphabetically with other Flash language elements in Chapter 7 ActionScript...

Page 79: ...Sample entry for classes 79 Method property and event handler listings The methods properties and event handlers of a class are listed alphabetically after the class entry...

Page 80: ...o 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...

Page 81: ...e operator expression subtracts 1 from the expression and returns the initial value of expression the value prior to the subtraction For more information see Operator precedence and associativity on p...

Page 82: ...pression and returns the initial value of expression the value prior to the addition The pre increment form of the operator increments x to 2 x 1 2 and returns the result as y var x Number 1 var y Num...

Page 83: ...result to the log file 1 2 3 4 5 6 7 8 9 10 The following example uses as a post increment operator in a while loop using a while loop var a Array var a Array new Array var i Number 0 while i 10 a pus...

Page 84: ...f using the logical NOT operator true returns false false returns true For more information see Operator precedence and associativity on page 32 Example In the following example the variable happy is...

Page 85: ...al only if they both refer to the same object array or function Values inside the object array or function are not compared When comparing by value if expression1 and expression2 are different data ty...

Page 86: ...Array 1 2 3 trace a 1 2 3 trace b 1 2 3 trace a b true a b trace a 1 2 3 trace b 1 2 3 trace a b false trace statement output 1 2 3 1 2 3 true 1 2 3 1 2 3 false See also logical NOT strict inequality...

Page 87: ...and functions are compared by reference A variable is compared by value or by reference depending on its type For more information see Operator precedence and associativity on page 32 Example The comm...

Page 88: ...the modulo operator trace 12 5 traces 2 trace 4 3 2 1 traces 0 0999999999999996 trace 4 4 traces 0 The first trace returns 2 rather than 12 5 or 2 4 because the modulo operator returns only the remai...

Page 89: ...icant digits discarded when they are converted so the value is still 32 bit Negative numbers are converted to an unsigned hex value using the two s complement notation with the minimum being 214748364...

Page 90: ...al AND Availability Flash Player 4 Usage expression1 expression2 Parameters None Returns A Boolean value Description Operator logical performs a Boolean operation on the values of one or both of the e...

Page 91: ...race You Win the Game else trace Try Again output You Win the Game See also logical NOT inequality strict inequality logical OR equality strict equality bitwise AND assignment Availability Flash Playe...

Page 92: ...sses them as parameters to a function outside the parentheses Usage 1 Controls the order in which the operators execute in the expression Parentheses override the normal precedence order and cause the...

Page 93: ...ilability Flash Player 4 Usage Negation expression Subtraction expression1 expression2 Parameters None Returns An integer or floating point number Description Operator arithmetic used for negating or...

Page 94: ...Flash Player 4 Usage expression1 expression2 Parameters None Returns An integer or floating point number Description Operator arithmetic multiplies two numerical expressions If both expressions are i...

Page 95: ...ng two expressions are equivalent x y x x y For more information see Operator precedence and associativity on page 32 Example Usage 1 The following example assigns the value 50 to the variable x var x...

Page 96: ...var v Number 0 v 4 5 6 trace v output 4 The following example uses the comma operator with the parentheses operator and illustrates that the comma operator returns the value of the last expression wh...

Page 97: ...that is a child of or nested in another movie clip Returns The method property or movie clip named on the right side of the dot Description Operator used to navigate movie clip hierarchies to access...

Page 98: ...operator specifies the variable s type when used in a function declaration or definition this operator specifies the function s return type when used with a function parameter in a function definitio...

Page 99: ...lso var function conditional Availability Flash Player 4 Usage expression1 expression2 expression3 Parameters expression1 An expression that evaluates to a Boolean value usually a comparison expressio...

Page 100: ...4 Usage expression1 expression2 Parameters expression A number or a variable that evaluates to a number Returns A floating point number Description Operator arithmetic divides expression1 by expressi...

Page 101: ...eter Example The following script uses comment delimiters to identify the first third fifth and seventh lines as comments record the X position of the ball movie clip var ballX Number ball_mc _x recor...

Page 102: ...ill end the comment regardless of the number of opening comment tags placed between them For more information see Operator precedence and associativity on page 32 Example The following script uses com...

Page 103: ...Also division array access Availability Flash Player 4 Usage myArray a0 a1 aN myArray i value myObject propertyName Parameters myArray The name of an array a0 a1 aN Elements in an array any native typ...

Page 104: ...sage 2 Surround the index of each element with brackets to access it directly you can add a new element to an array or you can change or retrieve the value of an existing element The first index in an...

Page 105: ...he following ActionScript to loop over all objects in the _root scope which is useful for debugging for i in _root trace i _root i You can also use the array access operator on the left side of an ass...

Page 106: ...2147483647 For more information see Operator precedence and associativity on page 32 Example The following example uses the bitwise XOR operator on the decimals 15 and 9 and assigns the result to the...

Page 107: ...values for each name property Returns Usage 1 An Object object Usage 2 Nothing except when a function has an explicit return statement in which case the return type is specified in the function implem...

Page 108: ...account i The following example shows how array and object initializers can be nested within each other var person Object name Gina Vechio children Ruby Chickie Puppa The following example uses the i...

Page 109: ...eing 2147483648 or 0x800000000 numbers less than the minimum are converted to two s complement with greater precision and also have the most significant digits discarded The return value is interprete...

Page 110: ...nd associativity on page 32 Example The following example uses the logical OR operator in an if statement The second expression evaluates to true so the final result is true var x Number 10 var y Numb...

Page 111: ...ression1 expression2 For example the following two statements are equivalent x y x x y For more information see Operator precedence and associativity on page 32 Example The following example uses the...

Page 112: ...ts 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 d...

Page 113: ...er or string Returns A string integer or floating point number Description Operator adds numeric expressions or concatenates combines strings If one expression is a string all other expressions are co...

Page 114: ...ng or a number Description Operator arithmetic compound assignment assigns expression1 the value of expression1 expression2 For example the following two statements have the same result x y x x y This...

Page 115: ...e evaluated using alphabetical order all capital letters come before lowercase letters For more information see Operator precedence and associativity on page 32 Example The following examples show tru...

Page 116: ...00 numbers less than the minimum are converted to two s complement with greater precision and also have the most significant digits discarded The return value is interpreted as a two s complement numb...

Page 117: ...and stores the contents as a result in expression1 The following two expressions are equivalent A B A A B For more information see Operator precedence and associativity on page 32 Example In the foll...

Page 118: ...all capital letters come before lowercase letters For more information see Operator precedence and associativity on page 32 Example The following examples show true and false results for both numeric...

Page 119: ...e uses assignment by reference to create the moonsOfJupiter variable which contains a reference to a newly created Array object Assignment by value is then used to copy the value Callisto to the first...

Page 120: ...ements are equivalent x y x x y String expressions must be converted to numbers otherwise NaN not a number is returned For more information see Operator precedence and associativity on page 32 Example...

Page 121: ...equal if they refer to the same object array or function Two separate arrays are never considered equal even if they have the same number of elements When comparing by value if expression1 and expres...

Page 122: ...equality strict inequality logical AND logical OR strict equality strict equality Availability Flash Player 6 Usage expression1 expression2 Returns A Boolean value Description Operator tests two expre...

Page 123: ...ean false trace string1 bool2 true trace string1 bool2 false The following examples show how strict equality treats variables that are references differently than it treats variables that contain lite...

Page 124: ...letters come before lowercase letters For more information see Operator precedence and associativity on page 32 Example In the following example the greater than operator is used to determine whether...

Page 125: ...ts on the left are filled in with 0 if the most significant bit the bit farthest to the left of expression1 is 0 and filled in with 1 if the most significant bit is 1 Shifting a value right by one pos...

Page 126: ...ample shows the result of the previous example var x Number 1 This is because 1 decimal equals 11111111111111111111111111111111 binary thirty two 1 s shifting right by one bit causes the least signifi...

Page 127: ...right by one bit to see next bit numberToConvert 1 return result trace convertToBinary 479 Returns the string 00000000000000000000000111011111 This string is the binary representation of the decimal...

Page 128: ...Number 1 1 trace x output 2147483647 This is because 1 decimal is 11111111111111111111111111111111 binary thirty two 1 s and when you shift right unsigned by 1 bit the least significant rightmost bit...

Page 129: ...ue is true Note Unlike the Boolean class constructor the Boolean function does not use the keyword new Moreover the Boolean class constructor initializes a Boolean object to false if no parameter is s...

Page 130: ...s 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...

Page 131: ...x and then by using the Array class s push method var myArray Array Array myArray push 12 trace myArray traces 12 myArray 4 7 trace myArray traces 12 undefined undefined undefined 7 Usage 2 The follow...

Page 132: ...sed in a switch the break statement instructs Flash to skip the rest of the statements in that case block and jump to the first statement following the enclosing switch statement In nested loops the b...

Page 133: ...break 133 See also for for in do while while switch case continue throw try catch finally...

Page 134: ...ase statement outside a switch statement it produces an error and the script doesn t compile Note You should always end the statement s parameter with a break statement If you omit the break statement...

Page 135: ...case 135 See also break default strict equality switch...

Page 136: ...se the fully qualified class name of the form base sub1 sub2 MyClass for more information see Using packages on page 57 Also the class s AS file must be stored within the path in a directory structure...

Page 137: ..._leafType this bloomSeason param_bloomSeason Create methods to return property values because best practice recommends against directly referencing a property of a class function getLeafType String re...

Page 138: ...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...

Page 139: ...mple The following example first sets and then clears an interval call function callback trace interval called getTimer ms var intervalID Number setInterval callback 1000 You need to clear the interva...

Page 140: ...the loop body and jump to the top of the loop where the condition is tested trace example 1 var i Number 0 while i 10 if i 3 0 i continue trace i i In the following do while loop continue causes the F...

Page 141: ...for in loop continue causes the Flash interpreter to skip the rest of the loop body and jump back to the top of the loop where the next value in the enumeration is processed for i in _root if i versi...

Page 142: ...have a default case statement A default case statement does not have to be last in the list If you use a default statement outside a switch statement it produces an error and the script doesn t compi...

Page 143: ...ly used as a statement as shown in the following example delete x The delete operator can fail and return false if the reference parameter does not exist or cannot be deleted Predefined objects and pr...

Page 144: ...undefined Usage 4 The following example shows the behavior of delete on object references var ref1 Object new Object ref1 name Jody copy the reference variable into a new variable and delete ref1 ref2...

Page 145: ...statements to be executed before the while loop begins many programmers believe that do while loops are easier to read If the condition always evaluates to true the do while loop is infinite If you en...

Page 146: ...146 Chapter 5 ActionScript Core Language Elements See also break continue while...

Page 147: ...be type checked for return type and parameter types Subclasses of dynamic classes are also dynamic For more information see Creating dynamic classes on page 56 Example In the following example class P...

Page 148: ...ig i output Error Scene Scene 1 layer Layer 1 frame 1 Line 14 There is no property with the name dance craig dance true Total ActionScript Errors 1 Reported Errors 1 Add the dynamic keyword to the Per...

Page 149: ...enclose the block of statements to be executed by the else statement are not necessary if only one statement will execute Example In the following example the else condition is used to check whether...

Page 150: ...f the else if condition returns true the Flash interpreter runs the statements that follow the condition inside curly braces If the else if condition is false Flash skips the statements inside the cur...

Page 151: ...ntroduce escape characters and is not equivalent to the modulo operator Example The following code produces the result someuser 40somedomain 2Ecom var email String someuser somedomain com trace escape...

Page 152: ...ariable or property is returned If expression is an object or movie clip a reference to the object or movie clip is returned If the element named in expression cannot be found undefined is returned Ex...

Page 153: ...sses on page 55 Interfaces can also be extended using the extends keyword An interface that extends another interface includes all the original interface s method declarations Example In the following...

Page 154: ...h anti lock brakes The following example instantiates a Car object calls a method defined in the Vehicle class start then calls the method overridden by the Car class stop and finally calls a method f...

Page 155: ...hod overridden by the Truck class reverse then calls a method defined in the Vehicle class stop var myTruck Truck new Truck 2 White 18 myTruck reverse output Truck make beeping sound Vehicle reverse m...

Page 156: ...r it becomes 0 when it converts false to a string it becomes false For more information see Automatic data typing on page 24 Example This example shows how automatic data typing converts false to a nu...

Page 157: ...tement evaluates the init initialize expression once and then starts a looping sequence The looping sequence begins by evaluating the condition expression If the condition expression evaluates to true...

Page 158: ...or 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 wil...

Page 159: ...rs The for in statement iterates over properties of objects in the iterated object s prototype chain Properties of the object are enumerated first then properties of its immediate prototype then prope...

Page 160: ...in myArray trace myArray index myArray index output myArray 2 three myArray 1 two myArray 0 one The following example uses the typeof operator with for in to iterate over a particular type of child f...

Page 161: ...ction to control a SWF file playing in Flash Player including projectors A projector is a SWF file saved in a format that can run as a stand alone application that is without Flash Player Command Para...

Page 162: ...the name myDocument the JavaScript function called is myDocument_DoFScommand Usage 3 The fscommand function can send messages to Macromedia Director that are interpreted by Lingo Director s scripting...

Page 163: ...a function each time you call it so you can reuse a function in different situations Use the return statement in a function s statement s to cause a function to generate or return a value You can use...

Page 164: ...rameter and returns the Math pow x 2 of the parameter 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...

Page 165: ...ect addProperty method in ActionScript 1 For more information see Implicit getter setter methods on page 63 Example In the following example you define a Team class The Team class includes get set met...

Page 166: ...166 Chapter 5 ActionScript Core Language Elements 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 set...

Page 167: ...ns the number of milliseconds that have elapsed since the SWF file started playing Example In the following example the getTimer and setInterval functions are used to create a simple timer this create...

Page 168: ...variables omit this parameter The GET method appends the variables to the end of the URL and is used for small numbers of variables The POST method sends the variables in a separate HTTP header and is...

Page 169: ...onRelease function getURL http www macromedia com _blank GET The following ActionScript uses POST to send variables in the HTTP header Make sure you test your documents in a browser window because oth...

Page 170: ...ion number of the Flash Player playing the SWF file var flashVersion String getVersion trace flashVersion output WIN 7 0 19 0 trace version output WIN 7 0 19 0 trace System capabilities version output...

Page 171: ...e the fully qualified name of the variable e g _global variableName Failure to do so will create a local variable of the same name that obscures the global variable you are attempting to set Example T...

Page 172: ...re not necessary if only one statement will execute Example The following example uses an if statement to evaluate how long it takes a user to click the submit_btn instance in a SWF file If a user cli...

Page 173: ...ace02 Description Keyword specifies that a class must define all the methods declared in the interface or interfaces being implemented For more information see Interfaces as data types on page 59 Exam...

Page 174: ...s UserClass after importing import macr util users UserClass var myUser UserClass new UserClass If there are several class files in the package working_directory macr utils users that you want to acce...

Page 175: ...ath the AS file must be in the same directory as the script containing the include statement To specify a relative path for the AS file use a single dot to indicate the current directory two dots to i...

Page 176: ...ript 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_script...

Page 177: ...ility 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 CHAPTER 5 Action...

Page 178: ...s 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_INFINIT...

Page 179: ...d class Tests whether object is an instance of class The instanceof operator does not convert primitive types to wrapper objects For example the following code returns true new String Hello instanceof...

Page 180: ...ermitted The get and set statements are not allowed in interface definitions FFor more information see Creating and using interfaces on page 58 Example The following example shows several ways to defi...

Page 181: ...n 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 funct...

Page 182: ...value Description Function evaluates expression and returns true if it is a finite number or false if it is infinity or negative infinity The presence of infinity or negative infinity indicates a math...

Page 183: ...trace isNaN Tree returns true trace isNaN 56 returns false trace isNaN Number POSITIVE_INFINITY returns false The following example shows how you can use isNAN to check whether a mathematical expressi...

Page 184: ...ts NaN Availability Flash Player 5 Usage NaN Description Variable a predefined variable with the IEEE 754 value for NaN not a number To determine if a number is NaN use isNaN See also isNaN Number NaN...

Page 185: ...heses as well as the newly created object which is referenced using the keyword this The constructor function can use this to set the variables of the object Example The following example creates the...

Page 186: ...ank line in text output generated by your code Use newline to make space for information that is retrieved by a function or statement in your code Example The following example shows how newline write...

Page 187: ...was provided You can use null to represent values that are missing or that do not have a defined data type Example In a numeric context null evaluates to 0 Equality tests can be performed with null In...

Page 188: ...function attempts to parse expression as a decimal number with an optional trailing exponent that is 1 57505e 3 If expression is NaN the return value is NaN If expression is undefined the return valu...

Page 189: ...and is equivalent to creating an object using the Object constructor see Constructor for the Object class on page 376 Example In the following example a new empty object is created and then the object...

Page 190: ...e the pointer is over the button the mouse button is pressed and then rolls outside the button area dragOver While the pointer is over the button the mouse button has been pressed then rolled outside...

Page 191: ...startDrag function executes when the mouse is pressed and the conditional script is executed when the mouse is released and the object is dropped on press startDrag this on release trace X this _x tra...

Page 192: ...not a part of the initial number If the string does not begin with a number that can be parsed parseFloat returns NaN White space preceding valid integers is ignored as are trailing nonnumeric charac...

Page 193: ...pecifying a radix of 8 are interpreted as octal numbers White space preceding valid integers is ignored as are trailing nonnumeric characters Example The examples in this section use the parseInt func...

Page 194: ...r 5 ActionScript Core Language Elements 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 p...

Page 195: ...he following example demonstrates how you can hide certain properties within a class using the private keyword Create a new AS file called Login as class Login private var loginUserName String private...

Page 196: ...Script Core Language Elements Because loginPassword is a private variable you cannot access it from outside the Login as class file Attempts to access the private variable generate an error message Se...

Page 197: ...at also contains private or static variables Example The following example shows how you can use public variables in a class file Create a new class file called User as and enter the following code cl...

Page 198: ...mmediately to the calling function If the return statement is used alone it returns undefined You can t return multiple values If you try to do so only the last value is returned In the following exam...

Page 199: ...licit get set methods are syntactic shorthand for the Object addProperty method in ActionScript 1 For more information see Implicit getter setter methods on page 63 Example The following example creat...

Page 200: ...ctionScript var gus Login new Login Gus Smith trace gus username output Gus gus username Rupert trace gus username output Rupert In the following example the get function executes when the value is tr...

Page 201: ...ata type associated with the variable in a class file no compiler error is generated A subtle but important distinction to bear in mind is that the parameter variableString is a string not a variable...

Page 202: ...Language Elements The following code loops three times and creates three new variables called caption0 caption1 and caption2 for var i 0 i 3 i set caption i this is caption i trace caption0 trace capt...

Page 203: ...ing integer that you can pass to clearInterval to cancel the interval Description Function calls a function or a method or an object at periodic intervals while a SWF file plays You can use an interva...

Page 204: ...unction by using clearInterval when you have finished using it as shown in the following example create an event listener object for our MovieClipLoader instance var listenerObjectbject new Object lis...

Page 205: ...al 205 jpeg_mcl addListener listenerObject jpeg_mcl loadClip http www macromedia com software central images klynch_breezo jpg this createEmptyMovieClip jpeg_mc this getNextHighestDepth See also clear...

Page 206: ...er using the instance You can use this keyword in class definitions only not in interface definitions Example The following example demonstrates how you can use the static keyword to create a counter...

Page 207: ...or other ActionScript element Example The following example uses quotation marks to indicate that the value of the variable yourGuess is the literal string Prince Edward Island and not the name of a...

Page 208: ...y calling the string property for the object or by calling Object toString if no such property exists If expression is undefined the return value is undefined If expression is a Boolean value the retu...

Page 209: ...onstructor function to invoke the superclass version of the constructor function and can optionally pass parameters to it This is useful for creating a subclass that performs additional initialization...

Page 210: ...n trace mySock getColor mySock setColor Orange trace mySock getColor The following result is written to the log file Clothes I am the constructor Socks I am the constructor Socks I am getColor Clothes...

Page 211: ...true All switch statements should include a default case The default case should include a break statement that prevents a fall through error if another case is added later When a case falls through...

Page 212: ...2 Chapter 5 ActionScript Core Language Elements 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 i...

Page 213: ...str String Defined in ApplyThis as function conctStr x String String return x x function addStr String return str Then in a FLA or AS file add the following ActionScript var obj ApplyThis new ApplyThi...

Page 214: ...of Simple as Example In the following example the keyword this references the Circle object function Circle radius Number Void this radius radius this area Math PI Math pow radius 2 var myCircle new...

Page 215: ...t contain an symbol the function throws an error function checkEmail email String if email indexOf 1 throw new Error Invalid email address checkEmail someuser_theirdomain com The following code then c...

Page 216: ...pt 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...

Page 217: ...sages in the log file Use the expression parameter to check whether a condition exists or to write values to the log file Example The following example uses a trace statement to write the methods and...

Page 218: ...ue in an if statement var shouldExecute Boolean code that sets shouldExecute to either true or false goes here shouldExecute is set to true for this example shouldExecute true if shouldExecute true tr...

Page 219: ...lock completes normally then the code in the finally block is still executed The finally block executes even if the try block exits using a return statement A try block must be followed by a catch blo...

Page 220: ...r not an error occurs Because setInterval is used clearInterval must be placed in the finally block to ensure that the interval is cleared from memory myFunction function trace this is myFunction try...

Page 221: ...e block throws a different type of object In this case myRecordSet is an instance of a hypothetical class named RecordSet whose sortRows method can throw two types of errors RecordSetException and Mal...

Page 222: ...nvokes the sortRows method on an instance of the RecordSet class It defines catch blocks for each type of error that is thrown by sortRows import RecordSet var myRecordSet RecordSet new RecordSet try...

Page 223: ...ssion is a string movie clip object function number or Boolean value The following table shows the results of the typeof operator on each type of expression nu Example In the following example all ins...

Page 224: ...compared with the strict equality operator they compare as not equal Example In the following example the variable x has not been declared and therefore has the value undefined In the first section o...

Page 225: ...at converting all hexadecimal sequences to ASCII characters and returns the string Example The following example shows the escape to unescape conversion process var email String user somedomain com tr...

Page 226: ...length 25 syntax error When you use var you can strictly type the variable For more information see Strict data typing on page 24 Note You must also use var when declaring properties inside class defi...

Page 227: ...ed values if someUndefinedVariable void 0 trace someUndefinedVariable is undefined The previous code can also be written in the following way if someUndefinedVariable undefined trace someUndefinedVari...

Page 228: ...ression condition is evaluated 2 If condition evaluates to true or a value that converts to the Boolean value true such as a nonzero number go to step 3 Otherwise the while statement is completed and...

Page 229: ...while 229 i 3 The following result is written to the log file 0 3 6 9 12 15 18 See also do while continue for for in...

Page 230: ...length and my_array concat In another example if object is state california any actions or statements inside the with statement are called from inside the california instance To find the value of an...

Page 231: ...y In the following example the built in Math object is placed at the front of the scope chain Setting Math as a default object resolves the identifiers cos sin and PI to Math cos Math sin and Math PI...

Page 232: ...hat 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 informat...

Page 233: ...if the Flash Player is communicating with an accessibility aid usually a screen reader false otherwise Description Method indicates whether an accessibility aid is currently active and the player is...

Page 234: ...all changes to _accProps accessibility properties objects to take effect For information on setting accessibility properties see _accProps If you modify the accessibility properties for multiple obje...

Page 235: ...extArea and TextInput controls For changes to these properties to take effect you must call Accessibility updateProperties To determine whether the player is running in an environment that supports ac...

Page 236: ...name Price Accessibility updateProperties If you are specifying several accessibility properties make as many changes as you can before calling Accessibility updateProperties instead of calling it af...

Page 237: ...e arguments callee Function Description Property refers to the function that is currently being called Example You can use the arguments callee property to make an anonymous function that is recursive...

Page 238: ...functions a caller function named function1 which calls a another function named function2 define the caller function named function1 var function1 Function function function2 hello from function1 def...

Page 239: ...turn arguments length trace getArgLength one two three output 3 trace getArgLength one two output 2 trace getArgLength one two three four output 4 In the following example the function called listSum...

Page 240: ...d Description Array concat Concatenates the parameters and returns them as a new array Array join Joins all elements of an array into a string Array pop Removes the last element of an array and return...

Page 241: ...of arrays an empty array an array with a specific length but whose elements have undefined values or an array whose elements have specific values Usage 1 If you don t specify any parameters an array...

Page 242: ...onna go_gos_array 1 Nina trace go_gos_array join returns Belinda Nina Kathy Charlotte Jane Donna See also Array length array access Array concat Availability Flash Player 5 Usage my_array concat value...

Page 243: ...new Array a b c 2 and 3 are elements in a nested array var n_array Array new Array 1 2 3 4 var x_array Array a_array concat n_array trace x_array 0 a trace x_array 1 b trace x_array 2 c trace x_array...

Page 244: ...rray Europa Io Callisto Titan Rhea trace a_nested_array join returns Europa Io Callisto Titan Rhea See Also String split Array length Availability Flash Player 5 Usage my_array length Number Descripti...

Page 245: ...pop Object Parameters None Returns The value of the last element in the specified array Description Method removes the last element from an array and returns the value of that element Example The foll...

Page 246: ...ement in the last line sends the new length of myPets_array 4 to the log file var myPets_array Array new Array cat dog var pushed Number myPets_array push bird fish trace pushed displays 4 See Also Ar...

Page 247: ...ys cat trace myPets_array displays dog bird fish See also Array pop Array push Array unshift Array slice Availability Flash Player 5 Usage my_array slice start Number end Number Array Parameters start...

Page 248: ...ents from the array var myPets_array Array new Array cat dog fish canary parrot var myFlyingPets_array Array myPets_array slice 2 trace myFlyingPets_array traces canary parrot The following example cr...

Page 249: ...option Flash returns an array that reflects the results of the sort and does not modify the array Otherwise Flash returns nothing and modifies the array to reflect the sort order Description Method s...

Page 250: ...erries apples Usage 2 The following example uses Array sort with a compare function var passwords_array Array new Array mom glam ana ring jay mag anne home regina silly function order a b Number Entri...

Page 251: ...t each option see Description on page 251 Returns The return value depends on whether you pass any parameters as described in the following list If you specify a value of 4 or Array UNIQUESORT for opt...

Page 252: ...ray sort To pass multiple flags in numeric format separate them with the bitwise OR operator or add the values of the flags together The following code shows three ways to specify a numeric descending...

Page 253: ...e 4 After any sort that doesn t pass a value of 8 for option my_array sortOn age Array NUMERIC my_array 0 age 3 my_array 1 age 4 my_array 2 age 29 my_array 3 age 35 Performing a sort that returns an i...

Page 254: ...rec_array length i trace rec_array i name rec_array i city results john omaha john kansas city bob omaha rec_array sortOn name city for i 0 i rec_array length i trace rec_array i name rec_array i city...

Page 255: ...original array var myPets_array Array new Array cat dog bird fish trace myPets_array splice 1 dog bird fish trace myPets_array cat The following example creates an array and splices it using element i...

Page 256: ...e following example creates my_array converts it to a string and writes 1 2 3 4 5 to the log file my_array Array new Array my_array 0 1 my_array 1 2 my_array 2 3 my_array 3 4 my_array 4 5 trace my_arr...

Page 257: ...he 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 goph...

Page 258: ...pression This parameter is optional Returns A reference to a Boolean object Description Constructor creates a Boolean object If you omit the x parameter the Boolean object is initialized with a value...

Page 259: ...alue of the Boolean myBool is myBool toString myBool false trace The value of the Boolean myBool is myBool toString Boolean valueOf Availability Flash Player 5 Usage myBoolean valueOf Boolean Paramete...

Page 260: ...cal time Date getHours Returns the hour according to local time Date getMilliseconds Returns the milliseconds according to local time Date getMinutes Returns the minutes according to local time Date g...

Page 261: ...e Sets the date according to universal time Returns the new time in milliseconds Date setUTCFullYear Sets the year according to universal time Returns the new time in milliseconds Date setUTCHours Set...

Page 262: ...optional millisecond An integer from 0 to 999 This parameter is optional Returns A reference to a Date object Description Constructor constructs a new Date object that holds the specified date or the...

Page 263: ...he returned values of Date getMonth Date getDate and Date getFullYear var today_date Date new Date var date_str String today_date getDate today_date getMonth 1 today_date getFullYear trace date_str di...

Page 264: ...ear Number Parameters None Returns An integer representing the year Description Method returns the full year a four digit number such as 2000 of the specified Date object according to local time Local...

Page 265: ...te getHours var my_date Date new Date var hourObj Object getHoursAmPm my_date getHours trace hourObj hours trace hourObj ampm function getHoursAmPm hour24 Number Object var returnObj Object new Object...

Page 266: ...meters None Returns An integer Description Method returns the minutes an integer from 0 to 59 of the specified Date object according to local time Local time is determined by the operating system on w...

Page 267: ...me of the month var my_date Date new Date trace my_date getMonth trace getMonthAsString my_date getMonth function getMonthAsString month Number String var monthNames_array Array new Array January Febr...

Page 268: ...in time when comparing two or more Date objects Example The following example uses the constructor to create a Date object based on the current time and uses the getTime method to return the number of...

Page 269: ...locale and time of year Date getUTCDate Availability Flash Player 5 Usage my_date getUTCDate Number Parameters None Returns An integer Description Method returns the day of the month an integer from...

Page 270: ...y_date getUTCDay output will equal getDay plus or minus one Date getUTCFullYear Availability Flash Player 5 Usage my_date getUTCFullYear Number Parameters None Returns An integer Description Method re...

Page 271: ...returned by Date getUTCHours may differ from the value returned by Date getHours depending on the relationship between your local time zone and universal time var today_date Date new Date trace today_...

Page 272: ...Usage my_date getUTCMinutes Number Parameters None Returns An integer Description Method returns the minutes an integer from 0 to 59 of the specified Date object according to universal time Example Th...

Page 273: ...today_date Date new Date trace today_date getMonth output based on local timezone trace today_date getUTCMonth output equals getMonth plus or minus 1 Date getUTCSeconds Availability Flash Player 5 Usa...

Page 274: ...getYear output 104 trace today_date getFullYear output 2004 See also Date getFullYear Date setDate Availability Flash Player 5 Usage my_date setDate date Number Parameters date An integer from 1 to 31...

Page 275: ...parameters are specified they are set to local time Local time is determined by the operating system on which Flash Player is running Calling this method does not modify the other fields of the specif...

Page 276: ...iseconds Availability Flash Player 5 Usage my_date setMilliseconds millisecond Number Number Parameters millisecond An integer from 0 to 999 Returns An integer Description Method sets the milliseconds...

Page 277: ...e and date to 8 00 a m on May 15 2004 and then uses Date setMinutes to change the time to 8 30 a m var my_date Date new Date 2004 4 15 8 0 trace my_date getMinutes output 0 my_date setMinutes 30 trace...

Page 278: ...sets the seconds for the specified Date object in local time and returns the new time in milliseconds Local time is determined by the operating system on which Flash Player is running Example The foll...

Page 279: ..._date getDate output 15 trace my_date getHours output 8 trace my_date getMinutes output 30 Date setUTCDate Availability Flash Player 5 Usage my_date setUTCDate date Number Number Parameters date A num...

Page 280: ...presented by the specified Date object Calling this method does not modify the other fields of the specified Date object but Date getUTCDay and Date getDay can report a new value if the day of the wee...

Page 281: ...ate object with today s date uses Date setUTCHours to change the time to 8 30 a m and changes the time again to 5 30 47 p m var my_date Date new Date my_date setUTCHours 8 30 trace my_date getUTCHours...

Page 282: ...Number Number Parameters minute An integer from 0 to 59 second An integer from 0 to 59 This parameter is optional millisecond An integer from 0 to 999 This parameter is optional Returns An integer De...

Page 283: ...004 and uses Date setMonth to change the date to June 15 2004 var today_date Date new Date 2004 4 15 trace today_date getUTCMonth output 4 today_date setUTCMonth 5 trace today_date getUTCMonth output...

Page 284: ...nd returns the new time in milliseconds Local time is determined by the operating system on which Flash Player is running Example The following example creates a new Date object with the date set to M...

Page 285: ...Number minute Number second Number millisecond Number Number Parameters year A four digit integer that represents the year for example 2000 month An integer from 0 January to 11 December date An integ...

Page 286: ...me This is the universal time variation of the example used for the new Date constructor method var maryBirthday_date Date new Date Date UTC 1974 7 12 trace maryBirthday_date output will be in local t...

Page 287: ...rameters message A string associated with the Error object this parameter is optional Returns A reference to an Error object Description Constructor creates a new Error object If message is specified...

Page 288: ...a function throws a specified message depending on the parameters entered into theNum If two numbers can be divided SUCCESS and the number are shown Specific errors are shown if you try to divide by 0...

Page 289: ...arameters else if denominator 0 throw new DivideByZeroError return numerator denominator try var theNum Number divideNumber 1 0 trace SUCCESS theNum output DivideByZeroError Unable to divide by zero c...

Page 290: ...wing 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 str...

Page 291: ...ed within any function that ActionScript calls This method also specifies the parameters to be passed to any called function Because apply is a method of the Function class it is also a method of ever...

Page 292: ...shows how apply passes an array of parameters and specifies the value of this define a function function theFunction trace this myObj this myObj trace arguments arguments instantiate an object var my...

Page 293: ...of the function invocation needs to be explicitly controlled Normally if a function is invoked as a method of an object within the body of the function this is set to myObject as shown in the followi...

Page 294: ...er 6 ActionScript Core Classes var obj Object new myObject myMethod call obj obj The trace statement displays The trace statement sends the following code to the log file this obj true See also Functi...

Page 295: ...ey getCode Returns the virtual key code of the last key pressed Key isDown Returns true if the key specified in the parameter is pressed Key isToggled Returns true if the Num Lock or Caps Lock key is...

Page 296: ...stered no change occurs Example The following example creates a new listener object and defines a function for onKeyDown and onKeyUp The last line uses addListener to register the listener with the Ke...

Page 297: ...ner onKeyDown myOnKeyDown Key addListener myListener my_btn onPress myOnPress my_btn _accProps shortcut Ctrl 7 Accessibility updateProperties See also Key getCode Key isDown Key onKeyDown Key onKeyUp...

Page 298: ...sed the Caps Lock key trace tCaps Lock Key isToggled Key CAPSLOCK Key addListener keyListener Information is written to the log file when you press the Caps Lock key The log file writes either true or...

Page 299: ...g example lets you draw lines with the mouse pointer using the Drawing API and listener objects Press the Backspace or Delete key to remove the lines that you draw this createEmptyMovieClip canvas_mc...

Page 300: ...press the Spacebar Give a sound in the library a linkage identifier of horn_id for this example var DISTANCE Number 10 var horn_sound Sound new Sound horn_sound attachSound horn_id var keyListener_ob...

Page 301: ...ss the arrow keys The car_mc instance stops when you press Enter and delete the onEnterFrame event var DISTANCE Number 5 var keyListener Object new Object keyListener onKeyDown function switch Key get...

Page 302: ...the current timer convert the value to seconds and round it to two decimal places var timer Number Math round getTimer 10 100 trace you pressed the Esc key getTimer ms timer s Key addListener keyList...

Page 303: ...ample adds a call to Key getAscii to show how the two methods differ The main difference is that Key getAscii differentiates between uppercase and lowercase letters and Key getCode does not var keyLis...

Page 304: ...istener keyListener The following example adds a call to Key getAscii to show how the two methods differ The main difference is that Key getAscii differentiates between uppercase and lowercase letters...

Page 305: ...Property constant associated with the key code value for the Insert key 45 Example The following example creates a new listener object and defines a function for onKeyDown The last line uses addListen...

Page 306: ...oggled to an active state false otherwise Although the term toggled usually means that something is switched between two options the method Key isToggled will only return true if the key is toggled to...

Page 307: ...ect new Object keyListener onKeyDown function capsLock_txt htmlText b Caps Lock b Key isToggled Key CAPSLOCK numLock_txt htmlText b Num Lock b Key isToggled 144 Key addListener keyListener Key LEFT Av...

Page 308: ...nd use addListener to register the listener with the Key object as shown in the following example var keyListener Object new Object keyListener onKeyDown function trace DOWN Code Key getCode tACSII Ke...

Page 309: ...y getAscii tKey chr Key getAscii Key addListener keyListener Listeners enable different pieces of code to cooperate because multiple listeners can receive notification about a single event See also Ke...

Page 310: ...yListener Key removeListener Availability Flash Player 6 Usage Key removeListener listener Object Boolean Parameters listener An object Returns If the listener was successfully removed the method retu...

Page 311: ...d car_mc a constant distance 10 when you press the arrow keys A sound plays when you press the Spacebar Give a sound in the library a linkage identifier of horn_id for this example var DISTANCE Number...

Page 312: ...scale 2 Key addListener keyListener Key SPACE Availability Flash Player 5 Usage Key SPACE Number Description Property constant associated with the key code value for the Spacebar 32 Example The follow...

Page 313: ...associated with the key code value for the Tab key 9 Example The following example creates a text field and displays the date in the text field when you press Tab this createTextField date_txt this ge...

Page 314: ...bar Give a sound in the library a linkage identifier of horn_id for this example var DISTANCE Number 10 var horn_sound Sound new Sound horn_sound attachSound horn_id var keyListener_obj Object new Obj...

Page 315: ...ree stored in the XML object The LoadVars class follows the same security restrictions as the XML class For information about using the LoadVars class and example code see Using the LoadVars class on...

Page 316: ...adVars new LoadVars LoadVars addRequestHeader Availability Flash Player 6 Usage my_lv addRequestHeader headerName String headerValue String Void my_lv addRequestHeader headerName_1 String headerValue_...

Page 317: ...ange ETag Host Last Modified Locations Max Forwards Proxy Authenticate Proxy Authorization Public Range Retry After Server TE Trailer Transfer Encoding Upgrade URI Vary Via Warning and WWW Authenticat...

Page 318: ...nd LoadVars sendAndLoad LoadVars decode Availability Flash Player 7 Usage my_lv decode variables String Void Parameters variables A URL encoded query string containing name value pairs Returns Nothing...

Page 319: ...ccessfully and how much data loads into the SWF file You must replace the URL parameter of the LoadVars load command so that the parameter refers to a valid text file using HTTP If you attempt to use...

Page 320: ...id not transmit an HTTP content length Example The following example uses a ProgressBar instance and a LoadVars object to download a text file When you test the file two things write to the log file w...

Page 321: ...ion Method downloads variables from the specified URL parses the variable data and places the resulting variables into my_lv Any properties in my_lv with the same names as downloaded variables are ove...

Page 322: ...on Property a Boolean value that indicates whether a load or sendAndLoad operation has completed undefined by default When a LoadVars load or LoadVars sendAndLoad operation is started the loaded prope...

Page 323: ...an be either undefined or a string that contains the URL encoded name value pairs downloaded from the server If the src parameter is undefined an error occurred while downloading the data from the ser...

Page 324: ...s invoked This handler is undefined by default This event handler is similar to XML onLoad LoadVars loaded LoadVars load LoadVars sendAndLoad LoadVars send Availability Flash Player 6 Usage my_lv send...

Page 325: ...he parent or top level frame use _parent or _top as the target parameter appear in a named frame use the frame s name as a string for the target parameter A successful send method call will always ope...

Page 326: ...n the same manner as LoadVars send Variables are downloaded into targetObject in the same manner as LoadVars load The value you pass for url must be in exactly the same domain For example a SWF file a...

Page 327: ...instantiates a new LoadVars object creates two properties and uses toString to return a string containing both properties in URL encoded format var my_lv LoadVars new LoadVars my_lv name Gary my_lv a...

Page 328: ...d LocalConnection connect commands specify the same connection name lc_name Code in the receiving SWF file this createTextField result_txt 1 10 10 100 22 result_txt border true var receiving_lc LocalC...

Page 329: ...ing_lc methodToExecute function param1 Number param2 Number result_txt text param1 param2 LocalConnection domain Returns a string representing the superdomain of the location of the current SWF file L...

Page 330: ...ethod from a sending LocalConnection object Flash expects the code you implement in this handler to return a Boolean value of true or false If the handler doesn t return true the request from the send...

Page 331: ...on of this method For example if you load a SWF file into my_mc you can then implement this method by checking whether the domain argument matches the domain of my_mc _url You must parse the domain ou...

Page 332: ...atus_ta text LocalConnection connected successfully break case error status_ta text LocalConnection encountered an error break sending_lc send _mylc sayHello name_ti text send_button addEventListener...

Page 333: ...other SWF files hosted using the HTTPS protocol This implementation maintains the integrity provided by the HTTPS protocol Using this method to override the default behavior is not recommended as it...

Page 334: ...to accept commands for example when you want to issue a LocalConnection connect command using the same connectionName parameter in another SWF file Example The following example closes a connection c...

Page 335: ...fore calling this method as shown in all the examples in this section By default Flash Player resolves connectionName into a value of superdomain connectionName where superdomain is the superdomain of...

Page 336: ...any domain will be accepted the SWF with the receiving LocalConnection object can be moved to another domain without altering any sending LocalConnection objects For more information see the discussi...

Page 337: ...to SWF 1 and passes two variables The first variable contains the MP3 file to stream and the second variable is the filename that you display in the Label component instance in SWF 1 play_btn onReleas...

Page 338: ...bjects that are located in the same domain you probably don t need to use this command Example In the following example a receiving SWF file accepts commands only from SWF files located in the same do...

Page 339: ...result replyMethod aResult n1 123 and n2 456 It then executes the following line of code this send mydomain com result aResult 123 456 The aResult method line 54 shows the value returned by aSum 579...

Page 340: ...tion Event handler invoked after a sending LocalConnection object tries to send a command to a receiving LocalConnection object If you want to respond to this event handler you must create a function...

Page 341: ...hether the SWF file connects to another local connection object called lc_name A TextInput component called name_ti a TextArea instance called status_ta and a Button instance called send_button are us...

Page 342: ...fault If you are implementing communication between different domains you need to define connectionName in both the sending and receiving LocalConnection objects in such a way that Flash does not add...

Page 343: ...LocalConnection send 343 See also LocalConnection allowDomain LocalConnection connect LocalConnection domain LocalConnection onStatus...

Page 344: ...lculate radian values before calling the method and then provide the calculated value as the parameter or you can provide the entire right side of the equation with the angle s measure in degrees in p...

Page 345: ...y Math random Returns a pseudo random number between 0 0 and 1 0 Math round Rounds to the nearest integer Math sin Computes a sine Math sqrt Computes a square root Math tan Computes a tangent Propert...

Page 346: ...ge Math acos x Number Number Parameters x A number from 1 0 to 1 0 Returns A number the arc cosine of the parameter x Description Method computes and returns the arc cosine of the number specified in...

Page 347: ...thods 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 atan tangent Number Num...

Page 348: ...point y x in radians when measured counterclockwise from a circle s x axis where 0 0 represents the center of the circle The return value is between positive pi and negative pi Example The following...

Page 349: ...measured in radians Returns A number from 1 0 to 1 0 Description Method computes and returns the cosine of the specified angle in radians To calculate a radian see Description on page 344 of the Math...

Page 350: ...a one year period var principal Number 100 var simpleInterest Number 100 var continuouslyCompoundedInterest Number 100 Math E principal trace Beginning principal principal trace Simple interest after...

Page 351: ...that Flash Player 5 supports Usage Math floor x Number Number Parameters x A number or expression Returns The integer that is both closest to and less than or equal to parameter x Description Method...

Page 352: ...as accurate as the non emulated math functions that Flash Player 5 supports Usage Math LN2 Number Description Constant a mathematical constant for the natural logarithm of 2 expressed as loge2 with a...

Page 353: ...alue of 1 442695040888963387 Example This example traces the value of Math LOG2E trace Math LOG2E Output 1 44269504088896 Math LOG10E Availability Flash Player 5 In Flash Player 4 the methods and prop...

Page 354: ...lue Example The following example displays Thu Dec 30 00 00 00 GMT 0700 2004 which is the larger of the evaluated expressions var date1 Date new Date 2004 11 25 var date2 Date new Date 2004 11 30 var...

Page 355: ...supports Usage Math PI Number Parameters None Returns Nothing Description Constant a mathematical constant for the ratio of the circumference of a circle to its diameter expressed as pi with a value o...

Page 356: ...y Example The following example uses Math pow and Math sqrt to calculate the length of a line this createEmptyMovieClip canvas_mc this getNextHighestDepth var mouseListener Object new Object mouseList...

Page 357: ...ndom number because it is not generated by a truly random natural phenomenon such as radioactive decay Example The following example returns a random number between two specified integers function ran...

Page 358: ...r Math sin 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...

Page 359: ...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 sqrt x Number...

Page 360: ...ath class are emulated using approximations and might not be as accurate as the non emulated math functions that Flash Player 5 supports Usage Math SQRT1_2 Number Description Constant a mathematical c...

Page 361: ...aws a circle using the mathematical constant pi the tangent of an angle and the Drawing API drawCircle this 100 100 50 function drawCircle mc MovieClip x Number y Number r Number Void mc lineStyle 2 0...

Page 362: ...ener newListener Object Parameters newListener An object Returns Nothing Method Description Mouse addListener Registers an object to receive onMouseDown onMouseMove onMouseWheel and onMouseUp notifica...

Page 363: ...d invoked Multiple objects can listen for mouse notifications If the listener newListener is already registered no change occurs See also Mouse onMouseDown Mouse onMouseMove Mouse onMouseUp Mouse onMo...

Page 364: ...ctangle whenever the user clicks drags and releases the mouse at runtime this createEmptyMovieClip canvas_mc this getNextHighestDepth var mouseListener Object new Object mouseListener onMouseDown func...

Page 365: ...ferent pieces of code to cooperate because multiple listeners can receive notification about a single event Example The following example uses the mouse pointer as a tool to draw lines using onMouseMo...

Page 366: ...operate because multiple listeners can receive notification about a single event Example The following example uses the mouse pointer as a tool to draw lines using onMouseMove and the Drawing API The...

Page 367: ...use the onMouseWheel listener you must create a listener object You can then define a function for onMouseWheel and use addListener to register the listener with the Mouse object Note Mouse wheel eve...

Page 368: ...and lets the user draw lines in the SWF file at runtime using the mouse pointer One button clears all of the lines from the SWF file The second button removes the mouse listener so the user cannot dr...

Page 369: ...er click function evt Object Mouse removeListener mouseListener evt target enabled false startDrawing_button enabled true stopDrawing_button addEventListener click stopDrawingListener var startDrawing...

Page 370: ...my_mc Give a movie clip a Linkage identifier of cursor_help_id and add the following ActionScript my_mc onRollOver function Mouse hide this attachMovie cursor_help_id cursor_mc this getNextHighestDept...

Page 371: ...w Number 1234 myNumber toString The following example assigns the value of the MIN_VALUE property to a variable declared without the use of the constructor var smallest Number Number MIN_VALUE Method...

Page 372: ...the properties of a Number object The new Number constructor is primarily used as a placeholder A Number object is not the same as the Number function that converts a parameter to a primitive value E...

Page 373: ...Example The following ActionScript writes the largest and smallest representable numbers to the log file trace Number MIN_VALUE Number MIN_VALUE trace Number MAX_VALUE Number MAX_VALUE This code logs...

Page 374: ...lt negResult output negResult Infinity Number POSITIVE_INFINITY Availability Flash Player 5 Usage Number POSITIVE_INFINITY Description Property specifies the IEEE 754 value representing positive infin...

Page 375: ...9 trace myNumber toString 2 output 1001 trace myNumber toString 8 output 11 The following example results in a hexadecimal value var r Number new Number 250 var g Number new Number 128 var b Number n...

Page 376: ...This parameter is optional Method Description Object addProperty Creates a getter setter property on an object Object registerClass Associates a movie clip symbol with an ActionScript object class Ob...

Page 377: ...object If you pass the value null for this parameter the property is read only Returns A Boolean value true if the property is successfully created false otherwise Description Method creates a getter...

Page 378: ...al method getTitle returns a read only value that is associated with the property bookname When a script retrieves the value of myBook bookcount the ActionScript interpreter automatically invokes myBo...

Page 379: ...g return Catcher in the Rye Book prototype addProperty bookcount Book prototype getQuantity Book prototype setQuantity Book prototype addProperty bookname Book prototype getTitle null var myBook new B...

Page 380: ...wever in the following example the Object constructor property converts primitive data types such as the string literal seen here into wrapper objects The instanceof operator does not perform any conv...

Page 381: ...is already registered to a class this method replaces it with the new registration Object __resolve Availability Flash Player 6 Usage myObject __resolve function name String your statements here Para...

Page 382: ...nctions Using __resolve redirects undefined method calls to a generic function named myFunction instantiate a new object var myObject Object new Object define a function for __resolve to call myObject...

Page 383: ...ved in the same way as other undefined properties Added code is in bold typeface instantiate a new object var myObject Object new Object define a function for __resolve to call myObject myFunction fun...

Page 384: ...this myFunction apply this arguments create a new object method and assign it the reference this name f return the reference to the function return f test __resolve using undefined method names with p...

Page 385: ...works var myNumber Number 5 trace typeof myNumber output number trace myNumber toString output 5 trace typeof myNumber toString output string The following example shows how to override toString in a...

Page 386: ...lse otherwise Description Method removes a watchpoint that Object watch created This method returns a value of true if the watchpoint is successfully removed false otherwise Example See the example fo...

Page 387: ...new Array object containing two simple elements In this case both toString and valueOf return the same value one two var myArray Array new Array one two trace myArray toString output one two trace myA...

Page 388: ...method Only a single watchpoint can be registered on a property Subsequent calls to Object watch on the same property replace the original watchpoint The Object watch method behaves similarly to the...

Page 389: ...vent handler passing as parameters the name of the property to watch speed a reference to the callback function speedWatcher the speedLimit of 55 as the userData parameter myObject watch speed speedWa...

Page 390: ...you can configure your document to dynamically format Flash content that is appropriate for the printer settings These user layout properties are read only and cannot be changed by Flash Player Method...

Page 391: ...s to addPage was successful You should always check for successful calls to start and addPage before calling send if pagesToPrint 0 my_pj send print page s clean up delete my_pj delete object You cann...

Page 392: ...the conversion rate depends on the screen and its resolution If the screen is set to display 72 pixels per inch for example one point is equal to one pixel If you omit the printArea parameter or if i...

Page 393: ...en t passed a value for printArea and the Flex screen is larger than the printable area the same type of clipping takes place If you want to scale a movie clip before you print it set its MovieClip _x...

Page 394: ...area 400 pixels wide and 400 pixels high of frame 3 of the dance_mc movie clip in bitmap format if my_pj addPage dance_mc xMin 0 xMax 400 yMin 0 yMax 400 printAsBitmap true 3 pageCount Starting at 0...

Page 395: ...ge failed you should check that calls to PrintJob addpage and PrintJob start were successful before calling PrintJob send var my_pj PrintJob new PrintJob if my_pj start if my_pj addPage this my_pj sen...

Page 396: ...alog box any subsequent calls to PrintJob addPage and PrintJob send will fail However if you test for this return value and don t send PrintJob addPage commands as a result you should still delete the...

Page 397: ...an 8 5 x 11 portrait page pageAdded my_pj addPage this xMin 0 xMax 600 yMin 0 yMax 800 else my_pj orientation is landscape Now the printArea measurements are appropriate for an 11 x 8 5 landscape page...

Page 398: ...d objects as large as 100K When you try to save a larger object Flash Player shows the Local Storage dialog box which lets the user allow or deny local storage for the domain that is requesting access...

Page 399: ...the SharedObject class Property summary for the SharedObject class Event handler summary for the SharedObject class Constructor for the SharedObject class For information on creating local shared obj...

Page 400: ..._so clear trace after my_so clear for var prop in my_so data trace t prop This ActionScript writes the following message to the log file before my_so clear name after my_so clear SharedObject data Ava...

Page 401: ...e To create private values for a shared object values that are available only to the client instance while the object is in use and are not stored with the object when it is closed create properties t...

Page 402: ...o a file when the shared object session ends that is when the SWF file is closed when the shared object is garbage collected because it no longer has any references to it or when you call SharedObject...

Page 403: ...Player 6 Usage SharedObject getLocal objectName String localPath String SharedObject Note The correct syntax is SharedObject getLocal To assign the object to a variable use syntax like myLocal_so Shar...

Page 404: ...er move the original SWF file to another location then not even that SWF file will be able to access the data already stored in the shared object You can reduce the likelihood that you will inadverten...

Page 405: ...red object by stepping through each of its data properties the more data properties the object has the longer it takes to estimate its size For this reason estimating object size can have significant...

Page 406: ...alled System onStatus If onStatus is invoked for a particular object and no function is assigned to respond to it Flash processes a function assigned to System onStatus if it exists The following even...

Page 407: ...entUserName my_so onStatus function infoObject Object status_txt htmlText textformat tabStops 50 for var i in infoObject status_txt htmlText b i b t infoObject i status_txt htmlText textformat var flu...

Page 408: ...length property with a string literal Do not confuse a string literal with a String object In the following example the first line of code creates the string literal first_string and the second line...

Page 409: ...g class unless you have a good reason to use a String object rather than a string literal See also String string delimiter String charAt Availability Flash Player 5 Usage my_str charAt index Number St...

Page 410: ...thod is called on the first letter of the string Chris var my_str String Chris var firstChar_str String my_str charAt 0 trace firstChar_str output C See also String charCodeAt String charCodeAt Availa...

Page 411: ...ated Returns A string Description Method combines the value of the String object with the parameters and returns the newly formed string the original value my_str is unchanged Example The following ex...

Page 412: ...tr to search for the substring Returns A number the position of the first occurrence of the specified substring or 1 Description Method searches the string and returns the position of the first occurr...

Page 413: ...escription Method searches the string from right to left and returns the index of the last occurrence of substring found before startIndex within the calling string This index is zero based meaning th...

Page 414: ...is x length 1 Example The following example creates a new String object and uses String length to count the number of characters var my_str String Hello world trace my_str length output 12 The follow...

Page 415: ...f the end parameter is not specified the end of the substring is the end of the string If the character indexed by start is the same as or to the right of the character indexed by end the method retur...

Page 416: ...s of my_str Description Method splits a String object into substrings by breaking it wherever the specified delimiter parameter occurs and returns the substrings in an array If you use an empty string...

Page 417: ...th A number the number of characters in the substring being created If length is not specified the substring includes all the characters from the start to the end of the string Returns A string a subs...

Page 418: ...alue 0 is used Returns String a substring of the specified string Description Method returns a string comprising the characters between the points specified by the start and end parameters If the end...

Page 419: ...of that string using toLowerCase to convert all uppercase characters to lowercase characters var upperCase String LOREM IPSUM DOLOR var lowerCase String upperCase toLowerCase trace upperCase upperCase...

Page 420: ...se 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 lore...

Page 421: ...en accessing local settings such as camera or microphone access permissions or locally persistent data shared objects The default value is true for files published for Flash Player 7 or later and fals...

Page 422: ...e you want to store settings and data If you want to change this property from its default value do so near the beginning of your script The property can t be changed after any activity that requires...

Page 423: ...when a class specific onStatus function does not exist Create generic function System onStatus function genericError Object Your script would do something more meaningful here trace An error has occur...

Page 424: ...to the out_txt field this createTextField in_txt this getNextHighestDepth 10 10 160 120 in_txt multiline true in_txt border true in_txt text lorum ipsum this createTextField out_txt this getNextHighes...

Page 425: ...amera get Microphone get SharedObject getLocal System useCodepage Availability Flash Player 6 Usage System useCodepage Boolean Description Property a Boolean value that tells Flash Player whether to u...

Page 426: ...operating system If you set System useCodepage to true remember that the traditional code page of the operating system running the player must include the characters used in your external text file in...

Page 427: ...EB 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 proper...

Page 428: ...ning L System capabilities localFileReadDisable Specifies whether the player will attempt to read anything including the first SWF file the player launches with from the user s hard disk LFD System ca...

Page 429: ...lso Camera get Microphone get System showSettings System capabilities hasAccessibility Availability Flash Player 6 Usage System capabilities hasAccessibility Boolean Description Read only property a B...

Page 430: ...olean value that is true if the player can encode an audio stream such as that coming from a microphone false otherwise The server string is AE Example The following example traces the value of this r...

Page 431: ...r65 Usage System capabilities hasPrinting Boolean Description Read only property a Boolean value that is true if the player is running on a system that supports printing false otherwise The server st...

Page 432: ...rver false otherwise The server string is SP Example The following example traces the value of this read only property trace System capabilities hasScreenPlayback System capabilities hasStreamingAudio...

Page 433: ...alue that is true if the player can encode a video stream such as that coming from a web camera false otherwise The server string is VE Example The following example traces the value of this read only...

Page 434: ...ish systems no longer includes the country code In Flash Player 6 all English systems return the language code and the two letter country code subtag en US In Flash Player 7 English systems return onl...

Page 435: ...t Flash Player launches with from the user s hard disk For example attempts to read a file on the user s hard disk using XML load or LoadVars load will fail if this property is set to true Reading run...

Page 436: ...current operating system The os property can return the following strings Windows XP Windows 2000 Windows NT Windows 98 ME Windows 95 Windows CE available only in Flash Player SDK not in the desktop v...

Page 437: ...net Explorer The server string is PT Example The following example traces the value of this read only property trace System capabilities playerType System capabilities screenColor Availability Flash P...

Page 438: ...the maximum horizontal resolution of the screen The server string is R which returns both the width and height of the screen Example The following example traces the value of this read only property...

Page 439: ...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 capabi...

Page 440: ...tified 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 In files playing in Flash Player 7 or later the parameter s pa...

Page 441: ...alue until the file is completely loaded The best way to determine when a child SWF finishes loading is to use MovieClipLoader onLoadComplete The opposite situation can also occur that is you might cr...

Page 442: ...h access in SWF files published for Flash Player 7 or later Note It is sometimes necessary to call System security allowInsecureDomain with an argument that exactly matches the domain of the SWF file...

Page 443: ...com sub dir deep vars2 txt allowed loadVariables http foo com elsewhere vars3 txt not allowed You can load any number of policy files using loadPolicyFile When considering a request that requires a p...

Page 444: ...icy allow access from domain to ports 507 allow access from domain foo com to ports 507 516 allow access from domain bar com to ports 516 523 allow access from domain www foo com to ports 507 516 523...

Page 445: ...XML class Method Description XML addRequestHeader Adds or changes HTTP headers for POST operations XML appendChild Appends a node to the end of the specified object s child list XML cloneNode Clones t...

Page 446: ...XML nodeType The type of the specified node XML element or text node XML nodeValue The text of the specified node if the node is a text node XML parentNode Read only references the parent node of the...

Page 447: ...new empty XML object var my_xml XML new XML The following example creates an XML object by parsing the XML text specified in the source parameter and populates the newly created XML object with the re...

Page 448: ...xy Authenticate Proxy Authorization Public Range Retry After Server TE Trailer Transfer Encoding Upgrade URI Vary Via Warning and WWW Authenticate Example The following example adds a custom HTTP head...

Page 449: ...endChild method to the XML document named doc1 Shows how to move a node using the appendChild method by moving the root node from doc1 to doc2 Clones the root node from doc2 and appends it to doc1 Cre...

Page 450: ...that attribute s value by using the color as the key index as the following code shows var myColor String doc firstChild attributes color Example The following example writes the names of the XML attr...

Page 451: ...eateElement rootNode create three child nodes var oldest XMLNode doc createElement oldest var middle XMLNode doc createElement middle var youngest XMLNode doc createElement youngest add the rootNode a...

Page 452: ...lastChild are also null Example The following example shows how to use the XML cloneNode method to create a copy of a node create a new XML document var doc XML new XML create a root node var rootNod...

Page 453: ...XML send or XML sendAndLoad method The default is application x www form urlencoded which is the standard MIME content type used for most HTML forms Example The following example creates a new XML doc...

Page 454: ...reateTextNode method are the constructor methods for creating nodes for an XML object Example The following example creates three XML nodes using the createElement method create an XML document var do...

Page 455: ...sting XML nodes create an XML document var doc XML new XML create three XML nodes using createElement var element1 XMLNode doc createElement element1 var element2 XMLNode doc createElement element2 va...

Page 456: ...on the XML docTypeDecl property is set to undefined The XML toString method outputs the contents of XML docTypeDecl immediately after the XML declaration stored in XML xmlDecl and before any other tex...

Page 457: ...ootNode as the root of the XML document tree doc appendChild rootNode add each of the child nodes as children of rootNode rootNode appendChild oldest rootNode appendChild middle rootNode appendChild y...

Page 458: ...is example will not work properly because in test movie mode Flash Player loads local files in their entirety create a new XML document var doc XML new XML var checkProgress function xmlObj XML var by...

Page 459: ...e creates a new XML packet If the root node has child nodes the code loops over each child node to display the name and value of the node Add the following ActionScript to your FLA or AS file var my_x...

Page 460: ...ing code shows XML prototype ignoreWhite true Example The following example loads an XML file with a text node that contains only white space the foyer tag comprises fourteen space characters To run t...

Page 461: ...ge my_xml insertBefore childNode XMLNode beforeNode XMLNode Void Parameters childNode The XMLNode object to be inserted beforeNode The XMLNode object before the insertion point for the childNode Retur...

Page 462: ...with the last item in the node s child list and ending with the first child of the node s child list create a new XML document var doc XML new XML create a root node var rootNode XMLNode doc createEl...

Page 463: ...Before XML removeNode XMLNode class XML load Availability Flash Player 5 behavior changed in Flash Player 7 Usage my_xml load url String Void Parameters url A string that represents the URL where the...

Page 464: ...ect previously contained any XML trees they are discarded You can define a custom function that executes when the onLoad event handler of the XML object is invoked Example The following simple example...

Page 465: ...extSibling Availability Flash Player 5 Usage my_xml nextSibling XMLNode Description Read only property an XMLNode value that references the next sibling in the parent node s child list This property i...

Page 466: ...ode doc createElement rootNode place the new node into the XML tree doc appendChild myNode create an XML text node using createTextNode var myTextNode XMLNode doc createTextNode textNode place the new...

Page 467: ...e nodeType is a numeric value from the NodeType enumeration in the W3C DOM Level 1 recommendation www w3 org TR 1998 REC DOM Level 1 19981001 level one core html The following table lists the values I...

Page 468: ...ce the new node into the XML tree myNode appendChild myTextNode trace myNode nodeType trace myTextNode nodeType output 1 3 See also XML nodeValue XML nodeValue Availability Flash Player 5 Usage my_xml...

Page 469: ...y and firstChild nodeValue When you use firstChild to display contents of the node it maintains the amp entity However when you explicitly use nodeValue it converts to the ampersand character var my_x...

Page 470: ...ing that contains XML text downloaded from the server unless an error occurs during the download in which case the src parameter is undefined By default the XML onData event handler invokes XML onLoad...

Page 471: ...he following example includes ActionScript for a simple e commerce storefront application The sendAndLoad method transmits an XML element that contains the user s name and password and uses an XML onL...

Page 472: ...n first child is the login node var rootNode XMLNode my_xml firstChild first child of the root is the username node var targetNode XMLNode rootNode firstChild trace the parent node of targetNode nodeN...

Page 473: ...tributes name output California XML previousSibling Availability Flash Player 5 Usage my_xml previousSibling XMLNode Description Read only property an XMLNode value that references the previous siblin...

Page 474: ...fied XML object and its descendant nodes var xml_str String state name California city San Francisco city state var my_xml XML new XML xml_str var cityNode XMLNode my_xml firstChild firstChild trace b...

Page 475: ...ET method Example The following example defines an XML packet and sets the content type for the XML object The data is then sent to a server and shows a result in a browser window var my_xml XML new X...

Page 476: ...ng the loaded property is set to true if the data successfully loaded and the onLoad event handler is invoked The XML data is not parsed until it is completely downloaded If the XML object previously...

Page 477: ...s not properly terminated 9 A start tag was not matched with an end tag 10 An end tag was encountered without a matching start tag Example The following example loads an XML packet into a SWF file A s...

Page 478: ...with an end tag break case 10 errorMessage An end tag was encountered without a matching start tag break default errorMessage An unknown error has occurred break trace status my_xml status errorMessag...

Page 479: ...is parsed into an XML object this property is set to the text of the document s XML declaration This property is set using a string representation of the XML declaration not an XML node object If no X...

Page 480: ..._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 toS...

Page 481: ...entries See also XML class Property method or collection Corresponding XML class entry appendChild XML appendChild attributes XML attributes childNodes XML childNodes cloneNode XML cloneNode firstChi...

Page 482: ...TCP port numbers greater than or equal to 1024 One consequence of this restriction is that the server daemons that communicate with the XMLSocket object must also be assigned to port numbers greater...

Page 483: ...n XMLSocket object var socket XMLSocket new XMLSocket XMLSocket close Availability Flash Player 5 Usage myXMLSocket close Void Method Description XMLSocket close Closes an open socket connection XMLSo...

Page 484: ...ified DNS domain name or an IP address in the form aaa bbb ccc ddd You can also specify null to connect to the host server on which the SWF file resides If the SWF file issuing this call is running in...

Page 485: ...file that is being accessed For more information see Applying Flex Security in Developing Flex Applications When load is executed the XML object property loaded is set to false When the XML data fini...

Page 486: ...ou must assign a function containing custom actions Example The following example executes a trace statement if an open connection is closed by the server var socket XMLSocket new XMLSocket socket con...

Page 487: ...ption Event handler invoked when a message has been downloaded from the server terminated by a zero 0 byte You can override XMLSocket onData to intercept the data sent by the server without parsing it...

Page 488: ...was established if this is the first message received Each batch of parsed XML is treated as a single XML document and passed to the onXML method The default implementation of this method performs no...

Page 489: ...tely but the data may be transmitted at a later time The XMLSocket send method does not return a value indicating whether the data was successfully transmitted If the myXMLSocket object is not connect...

Page 490: ...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 o...

Page 491: ...he following example the playMP3 function is defined The TextField object list_txt is created and set so HTML text can be rendered The text Track 1 and Track 2 are links inside the text field The play...

Page 492: ...mary for the Camera class Property summary for the Camera class Method Description Camera get Returns a default or specified Camera object or null if the camera is not available Camera setMode Sets as...

Page 493: ...therwise it is undefined Camera motionLevel The amount of motion required to invoke Camera onActivity true Camera motionTimeOut The number of milliseconds between the time when the camera stops detect...

Page 494: ...andwidth Availability Flash Player 6 Usage active_cam bandwidth Number Description Read only property an integer that specifies the maximum amount of bandwidth the current outgoing video feed can use...

Page 495: ...roperty cannot be set however you can use the Camera setMode method to set a related property Camera fps which specifies the maximum frame rate at which you would like the camera to capture data Examp...

Page 496: ...rate in frames per second that the camera captures data using the currentFps property var my_video Video var fps_pb mx controls ProgressBar var my_cam Camera Camera get my_video attachVideo my_cam th...

Page 497: ...to the default camera By means of the Camera settings panel discussed later in this section the user can specify the default camera Flash should use If you pass a value for index you might be trying...

Page 498: ...he following example lets you select an active camera to use from a ComboBox instance The current active camera is displayed in a Label instance var my_cam Camera Camera get var my_video Video my_vide...

Page 499: ...flected in the array returned by Camera names Example The following example displays an array of cameras in a text field that is created at runtime and tells you which camera you are currently using v...

Page 500: ...on 3 var motionLevel_lbl mx controls Label configure the NumericStepper component instance var motionLevel_nstep mx controls NumericStepper motionLevel_nstep minimum 0 motionLevel_nstep maximum 100 mo...

Page 501: ...cam motionTimeOut Number Description Read only property the number of milliseconds between the time the camera stops detecting motion and the time Camera onActivity false is invoked The default value...

Page 502: ...ly property a Boolean value that specifies whether the user has denied access to the camera true or allowed access false in the Flash Player Privacy Settings panel When this value changes Camera onSta...

Page 503: ...lability Flash Player 6 Usage Camera names Array Note The correct syntax is Camera names To assign the return value to a variable use syntax like cam_array Camera names To determine the name of the cu...

Page 504: ...Parameters activity A Boolean value set to true when the camera starts detecting motion false when it stops Returns Nothing Description Event handler invoked when the camera starts or stops detecting...

Page 505: ...e and this handler is invoked with an information object whose code property is Camera Unmuted and whose level property is Status If the user denies access the Camera muted property is set to true and...

Page 506: ...from 1 lowest quality maximum compression to 100 highest quality no compression The default value is 0 which means that picture quality can vary as needed to avoid exceeding available bandwidth Examp...

Page 507: ...ve mode that best meets the specified requirements If the camera does not have a native mode that matches all the parameters you pass Flash selects a capture mode that most closely synthesizes the req...

Page 508: ...pecifies how many milliseconds must elapse without activity before Flash considers activity to have stopped and invokes the Camera onActivity false event handler The default value is 2000 2 seconds Re...

Page 509: ...idth When an audio stream is considered silent no audio data is sent Instead a single message is sent indicating that silence has started Camera setMotionLevel is designed to detect motion and does no...

Page 510: ...ecedence pass a value for bandwidth and 0 for frameQuality Flash will transmit video at the highest quality possible within the specified bandwidth If necessary Flash will reduce picture quality to av...

Page 511: ...ode displays the current width height and FPS of a video instance in a Label component instance on the Stage var my_cam Camera Camera get var my_video Video my_video attachVideo my_cam var dimensions_...

Page 512: ...ription Constructor creates a Color object for the movie clip specified by the target_mc parameter You can then use the methods of that Color object to change the color of the entire target movie clip...

Page 513: ...value to a hexadecimal string and assigns it to the myValue variable var my_color Color new Color my_mc set the color my_color setRGB 0xff9933 var myValue String my_color getRGB toString 16 trace the...

Page 514: ...Color setRGB Availability Flash Player 5 Usage my_color setRGB 0xRRGGBB Number Void Parameters 0xRRGGBB The hexadecimal or RGB color to be set RR GG and BB each consist of two hexadecimal digits that...

Page 515: ...a color transform object correspond to the settings in the Advanced Effect dialog box and are defined as follows ra is the percentage for the red component 100 to 100 rb is the offset for the red com...

Page 516: ...the colorTransformObject to a Color object Create a color object called my_color for the target my_mc var my_color Color new Color my_mc Create a color transform object called myColorTransform using...

Page 517: ...click in Flash Player the edit menu which appears when you right click over a selectable or editable text field and an error menu which appears when a SWF file has failed to load into Flash Player On...

Page 518: ...or based on the type of object movie clip text field or button or the Timeline that the user right clicks or Control clicks For an example of creating an event handler see ContextMenu onSelect Exampl...

Page 519: ...on Property an object that has the following Boolean properties zoom quality play loop rewind forward_back and print Setting these variables to false removes the corresponding menu items from the spec...

Page 520: ...uilt in menu items are hidden and adds a menu item with the text Save It then creates a copy of my_cm and assigns it to the variable clone_cm which inherits all the properties of the original menu var...

Page 521: ...extMenuItem class entry Example The following example creates a new custom menu item called menuItem_cm with a caption of Send e mail and a callback handler named emailHandler The new menu item is the...

Page 522: ...items are hidden except for Print The menu object is attached to the current Timeline var my_cm ContextMenu new ContextMenu my_cm hideBuiltInItems my_cm builtInItems print true this menu my_cm Context...

Page 523: ...ontext 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...

Page 524: ...acters newlines and other white space characters are ignored No item can be more than 100 characters long Items that are identical to any built in menu item or to another custom item are ignored wheth...

Page 525: ...value is true This parameter is optional visible A Boolean value that indicates whether the menu item is visible or invisible The default value is true This parameter is optional Returns A reference...

Page 526: ...tMenuItem copy Availability Flash Player 7 Usage menuItem_cmi copy ContextMenuItem Returns A ContextMenuItem object Description Method creates and returns a copy of the specified ContextMenuItem objec...

Page 527: ...Stop is selected the number of milliseconds that have elapsed since the SWF file started is traced The Start menu item is re enabled and the Stop menu item is disabled var my_cm ContextMenu new Contex...

Page 528: ...es two parameters obj a reference to the object under the mouse when the user invoked the Flash Player context menu and item a reference to the ContextMenuItem object that represents the selected menu...

Page 529: ...array Finally the menu is attached to the current Timeline of the SWF file var my_cm ContextMenu new ContextMenu var open_cmi ContextMenuItem new ContextMenuItem Open itemHandler var save_cmi Context...

Page 530: ...ble and the Stop menu item is made invisible var my_cm ContextMenu new ContextMenu var startMenuItem ContextMenuItem new ContextMenuItem Start startHandler startMenuItem visible true my_cm customItems...

Page 531: ...the original movie clip are not copied into the duplicate movie clip Use the removeMovieClip function or method to delete a movie clip instance created with duplicateMovieClip Example In the followin...

Page 532: ...ces Note If you use a component then FocusManager overrides Flash Player s focus handling including use of this global property Example The following example demonstrates how to hide the yellow rectan...

Page 533: ...turns The value of the specified property Description Function returns the value of the specified property for the movie clip my_mc Example The following example creates a new movie clip someClip_mc a...

Page 534: ...Microphone class Method Description Microphone get Returns a default or specified Microphone object or null if the microphone is not available Microphone setGain Specifies the amount by which the mic...

Page 535: ...ity level of the current microphone in a ProgressBar instance called activityLevel_pb var activityLevel_pb mx controls ProgressBar activityLevel_pb mode manual Microphone names Class property an array...

Page 536: ...lability Flash Player 6 Usage active_mic gain Number Description Read only property the amount by which the microphone boosts the signal Valid values are 0 to 100 The default value is 50 Example The f...

Page 537: ...e the same microphone Thus if your script contains the lines mic1 Microphone get and mic2 Microphone get both mic1 and mic2 reference the same default microphone In general you shouldn t pass a value...

Page 538: ...user specify the default microphone and then captures audio and plays it back locally To avoid feedback you may want to test this code while wearing headphones this createEmptyMovieClip sound_mc this...

Page 539: ...age active_mic muted Boolean Description Read only property a Boolean value that specifies whether the user has denied access to the microphone true or allowed access false When this value changes Mic...

Page 540: ...e current microphone use active_mic name Description Read only class property retrieves an array of strings reflecting the names of all available sound capture devices without displaying the Flash Pla...

Page 541: ...Description Event handler invoked when the microphone starts or stops detecting sound If you want to respond to this event handler you must create a function to process its activity value To specify t...

Page 542: ...access to the microphone If you want to respond to this event handler you must create a function to process the information object generated by the microphone When a SWF file tries to access the micr...

Page 543: ...lip sound_mc this getNextHighestDepth var active_mic Microphone Microphone get sound_mc attachAudio active_mic active_mic onStatus function infoObj Object status_txt _visible active_mic muted muted_tx...

Page 544: ...i break function changeRate active_mic setRate rate_cb selectedItem rate_lbl text Current rate active_mic rate kHz rate_cb addEventListener change changeRate rate_lbl text Current rate active_mic rat...

Page 545: ...b setProgress active_mic gain 100 gain_nstep value active_mic gain function changeGain active_mic setGain gain_nstep value gain_pb setProgress active_mic gain 100 gain_nstep addEventListener change ch...

Page 546: ...rate_array rate_cb labelFunction function item Object return item kHz for var i 0 i rate_array length i if rate_cb getItemAt i active_mic rate rate_cb selectedIndex i break function changeRate active...

Page 547: ...lence value This method is similar in purpose to Camera setMotionLevel both methods are used to specify when the onActivity event handler should be invoked However these methods have a significantly d...

Page 548: ...e example for Camera setMotionLevel See also Microphone activityLevel Microphone onActivity Microphone setGain Microphone silenceLevel Microphone silenceTimeOut Microphone setUseEchoSuppression Availa...

Page 549: ...sound_mc attachAudio active_mic activityLevel_pb mode manual activityLevel_pb label Activity Level 3 useEchoSuppression_ch selected active_mic useEchoSuppression this onEnterFrame function activityLe...

Page 550: ...nstepListener this onEnterFrame function silenceLevel_pb setProgress active_mic activityLevel 100 active_mic onActivity function active Boolean if active silenceLevel_pb indeterminate false silenceLe...

Page 551: ...nceLevel_pb label Activity level 3 silenceLevel_pb mode manual silenceTimeOut_nstep minimum 0 silenceTimeOut_nstep maximum 10 silenceTimeOut_nstep value active_mic silenceTimeOut 1000 var nstepListene...

Page 552: ...dio stream var useEchoSuppression_ch mx controls CheckBox var activityLevel_pb mx controls ProgressBar this createEmptyMovieClip sound_mc this getNextHighestDepth var active_mic Microphone Microphone...

Page 553: ...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 You must run this example as a Flash panel beca...

Page 554: ...lip Creates an empty movie clip MovieClip createTextField Creates an empty text field MovieClip duplicateMovieClip Duplicates the specified movie clip MovieClip getBounds Returns the minimum and maxim...

Page 555: ...nds the playhead to the previous frame of the movie clip MovieClip removeMovieClip Removes the movie clip from the Timeline if it was created with duplicateMovieClip MovieClip duplicateMovieClip or Mo...

Page 556: ...MovieClip _framesloaded Read only the number of frames that have been loaded from a streaming SWF file MovieClip _height The height of a movie clip instance in pixels MovieClip hitArea A reference to...

Page 557: ...e percentage that the movie clip is scaled horizontally MovieClip _y The y coordinate of a movie clip instance MovieClip _ymouse Read only the y coordinate of the mouse pointer within a movie clip ins...

Page 558: ...age_mc holder_mc getNextHighestDepth MovieClip onLoad Invoked when the movie clip is instantiated and appears in the Timeline MovieClip onMouseDown Invoked when the left mouse button is pressed MovieC...

Page 559: ...udio source to be played To stop playing the audio source pass false for source You can extend the methods and event handlers of the MovieClip class by creating a subclass Example The following code c...

Page 560: ...Video attachVideo MovieClip attachMovie Availability Flash Player 5 Usage my_mc attachMovie idName String newName String depth Number initObject Object MovieClip Parameters idName The linkage name of...

Page 561: ...ieClip MovieClip beginFill Availability Flash Player 6 Usage my_mc beginFill rgb Number alpha Number Void Parameter rgb A hex color value for example red is 0xFF0000 blue is 0x0000FF and so on If this...

Page 562: ...blue is 0x0000FF and so on alphas An array of alpha values for the corresponding colors in the colors array valid values are 0 100 If the value is less than 0 Flash uses 0 If the value is greater than...

Page 563: ...clip for the upper left corner of the gradient y is the vertical position relative to the registration point of the parent clip for the upper left corner of the gradient w is the width of the gradien...

Page 564: ...g conditions exist The number of items in the colors alphas and ratios parameters are not equal The fillType parameter is not linear or radial Any of the fields in the object for the matrix parameter...

Page 565: ...ers None Returns Nothing Description Method removes all the graphics created during runtime using the movie clip draw methods including line styles specified with MovieClip lineStyle Shapes and lines...

Page 566: ...clip Returns A reference to the newly created movie clip Description Method creates an empty movie clip as a child of an existing movie clip This method behaves similarly to the attachMovie method but...

Page 567: ...depth parameter determines the new text field s z order position in the movie clip Each position in the z order can contain only one object If you create a new text field on a depth that already has a...

Page 568: ...can extend the methods and event handlers of the MovieClip class by creating a subclass Example The following example creates a text field with a width of 300 a height of 100 an x coordinate of 100 a...

Page 569: ...he parent movie clip anchorX An integer that specifies the horizontal position of the next anchor point relative to the registration point of the parent movie clip anchorY An integer that specifies th...

Page 570: ...e Math class this createEmptyMovieClip circle2_mc 2 circle2_mc lineStyle 0 0x000000 drawCircle circle2_mc 10 10 100 function drawCircle mc MovieClip x Number y Number r Number Void mc moveTo x r y mc...

Page 571: ...owing example evaluates the _droptarget property of the garbage_mc movie clip instance and uses eval to convert it from slash syntax to a dot syntax reference The garbage_mc reference is then compared...

Page 572: ...s start playing at Frame 1 no matter what frame the original movie clip is on when the duplicateMovieClip method is called Variables in the parent movie clip are not copied into the duplicate movie cl...

Page 573: ...led is set to false the object is not included in automatic tab ordering Example The following example disables the circle_mc movie clip when the user clicks it circle_mc onRelease function trace disa...

Page 574: ...ilability Flash Player 6 Usage my_mc _focusrect Boolean Description Property a Boolean value that specifies whether a movie clip has a yellow rectangle around it when it has keyboard focus This proper...

Page 575: ...his movie clip in the browser by pressing Enter or the Spacebar when _focusrect is disabled See Also _focusrect MovieClip _framesloaded Availability Flash Player 4 Usage my_mc _framesloaded Number Des...

Page 576: ...spectively You can extend the methods and event handlers of the MovieClip class by creating a subclass Example The following example creates a movie clip called square_mc The code draws a square for t...

Page 577: ...extend the methods and event handlers of the MovieClip class by creating a subclass See also MovieClip getBytesTotal MovieClip getBytesTotal Availability Flash Player 5 Usage my_mc getBytesTotal Numb...

Page 578: ...h of all movie clip instances on the Stage for var i in this if typeof this i movieclip trace movie clip this i _name is at depth this i getDepth See also MovieClip getInstanceAtDepth MovieClip getNex...

Page 579: ...Clip getNextHighestDepth Availability Flash Player 7 Usage my_mc getNextHighestDepth Number Parameters None Returns An integer that reflects the next available depth index that would render above all...

Page 580: ...lash Player version that was targeted when the SWF file loaded into my_mc was published Description Method returns an integer that indicates the Flash Player version for which my_mc was published If m...

Page 581: ...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...

Page 582: ...se one of the following reserved target names _self specifies the current frame in the current window _blank specifies a new window _parent specifies the parent of the current frame and _top specifies...

Page 583: ...lobalToLocal Availability Flash Player 5 Usage my_mc globalToLocal point Object Void Parameters point The name or identifier of an object created with the generic Object class The object specifies the...

Page 584: ...rmat Mouse addListener mouseListener See also MovieClip getBounds MovieClip localToGlobal MovieClip gotoAndPlay Availability Flash Player 5 Usage my_mc gotoAndPlay frame Object Void Parameters frame A...

Page 585: ...tes 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...

Page 586: ...uare_mc movie clip traces that it has been clicked square_mc hitArea circle_mc square_mc onRelease function trace hit this _name You can also set the circle_mc movie clip visible property to false to...

Page 587: ...le The following example uses hitTest to determine if the movie clip circle_mc overlaps or intersects the movie clip square_mc when the user releases the mouse button square_mc onPress function this s...

Page 588: ...You can extend the methods and event handlers of the MovieClip class by creating a subclass Example The following code draws a triangle with a 5 pixel solid magenta line with no fill this createEmptyM...

Page 589: ...0xFF00FF 100 triangle_mc moveTo 200 200 triangle_mc lineTo 300 300 triangle_mc lineTo 100 300 triangle_mc lineTo 200 200 triangle_mc endFill See also MovieClip beginFill MovieClip createEmptyMovieClip...

Page 590: ...f you attach an event handler to a button using on or if you create a dynamic handler using an event handler method such as MovieClip onPress and then you call loadMovie the event handler does not rem...

Page 591: ...rameter The GET method appends the variables to the end of the URL and is used for small numbers of variables The POST method sends the variables in a separate HTTP header and is used for long strings...

Page 592: ...is reflected after you click and drag the instance this createTextField point_txt this getNextHighestDepth 0 0 100 22 var mouseListener Object new Object mouseListener onMouseMove function var point O...

Page 593: ...ie set the MovieClip _lockroot property to true in the loader movie as shown in the following code If you don t set _lockroot to true in the loader movie the loader has access only to its own library...

Page 594: ..._mc _level0 nolockroot_mc lockroot_mc _level0 lockroot_mc from nolockroot swf myVar 1 i lockroot_mc dumpRoot type Function version WIN 7 0 19 0 nolockroot_mc _level0 nolockroot_mc lockroot_mc _level0...

Page 595: ...eled View Image in Browser that has an associated function named viewImage var menu_cm ContextMenu new ContextMenu menu_cm customItems push new ContextMenuItem View Image in Browser viewImage this cre...

Page 596: ...wing position is not changed You can extend the methods and event handlers of the MovieClip class by creating a subclass Example The following example draws a triangle with a 5 pixel solid magenta lin...

Page 597: ...etMCInfo target_mc MovieClip obj Object trace You clicked on the movie clip target_mc _name trace t width target_mc _width height target_mc _height trace for var i in this if typeof this i movieclip t...

Page 598: ...le illustrates the correct use of MovieClip onData and onClipEvent data symbol_mc is a movie clip symbol in the library It is linked to the MovieClip class The following function is triggered for each...

Page 599: ...the event handler is invoked You can define the function on the Timeline or in a class file that extends the MovieClip class or is linked to a symbol in the library Example The following example defi...

Page 600: ...ragOut MovieClip onEnterFrame Availability Flash Player 6 Usage my_mc onEnterFrame function your statements here Parameters None Returns Nothing Description Event handler invoked repeatedly at the fra...

Page 601: ...must be given focus This can be done either by using Selection setFocus or by setting the Tab key to navigate to the clip If Selection setFocus is used the path for the movie clip must be passed to Se...

Page 602: ...in the library The onKeyUp event handler works only if the movie clip has input focus enabled and set First the MovieClip focusEnabled property must be set to true for the movie clip Then the clip mu...

Page 603: ...event handler is invoked You can define the function on the Timeline or in a class file that extends the MovieClip class or is linked to a symbol in the library Example The following example displays...

Page 604: ...g example illustrates one way to use MovieClip onLoad with setInterval to check that a file has loaded into a movie clip that s created at runtime this createEmptyMovieClip tester_mc 1 tester_mc loadM...

Page 605: ...o a symbol in the library Example The following example defines a function for the onMouseDown method that writes the results of a trace method to the log file my_mc onMouseDown function trace onMouse...

Page 606: ...ion Event handler invoked when the mouse button is released 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 th...

Page 607: ...to the log file my_mc onPress function trace onPress called MovieClip onRelease Availability Flash Player 6 Usage my_mc onRelease function your statements here Parameters None Returns Nothing Descrip...

Page 608: ...t 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 libr...

Page 609: ..._mc onRollOut function trace onRollOut called MovieClip onRollOver Availability Flash Player 6 Usage my_mc onRollOver function your statements here Parameters None Returns Nothing Description Event ha...

Page 610: ...dFocus contains a null value You must define a function that executes when the event handler in invoked You can define the function on the Timeline or in a class file that extends the MovieClip class...

Page 611: ...linked to a symbol in the library Example The following example defines a function for the MovieClip onUnload method that writes the results of a trace method to the log file my_mc onUnload function t...

Page 612: ...targetPath TextField _parent MovieClip play Availability Flash Player 5 Usage my_mc play Void Parameters None Returns Nothing Description Method moves the playhead in the Timeline of the movie clip Y...

Page 613: ...Example In the following example two movie clip buttons control the Timeline The prev_mc button moves the playhead to the previous frame and the next_mc button moves the playhead to the next frame sto...

Page 614: ...a button in the following example you attach a movie clip instance to the Stage in a random position When you click a movie clip instance you remove that instance from the SWF file function randRange...

Page 615: ...ame of a movie clip to be masked mask_mc The instance name of a movie clip to be a mask Returns Nothing Description Method makes the movie clip in the parameter mask_mc a mask that reveals the movie c...

Page 616: ...ser first clicked on the movie clip false This parameter is optional left top right bottom Values relative to the coordinates of the movie clip s parent that specify a constraint rectangle for the mov...

Page 617: ...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 even...

Page 618: ...ect 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 MovieClipLoade...

Page 619: ...S or FLA file myMC1_mc onRelease function this swapDepths myMC2_mc myMC2_mc onRelease function this swapDepths myMC1_mc See also MovieClip getDepth MovieClip getInstanceAtDepth MovieClip getNextHighes...

Page 620: ...in automatic tab ordering It is undefined by default If tabEnabled is undefined the object is included in automatic tab ordering only if it defines at least one movie clip handler such as MovieClip o...

Page 621: ...des an object with a tabIndex value of 2 The custom tab ordering disregards the hierarchical relationships of objects in a SWF file All objects in the SWF file with tabIndex properties are placed in t...

Page 622: ...lowing example two movie clip buttons control the Timeline The prev_mc button moves the playhead to the previous frame and the next_mc button moves the playhead to the next frame stop prev_mc onReleas...

Page 623: ...ick a movie clip and release the mouse button on a second movie clip to see which instance receives the event myMC1_mc trackAsMenu true myMC2_mc trackAsMenu true myMC3_mc trackAsMenu false myMC1_mc on...

Page 624: ...the image_mc instance to the log file this createEmptyMovieClip image_mc 1 var mclListener Object new Object mclListener onLoadInit function target_mc MovieClip trace _url target_mc _url var image_mc...

Page 625: ...r is true If useHandCursor is set to true the pointing hand used for buttons is displayed when the mouse rolls over a button movie clip If useHandCursor is false the arrow pointer is used instead You...

Page 626: ...visible false this _visible false myMC2_mc onRelease function trace this _name _alpha 0 this _alpha 0 See also TextField _visible MovieClip _width Availability Flash Player 4 as a read only property U...

Page 627: ...clip s coordinates refer to the registration point position Example The following example attaches a movie clip with the linkage identifier cursor_id to a SWF file The movie clip is called cursor_mc a...

Page 628: ...operty determines the horizontal scale percentage of the movie clip as applied from the registration point of the movie clip The default registration point is 0 0 Scaling the local coordinate system a...

Page 629: ...formations the movie clip is in the local coordinate system of the enclosing movie clip Thus for a movie clip rotated 90 counterclockwise the movie clip s children inherit a coordinate system that is...

Page 630: ...function mouse_txt htmlText textformat tabStops 50 100 mouse_txt htmlText row1_str mouse_txt htmlText b _level0 b t _xmouse t _ymouse mouse_txt htmlText b my_mc b t this _xmouse t this _ymouse mouse_...

Page 631: ...eturns to the previous scaling this createEmptyMovieClip box_mc 1 box_mc _x 100 box_mc _y 100 with box_mc lineStyle 1 0xCCCCCC beginFill 0xEEEEEE moveTo 0 0 lineTo 80 0 lineTo 80 60 lineTo 0 60 lineTo...

Page 632: ...onLoadComplete listener is invoked After the downloaded file s first frame actions have been executed the MovieClipLoader onLoadInit listener is invoked After MovieClipLoader onLoadInit has been invo...

Page 633: ...ener MovieClipLoader addListener Availability Flash Player 7 Usage my_mcl addListener listenerObject Object Void Listener Description MovieClipLoader onLoadComplete Invoked when a file loaded with Mov...

Page 634: ...width 2 target_mc _width 2 target_mc _y Stage height 2 target_mc _width 2 var w Number target_mc _width var h Number target_mc _height target_mc lineStyle 4 0x000000 target_mc moveTo 0 0 target_mc lin...

Page 635: ...mclListener onLoadInit function target_mc MovieClip target_mc onPress function this startDrag target_mc onRelease function this stopDrag var mclProgress Object image_mcl getProgress target_mc target_...

Page 636: ...e of the clip have executed so you can begin manipulating the loaded clip The MovieClipLoader onLoadComplete handler is invoked when a file has completed downloading A SWF file or image loaded into a...

Page 637: ...ner onLoadInit function target_mc MovieClip trace First my_mcl instance trace Movie clip target_mc is now initialized you can now do any setup required for example target_mc _width 100 target_mc _heig...

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 f...

Page 639: ...ized Example The following example loads an image into a movie clip instance called image_mc The onLoadInit and onLoadComplete events are used to determine how long it takes to load the image The info...

Page 640: ...download is interrupted due to server overload server crash and so on MovieClipLoader onLoadComplete will not be called The value for target_mc identifies the movie clip this call is being made for Th...

Page 641: ...lip this call is being made for This is useful if you are loading multiple files with the same set of listeners This optional parameter is passed to your ActionScript Example The following example loa...

Page 642: ...p loaded by a MovieClipLoader loadClip method This parameter is optional loadedBytes The number of bytes that had been loaded when the listener was invoked totalBytes The total number of bytes in the...

Page 643: ...eEmptyMovieClip stroke_mc 2 with progressBar_mc stroke_mc lineStyle 0 0x000000 moveTo 0 0 lineTo 100 0 lineTo 100 10 lineTo 0 10 lineTo 0 0 with progressBar_mc bar_mc beginFill 0xFF0000 100 moveTo 0 0...

Page 644: ...ng example loads an image into a movie clip instance called image_mc The onLoadInit and onLoadComplete events are used to determine how long it takes to load the image This information displays in a t...

Page 645: ...and stop the loading process using two buttons called start_button and stop_button When the user starts or stops the progress information writes to the log file this createEmptyMovieClip image_mc thi...

Page 646: ...f you issue this command while a movie is loading MovieClipLoader onLoadError is invoked Example The following example loads an image into a movie clip called image_mc If you click the movie clip the...

Page 647: ...n Usage new NetConnection NetConnection Parameters None Returns A reference to a NetConnection object Description Constructor creates a NetConnection object that you can use in conjunction with a NetS...

Page 648: ...onstructor opens a local connection through which you can play back video FLV files from an HTTP address or from the local file system Example The following example opens a connection to play the vide...

Page 649: ...he following methods and properties of the NetConnection and NetStream classes are used to control FLV playback Property summary for the NetStream class Method Purpose NetStream close Closes the strea...

Page 650: ...ructs a new NetConnection object connection_nc and uses it to construct a new NetStream object called stream_ns Create a new video object called my_video Then add the following ActionScript to your FL...

Page 651: ...fer_txt html true var connection_nc NetConnection new NetConnection connection_nc connect null var stream_ns NetStream new NetStream connection_nc stream_ns setBufferTime 3 my_video attachVideo stream...

Page 652: ...NetStream new NetStream connection_nc stream_ns setBufferTime 3 my_video attachVideo stream_ns stream_ns play video1 flv var buffer_interval Number setInterval checkBufferTime 100 stream_ns function c...

Page 653: ...gressBar_mc this getNextHighestDepth progressBar_mc createEmptyMovieClip bar_mc progressBar_mc getNextHighestDepth with progressBar_mc bar_mc beginFill 0xFF0000 moveTo 0 0 lineTo 100 0 lineTo 100 10 l...

Page 654: ...stream_ns NetStream new NetStream connection_nc my_video attachVideo stream_ns stream_ns play video1 flv this createTextField loaded_txt this getNextHighestDepth 10 10 160 22 this createEmptyMovieCli...

Page 655: ...None Returns Nothing Description Method stops playing all data on the stream sets the NetStream time property to 0 and makes the stream available for another use This command also deletes the local c...

Page 656: ...plays var connection_nc NetConnection new NetConnection connection_nc connect null var stream_ns NetStream new NetStream connection_nc my_video attachVideo stream_ns stream_ns play video1 flv this cre...

Page 657: ...d try changing the buffer using the NetStream setBufferTime method Example The following example writes data about the stream to the log file var connection_nc NetConnection new NetConnection connecti...

Page 658: ...mes play This parameter is optional Returns Nothing Description Method pauses or resumes playback of a stream The first time you call this method without sending a parameter it pauses play the next ti...

Page 659: ...ant to stop a stream that is currently playing use NetStream close You can play local FLV files that are stored in the same directory as the SWF file or in a subdirectory you can t navigate to a highe...

Page 660: ...to seek n seconds forward or backward respectively from the current position For example to rewind 20 seconds from the current position use my_ns seek my_ns time 20 The precise location to which a vi...

Page 661: ...conds to 15 Flash begins playing the stream only after 15 seconds of data are buffered Example See the example for NetStream bufferLength See also NetStream bufferTime NetStream time Availability Flas...

Page 662: ...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 Numb...

Page 663: ...ns that are attached to the affected frames mouseMove The action is initiated every time the mouse is moved Use the _xmouse and _ymouse properties to determine the current mouse position mouseDown The...

Page 664: ...erty the playhead is sent to the previous frame onClipEvent keyDown if Key getCode Key RIGHT this _parent nextFrame else if Key getCode Key LEFT this _parent prevFrame The following example uses onCli...

Page 665: ...ctor onUpdate is invoked The onUpdate function does something to update itself For instance if the component includes a color parameter the onUpdate function might alter the color of a movie clip insi...

Page 666: ...e the current movie clip or object Example In the following example there is a movie clip on the Stage with the instance name square_mc Within that movie clip is another movie clip with an instance na...

Page 667: ...lled newClip_mc Images are loaded into both movie clips When a button button_mc is clicked the duplicated movie clip is removed from the Stage this createEmptyMovieClip myClip_mc this getNextHighestDe...

Page 668: ...ot is the same as using the deprecated slash notation to specify an absolute path within the current level Caution If a movie clip that contains _root is loaded into another movie clip _root refers to...

Page 669: ...BeginIndex Returns the index at the beginning of the selection span Returns 1 if there is no index or currently selected field Selection getCaretIndex Returns the current caret insertion point positio...

Page 670: ...signs a function The function takes two parameters a reference to the text field that lost focus and one to the text field that gained focus The function sets the border property of the text field tha...

Page 671: ...output_txt this getNextHighestDepth 0 0 300 200 output_txt multiline true output_txt wordWrap true output_txt border true output_txt type input output_txt text Enter your text here var my_cm ContextM...

Page 672: ...estDepth 50 50 400 300 content_txt border true content_txt type input content_txt wordWrap true content_txt multiline true content_txt onChanged getCaretPos var keyListener Object new Object keyListen...

Page 673: ...ontext menu item convert the selected text to upper case tempString target text substring beginIndex endIndex toUpperCase break case Lowercase tempString target text substring beginIndex endIndex toLo...

Page 674: ...ls TextArea my_mc onRelease function my_btn onRelease function var keyListener Object new Object keyListener onKeyDown function if Key isDown Key SPACE focus_ta text Selection getFocus newline focus_t...

Page 675: ...i in this if this i instanceof TextField this i border true this i type input this createTextField status_txt this getNextHighestDepth 200 10 300 100 status_txt html true status_txt multiline true var...

Page 676: ...2 0 25 100 22 this createTextField three_txt 3 0 50 100 22 this createTextField four_txt 4 0 75 100 22 for var i in this if this i instanceof TextField this i border true this i type input var select...

Page 677: ...automatically focuses in the text field that s missing data For example if the user does not type anything into the username_txt text field and clicks the submit button an error message appears and th...

Page 678: ...ext field The new selection span will begin at the index specified in the start parameter and end at the index specified in the end parameter Selection span indexes are zero based for example the firs...

Page 679: ...p as the movie clip plays Example The following ActionScript creates a new movie clip and loads an image into it The _x and _y coordinates are set for the clip using setProperty When you click the but...

Page 680: ...eturns the size of the sound in bytes Sound getPan Returns the value of the previous setPan call Sound getTransform Returns the value of the previous setTransform call Sound getVolume Returns the valu...

Page 681: ...e following example creates a new Sound object called global_sound The second line calls setVolume and adjusts the volume on all sounds in the movie to 50 var global_sound Sound new Sound global_sound...

Page 682: ...has the linkage identifier logoff_id var my_sound Sound new Sound my_sound attachSound logoff_id my_sound start Sound duration Availability Flash Player 6 Usage my_sound duration Number Description Re...

Page 683: ...stroke_mc pb getNextHighestDepth pb createTextField pos_txt pb getNextHighestDepth 0 pb_height pb_width 22 pb _x 100 pb _y 100 with pb bar_mc beginFill 0x00FF00 moveTo 0 0 lineTo pb_width 0 lineTo pb_...

Page 684: ...sTotal to determine what percentage of a sound has loaded Example The following example dynamically creates two text fields that display the bytes that are loaded and the total number of bytes for a s...

Page 685: ...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 Play...

Page 686: ...y created text field Add the following ActionScript to your FLA or AS file var bar_width Number 200 this createEmptyMovieClip bar_mc this getNextHighestDepth with bar_mc lineStyle 4 0x000000 moveTo 0...

Page 687: ...object with properties that contain the channel percentage values for the specified sound object Description Method returns the sound transform information for the specified Sound object set with the...

Page 688: ...orm_obj ll knob_ll onPress pressKnob knob_ll onRelease releaseKnob knob_ll onReleaseOutside releaseKnob knob_lr top knob_lr _y knob_lr bottom knob_lr _y 100 knob_lr left knob_lr _x knob_lr right knob_...

Page 689: ...und getVolume Availability Flash Player 5 Usage my_sound getVolume Number Parameters None Returns An integer Description Method returns the sound volume level as an integer from 0 to 100 where 0 is of...

Page 690: ...true knob_mc onMouseMove function if this isDragging this volume_txt text this _x knob_mc onRelease function this stopDrag this isDragging false my_sound setVolume this _x See also Sound setVolume So...

Page 691: ...lbum movie show title TBPM Beats per minute TCOM Composer TCON Content type TCOP Copyright message TDAT Date TDLY Playlist delay TENC Encoded by TEXT Lyricist text writer TFLT File type TIME Time TIT1...

Page 692: ...sound Sound new Sound my_sound onID3 function for var prop in my_sound id3 trace prop my_sound id3 prop my_sound loadSound song mp3 false See also Sound attachSound Sound loadSound TPOS Part of a set...

Page 693: ...unds are completely loaded before they play They are managed by the ActionScript Sound class and respond to all methods and properties of this class Streaming sounds play while they are downloading Pl...

Page 694: ...th the instance name id3_dg to your document and add the following ActionScript to your FLA or AS file import mx controls gridclasses DataGridColumn var id3_dg mx controls DataGrid id3_dg move 0 0 id3...

Page 695: ...mple The following example creates a new Sound object and loads a sound Loading the sound is handled by the onLoad handler which allows you to start the song after it is successfully loaded Create a n...

Page 696: ...t create a function that executes when this handler is invoked You can use either an anonymous function or a named function Example Usage 1 The following example uses an anonymous function var my_soun...

Page 697: ...an pan Number Number Parameters pan An integer specifying the left right balance for a sound The range of valid values is 100 to 100 where 100 uses only the left channel 100 uses only the right channe...

Page 698: ...m to play mono sounds as stereo play stereo sounds as mono and to add interesting effects to sounds The properties for the soundTransformObject are as follows 11 A percentage value specifying how much...

Page 699: ...ansform as follows my_sound setTransform mySoundTransformObject The following example plays a stereo sound as mono the soundTransformObjectMono object has the following parameters var mySoundTransform...

Page 700: ...my_sound start secondOffset Number loop Number Void Parameters secondOffset An optional parameter that lets you start playing the sound at a specific point For example if you have a 30 second sound a...

Page 701: ...tDepth 0 0 100 22 create a new Sound object var my_sound Sound new Sound if the sound loads play it if not trace failure loading my_sound onLoad function success Boolean if success my_sound start stat...

Page 702: ...sound that loads into a SWF file Add two buttons to your document and add the following ActionScript to your FLA or AS file var my_sound Sound new Sound my_sound loadSound song1 mp3 true stop_btn onR...

Page 703: ...r the MP3 for 10 seconds A new Sound object instance is created for the MP3 create text fields to hold debug information this createTextField counter_txt this getNextHighestDepth 0 0 100 22 this creat...

Page 704: ...addListener myListener Object Void Parameters myListener An object that listens for a callback notification from the Stage onResize event Method Description Stage addListener Adds a listener object t...

Page 705: ...e callback list of the Stage object Listener objects allow multiple objects to listen for resize notifications this createTextField stageSize_txt this getNextHighestDepth 10 10 100 22 var stageListene...

Page 706: ...rty read only indicates the current height in pixels of the Stage When the value of Stage scaleMode is noScale the height property represents the height of Flash Player When the value of Stage scaleMo...

Page 707: ...s event handler to write a function that lays out the objects on the Stage when a SWF file is resized Example The following example writes the results of the trace method to the log file when the Stag...

Page 708: ...tings dialog box The scaleMode property can use the values exactFit showAll noBorder and noScale Any other value sets the scaleMode property to the default showAll Example The following example demons...

Page 709: ...age width Availability Flash Player 6 Usage Stage width Number Description Property read only indicates the current width in pixels of the Stage When the value of Stage scaleMode is noScale the width...

Page 710: ...7 ActionScript for Flash stageListener onResize function stageSize_txt text w Stage width h Stage height Stage scaleMode noScale Stage addListener stageListener See also Stage align Stage height Stag...

Page 711: ...ged at a time After a startDrag operation is executed the movie clip remains draggable until it is explicitly stopped by stopDrag or until a startDrag action for another movie clip is called Example T...

Page 712: ...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...

Page 713: ...e sound is paused When the user clicks play_mc the song resumes from its paused position this createTextField songinfo_txt this getNextHighestDepth 0 0 Stage width 22 var bg_sound Sound new Sound bg_s...

Page 714: ...stops the current drag operation Example The following code placed in the main Timeline stops the drag action on the movie clip instance my_mc when the user releases the mouse button my_mc onPress fun...

Page 715: ...of the specified movie clip Description Function returns a string containing the target path of movieClipObject The target path is returned in dot notation To retrieve the target path in slash notati...

Page 716: ...th Returns the depth of a text field TextField getNewTextFormat Gets the default text format assigned to newly inserted text TextField getTextFormat Returns a TextFormat object containing formatting i...

Page 717: ...ct with a text field TextField mouseWheelEnabled Indicates whether Flash Player should automatically scroll multiline text fields when the mouse pointer is positioned over a text field and the user ro...

Page 718: ...the text field word wraps TextField _x The x coordinate of a text field instance TextField _xmouse Read only the x coordinate of the pointer relative to a text field instance TextField _xscale The val...

Page 719: ...ndler method For example the following code uses txt as the parameter that is passed to the onScroller event handler The parameter is then used in a trace method to write the instance name of the text...

Page 720: ...property of a text field named my_txt to 20 Set the linkage for a font symbol to my font Add the following ActionScript to your FLA or AS file var my_fmt TextFormat new TextFormat my_fmt font my font...

Page 721: ...ld will be resized and the left side will remain fixed If autoSize is set to center then the text is treated as center justified text meaning any resizing of a single line text field will be equally d...

Page 722: ...ener myMouseListener TextField background Availability Flash Player 6 Usage my_txt background Boolean Description Property if true the text field has a background fill If false the text field has no b...

Page 723: ...ple The following example creates a text field called my_txt sets the border property to true and displays some text in the field this createTextField my_txt this getNextHighestDepth 10 10 320 240 my_...

Page 724: ...creates a text field and fills it with text The scroll and bottomScroll properties for the text field are then traced for the comment_txt field this createTextField comment_txt this getNextHighestDep...

Page 725: ...to your FLA or AS file var my_str String Hello tWorld nHow are you t t tEnd this createTextField first_txt this getNextHighestDepth 10 10 160 120 first_txt html true first_txt multiline true first_tx...

Page 726: ...at my_fmt my_txt _rotation 45 TextField getDepth Availability Flash Player 6 Usage my_txt getDepth Number Parameters None Returns An integer Description Method returns the depth of a text field Exampl...

Page 727: ...he player s host system as an array It does not return names of all fonts in currently loaded SWF files The names are of type String Example The following code displays a font list returned by getFont...

Page 728: ...endIndex Number Object Parameters index An integer that specifies a character in a string beginIndex endIndex Integers that specify the starting and ending locations of a span of text within my_txt Re...

Page 729: ...o TextField getNewTextFormat TextField setNewTextFormat TextField setTextFormat TextField _height Availability Flash Player 6 Usage my_txt _height Number Description Property the height of the text fi...

Page 730: ...splays in a text field called scroll_txt Add the following ActionScript to your FLA or AS file this createTextField scroll_txt this getNextHighestDepth 10 10 160 20 this createTextField my_txt this ge...

Page 731: ...t field it behaves identically to the text property You can indicate that a text field is an HTML text field in the Property inspector or by setting the text field s html property to true Example The...

Page 732: ...ain A script may insert more text than maxChars allows the maxChars property indicates only how much text a user can enter If the value of this property is null there is no limit on the amount of text...

Page 733: ...true my_txt wordWrap true for var i 0 i 10 i my_txt text Lorem ipsum dolor sit amet consectetuer adipiscing elit sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat...

Page 734: ...menu_cm ContextMenu new ContextMenu menu_cm customItems push new ContextMenuItem Resize doResize function doResize obj TextField item ContextMenuItem Void Resize code here trace you selected item cap...

Page 735: ...nonscrollable_txt border true nonscrollable_txt wordWrap true nonscrollable_txt multiline true nonscrollable_txt mouseWheelEnabled false nonscrollable_txt text font_array join n See also Mouse onMous...

Page 736: ...epth 10 10 100 22 this createTextField second_mc this getNextHighestDepth 10 10 100 22 for var prop in this if this prop instanceof TextField var this_txt TextField this prop trace this_txt _name is a...

Page 737: ...in the text field using the mouse or selecting a menu item Programmatic changes to the text field do not trigger the onChanged event because the code recognizes changes that are made to the text field...

Page 738: ...roperties changes A reference to the text field instance is passed as a parameter to the onScroller handler You can capture this data by putting a parameter in the event handler method For example the...

Page 739: ...buttons with instance names scrollUp_btn and scrollDown_btn and add the following ActionScript to your FLA or AS file this createTextField scroll_txt this getNextHighestDepth 10 10 160 20 this create...

Page 740: ...g the ActionScript code that references _parent Use _parent to specify a relative path to movie clips or objects that are above the current text field You can use _parent to climb up multiple levels i...

Page 741: ...s will not function This security mechanism prevents an unscrupulous user from using the shortcuts to discover a password on an unattended computer Example The following example creates two text field...

Page 742: ...ed or TextField onScroller Returns If listener was successfully removed the method returns a true value If listener was not successfully removed for example if listener was not on the TextField object...

Page 743: ...e performed on a text field that was created with MovieClip createTextField When you call this method the text field is removed This method is similar to MovieClip removeMovieClip Example The followin...

Page 744: ...ield you can select Enter current date from the context menu This selection calls a function that replaces the selected text with the current date this createTextField my_txt this getNextHighestDepth...

Page 745: ...ng Description Property indicates the set of characters that a user may enter into the text field If the value of the restrict property is null you can enter any character If the value of the restrict...

Page 746: ...lash Player 6 Usage my_txt _rotation Number Description Property the rotation of the text field in degrees from its original orientation Values from 0 to 180 represent clockwise rotation values from 0...

Page 747: ...t 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 Example The following example sets the ma...

Page 748: ...and the text cannot be copied using the Copy command If selectable is set to true the text in the text field can be selected using the mouse or keyboard You can select text this way even if the text f...

Page 749: ...fmt color 0xFF9900 this createTextField my_txt 999 0 0 400 300 my_txt wordWrap true my_txt multiline true my_txt border true my_txt type input my_txt setNewTextFormat my_fmt my_txt text Oranges are a...

Page 750: ...es the properties of textFormat to all text in the text field Usage 2 Applies the properties of textFormat to the character at position index Usage 3 Applies the properties of the textFormat parameter...

Page 751: ...1_btn css2_btn and clearCss_btn are used to change the style sheet that is applied to news_txt or clear the style sheet from the text field Add the following ActionScript to your FLA or AS file this c...

Page 752: ...ined 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 imp...

Page 753: ...eral text fields called one_txt two_txt three_txt and four_txt The three_txt text field has the tabEnabled property set to false so it is excluded from the automatic tab ordering this createTextField...

Page 754: ...operty is flat This means that no attention is paid to the hierarchical relationships of objects in the SWF file All objects in the SWF file with tabIndex properties are placed in the tab order and th...

Page 755: ...t output _level0 my_txt TextField text Availability Flash Player 6 Usage my_txt text String Description Property indicates the current text in the text field Lines are separated by the carriage return...

Page 756: ...m is FFFFFF Example The following ActionScript creates a text field and changes its color property to red this createTextField my_txt 99 10 10 100 300 my_txt text this will be red text my_txt textColo...

Page 757: ...See Also TextField textHeight TextField type Availability Flash Player 6 Usage my_txt type String Description Property Specifies the type of text field There are two values dynamic which specifies a...

Page 758: ...the text field Example The following example retrieves the URL of the SWF file that created the text field and a SWF file that loads into it this createTextField my_txt 1 10 10 100 22 trace my_txt _u...

Page 759: ...ber setInterval updateDate 500 function updateDate Void today_date new Date TextField _visible Availability Flash Player 6 Usage my_txt _visible Boolean Description Property a Boolean value that indic...

Page 760: ...true my_txt multiline true my_txt type input my_txt wordWrap true this createTextField width_txt this getNextHighestDepth 10 10 30 20 width_txt border true width_txt maxChars 3 width_txt restrict 0 9...

Page 761: ...lability Flash Player 6 Usage my_txt _x Number Description Property an integer that sets the x coordinate of a text field relative to the local coordinates of the parent movie clip If a text field is...

Page 762: ...e displays the current position of the mouse in relation to the Stage The textfield_txt instance displays the current position of the mouse pointer in relation to the my_txt instance Add the following...

Page 763: ...y_txt _yscale 2 scaleDown_btn onRelease function my_txt _xscale 2 my_txt _yscale 2 See also TextField _x TextField _y TextField _yscale TextField _y Availability Flash Player 6 Usage my_txt _y Number...

Page 764: ...the mouse position relative to the text field Example See the example for TextField _xmouse See also TextField _xmouse TextField _yscale Availability Flash Player 6 Usage my_txt _yscale Number Descrip...

Page 765: ...ect to a TextField object s styleSheet property Method summary for the TextField StyleSheet class Event handler summary for the TextField StyleSheet class L Constructor for the TextField StyleSheet cl...

Page 766: ...oolean if success trace Styles loaded var styles_array Array my_styleSheet getStyleNames trace styles_array join newline else trace Error loading CSS my_styleSheet load styles css The styles css file...

Page 767: ...es_array length i trace t styles_array i trace else trace Error loading CSS Start the loading operation my_styleSheet load styles css clear_btn onRelease function my_styleSheet clear trace Styles clea...

Page 768: ...Load function success Boolean if success StyleSheetTracer display this else trace Error loading style sheet url Start the loading operation my_styleSheet load url static function display my_styleSheet...

Page 769: ...StyleSheet setStyle TextField StyleSheet getStyleNames Availability Flash Player 7 Usage styleSheet getStyleNames Array Parameters None Returns An array Description Method returns an array that contai...

Page 770: ...he file has finished loading The CSS file must reside in exactly the same domain as the SWF file that is loading it For more information about restrictions on loading data across domains see Applying...

Page 771: ...ssfully loaded Returns Nothing Description Callback handler invoked when a TextField StyleSheet load operation has completed If the style sheet loaded successfully the success parameter is true If the...

Page 772: ...the text was parsed successfully true or not false Description Method parses the CSS in cssText and loads the style sheet with it If a style in cssText is already in styleSheet the properties in styl...

Page 773: ...specified name to the style sheet object If the named style does not already exist in the style sheet it is added If the named style already exists in the style sheet it is replaced If the style para...

Page 774: ...style object passed to setStyle While not necessary this step reduces memory usage because Flash Player creates a copy of the style object you pass to setStyle See also object initializer TextField S...

Page 775: ...s 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 st...

Page 776: ...he bold property to a defined value The code my_txt setTextFormat my_fmt only changes the bold property of the text field s default text format because the bold property is the only one defined in my_...

Page 777: ...played If the target window is an empty string the text is displayed in the default target window _self If the url parameter is set to an empty string or to the value null you can get or set this prop...

Page 778: ...wing example creates a TextFormat object formats the stats_txt text field and creates a new text field to display the text in Define a TextFormat which is used to format the stats_txt text field var m...

Page 779: ...e block indentation in points Block indentation is applied to an entire block of text that is to all lines of the text In contrast normal indentation TextFormat indent affects only the first line of e...

Page 780: ...e my_fmt bullet Boolean Description Property a Boolean value that indicates that the text is part of a bulleted list In a bulleted list each paragraph of text is indented To the left of the first line...

Page 781: ...true my_txt wordWrap true my_txt border true my_txt text this is my first test field object text my_txt setTextFormat my_fmt TextFormat font Availability Flash Player 6 Usage my_fmt font String Descri...

Page 782: ...width parameter is specified word wrapping is applied to the specified text This lets you determine the height at which a text box shows all of the specified text The ascent and descent measurements p...

Page 783: ...apply its properties var my_fmt TextFormat new TextFormat with my_fmt font Arial bold true Obtain metrics information for the text string with the specified formatting var metrics Object my_fmt getTe...

Page 784: ...etrics textFieldHeight my_txt wordWrap true my_txt border true Assign the text and the TextFormat object to the TextObject my_txt text textToDisplay my_txt setTextFormat my_fmt TextFormat indent Avail...

Page 785: ...extFormat new TextFormat myformat italic true mytext text this is my first test field object text mytext setTextFormat myformat TextFormat leading Availability Flash Player 6 Usage my_fmt leading Numb...

Page 786: ...TextFormat myformat leftMargin 20 mytext text this is my first test field object text mytext setTextFormat myformat TextFormat rightMargin Availability Flash Player 6 Usage my_fmt rightMargin Number D...

Page 787: ...rst test field object text mytext setTextFormat myformat TextFormat tabStops Availability Flash Player 6 Usage my_fmt tabStops Array Description Property specifies custom tab stops as an array of non...

Page 788: ...ent window _blank specifies a new window _parent specifies the parent of the current frame and _top specifies the top level frame in the current window If the TextFormat url property is an empty strin...

Page 789: ...Format new TextFormat myformat underline true mytext text this is my first test field object text mytext setTextFormat myformat TextFormat url Availability Flash Player 6 Usage my_fmt url String Descr...

Page 790: ...mber Parameters startIndex An integer specifying the starting point in my_snap to search for the specified text Method Description TextSnapshot findText Returns the position of the first occurrence of...

Page 791: ...ing example illustrates how to use this method To use this code create a static text field that contains the text TextSnapshot Example var my_mc MovieClip this var my_snap TextSnapshot my_mc getTextSn...

Page 792: ...m An integer that indicates the position of the first character of my_snap to be examined Valid values for from are 0 through TextSnapshot getCount 1 If from is a negative value 0 is used to An intege...

Page 793: ...r 7 or later Usage my_snap getSelectedText includeLineEndings Boolean String Parameters includeLineEndings An optional Boolean value that specifies whether newline characters are inserted into the ret...

Page 794: ...ns A string containing the characters in the specified range or an empty string if no characters are found in the specified range Description Method returns a string that contains all the characters s...

Page 795: ...haracter is found or if the font doesn t contain character metric information see Description Description Method lets you determine which character within a TextSnapshot object is on or near specified...

Page 796: ...ingle character the mouse pointer is over my_ts setSelected hitIndex hitIndex 1 true See also MovieClip getTextSnapshot MovieClip _x MovieClip _y TextSnapshot setSelectColor Availability Authoring Fla...

Page 797: ...etSelectedText false get the selected text trace theText output Txt trace firstCharIsSelected output true trace secondCharIsSelected output false When you test the SWF file you see a colored rectangle...

Page 798: ...ion for static text fields In some cases this behavior means that text that is selected won t appear to be selected onscreen Example The following example illustrates how to use this method To use thi...

Page 799: ...hat clip 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 macrom...

Page 800: ...hat was loaded by means of loadMovieNum from Flash Player To unload a SWF or image that was loaded with MovieClip loadMovie use unloadMovie instead of unloadMovieNum Example The following example load...

Page 801: ...only with certain Mouse and MovieClip handlers the mouseDown mouseUp mouseMove keyDown and keyUp handlers for the Mouse class the onMouseMove onMouseDown onMouseUp onKeyDown and onKeyUp handlers for t...

Page 802: ...idth properties and so on Method summary for the Video class Property summary for the Video class Video attachVideo Availability Flash Player 6 the ability to work with Flash Video FLV files was added...

Page 803: ...p attachAudio to route the audio to a movie clip you can then create a Sound object to control some aspects of the audio For more information see MovieClip attachAudio Example The following example pl...

Page 804: ...y_video deblocking Number Description Property a number that specifies the behavior for the deblocking filter that the video compressor applies as needed when streaming the video The following are acc...

Page 805: ...height property of the Camera object that is capturing the video stream For FLV files this value is the height of the file that was exported as FLV You may want to use this property for example to ens...

Page 806: ...ilability Flash Player 6 Usage my_video smoothing Boolean Description Property a Boolean value that specifies whether the video should be smoothed interpolated when it is scaled For smoothing to work...

Page 807: ...ecifying the width of the video stream in pixels For live streams this value is the same as the Camera width property of the Camera object that is capturing the video stream For FLV files this value i...

Page 808: ...808 Chapter 7 ActionScript for Flash...

Page 809: ...Logical NOT Right to left and Logical AND Left to right or Logical OR Flash 4 Left to right add String concatenation formerly Left to right instanceof Instance of Left to right lt Less than string ve...

Page 810: ...810 Appendix A Deprecated Flash 4 operators...

Page 811: ...ion keys on page 813 Other keys on page 814 You can use key constants to intercept the built in behavior of keypresses For more information see Key class on page 295 Letters A to Z and standard number...

Page 812: ...2 Appendix B Keyboard Keys and Key Code Values L 76 M 77 N 78 O 79 P 80 Q 81 R 82 S 83 T 84 U 85 V 86 W 87 X 88 Y 89 Z 90 0 48 1 49 2 50 3 51 4 52 5 53 6 54 7 55 8 56 9 57 Letter or number key Key cod...

Page 813: ...tion keys on a standard keyboard with the corresponding ASCII key code values that are used to identify the keys in ActionScript Numeric keypad key Key code Numbpad 0 96 Numbpad 1 97 Numbpad 2 98 Numb...

Page 814: ...es that are used to identify the keys in ActionScript F10 This key is reserved by the system and cannot be used in ActionScript F11 122 F12 123 F13 124 F14 125 F15 126 Key Key code Backspace 8 Tab 9 C...

Page 815: ...Other keys 815 Num Lock 144 186 187 _ 189 191 192 219 220 221 222 Key Key code...

Page 816: ...816 Appendix B Keyboard Keys and Key Code Values...

Page 817: ...rs built in functions 41 C calling methods 21 casting data types 25 character sequences See strings child node 70 class files creating 48 class members and Singleton design pattern 61 and subclasses 6...

Page 818: ...Document Object Model XML 70 dot operators 38 dot syntax 14 dynamic classes 56 E ECMA 262 specification 10 encapsulation 47 equality operators 37 different from assignment operators 37 strict 37 erro...

Page 819: ...tion keys 813 letter and number keys 811 numeric keypad 813 other keys 814 keyboard ASCII key code values 811 keywords 12 listed 17 L languages using multiple in scripts 10 loaded data checking for 68...

Page 820: ...s 53 Q quotation marks including in strings 19 R reference data types 18 referencing variables 28 remote files communicating with 67 sites continuous connection 71 repeating actions 40 reserved words...

Page 821: ...oded format sending information 68 V values manipulating in expressions 31 variables about 27 assigning multiple 37 defined 13 determining data type 26 naming rules 27 passing content 30 referencing v...

Page 822: ...822 Index...

Page 823: ...ignment 120 equality 120 strict equality 122 greater than 124 greater than or equal to 124 bitwise right shift 125 bitwise right shift and assignment 126 bitwise unsigned right shift 127 bitwise unsig...

Page 824: ...ideBuiltInItems 521 ContextMenu onSelect 522 ContextMenuItem class 524 ContextMenuItem caption 526 ContextMenuItem copy 526 ContextMenuItem enabled 527 ContextMenuItem onSelect 528 ContextMenuItem sep...

Page 825: ...TER 301 Key ESCAPE 302 Key getAscii 302 Key getCode 303 Key INSERT 305 Key isDown 305 Key isToggled 306 Key LEFT 307 Key onKeyDown 308 Key onKeyUp 308 Key PGDN 309 Key PGUP 310 Key removeListener 310...

Page 826: ...class 554 MovieClip _alpha 558 MovieClip _currentframe 568 MovieClip _droptarget 571 MovieClip _focusrect 574 MovieClip _framesloaded 575 MovieClip _height 585 MovieClip _highquality 585 MovieClip _lo...

Page 827: ...MovieClipLoader addListener 633 MovieClipLoader getProgress 634 MovieClipLoader loadClip 635 MovieClipLoader onLoadComplete 638 MovieClipLoader onLoadError 639 MovieClipLoader onLoadInit 641 MovieCli...

Page 828: ...e addListener 704 Stage align 705 Stage height 706 Stage onResize 707 Stage removeListener 707 Stage scaleMode 708 Stage showMenu 708 Stage width 709 startDrag 711 static 206 stop 712 stopAllSounds 71...

Page 829: ...725 TextField getDepth 726 TextField getFontList 727 TextField getNewTextFormat 727 TextField getTextFormat 728 TextField hscroll 729 TextField html 730 TextField htmlText 731 TextField length 731 Tex...

Page 830: ...o deblocking 804 Video height 805 Video smoothing 806 Video width 807 void 227 W while 228 with 230 X XML class 445 XML addRequestHeader 447 XML appendChild 448 XML attributes 450 XML childNodes 450 X...

Reviews: