background image

ActionScript Language Reference

Summary of Contents for FLASH MX 2004-ACTIONSCRIPT LANGUAGE

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

Page 2: ...then you do so at your own risk Macromedia provides these links only as a convenience and the inclusion of the link does not imply that Macromedia endorses or accepts any responsibility for the conte...

Page 3: ...t inequality 32 modulo 34 modulo assignment 35 bitwise AND 36 logical AND 38 bitwise AND assignment 40 parentheses 41 minus 43 multiplication 44 multiplication assignment 45 comma 46 dot 48 type 50 co...

Page 4: ...ibility class 92 Accessibility isActive 93 Accessibility updateProperties 94 _accProps 95 arguments object 98 arguments callee 99 arguments caller 100 arguments length 101 Array 102 Array class 103 Ar...

Page 5: ...159 Button tabIndex 160 Button _target 161 Button trackAsMenu 162 Button _url 163 Button useHandCursor 164 Button _visible 165 Button _width 166 Button _x 167 Button _xmouse 168 Button _xscale 169 Bu...

Page 6: ...extMenuItem onSelect 226 ContextMenuItem separatorBefore 227 ContextMenuItem visible 228 continue 229 CustomActions class 231 CustomActions get 232 CustomActions install 233 CustomActions list 235 Cus...

Page 7: ...74 Date setYear 275 Date toString 276 Date UTC 277 default 278 delete 279 do while 281 duplicateMovieClip 283 dynamic 284 else 286 else if 287 endinitclip 288 Error class 289 Error message 291 Error n...

Page 8: ...353 Key getCode 354 Key HOME 355 Key INSERT 356 Key isDown 357 Key isToggled 358 Key LEFT 360 Key onKeyDown 361 Key onKeyUp 362 Key PGDN 363 Key PGUP 364 Key removeListener 365 Key RIGHT 366 Key SHIF...

Page 9: ...421 Math acos 422 Math asin 423 Math atan 424 Math atan2 425 Math ceil 426 Math cos 427 Math E 428 Math exp 429 Math floor 430 Math log 431 Math LN2 432 Math LN10 433 Math LOG2E 434 Math LOG10E 435 Ma...

Page 10: ...eginFill 498 MovieClip beginGradientFill 499 MovieClip clear 503 MovieClip createEmptyMovieClip 504 MovieClip createTextField 505 MovieClip _currentframe 507 MovieClip curveTo 508 MovieClip _droptarge...

Page 11: ...62 MovieClip onMouseUp 563 MovieClip onPress 564 MovieClip onRelease 565 MovieClip onReleaseOutside 566 MovieClip onRollOut 567 MovieClip onRollOver 568 MovieClip onSetFocus 569 MovieClip onUnload 570...

Page 12: ...ClipLoader removeListener 617 MovieClipLoader unloadClip 619 NaN 620 Infinity 621 NetConnection class 622 NetConnection connect 624 NetStream class 625 NetStream bufferLength 627 NetStream bufferTime...

Page 13: ...sBitmap 693 printAsBitmapNum 695 PrintJob class 697 PrintJob addPage 699 PrintJob send 703 PrintJob start 704 printNum 706 private 707 public 709 _quality 710 removeMovieClip 711 return 712 _root 713...

Page 14: ...Complete 768 Sound position 769 Sound setPan 770 Sound setTransform 771 Sound setVolume 773 Sound start 774 Sound stop 775 _soundbuftime 776 Stage class 777 Stage addListener 778 Stage align 779 Stage...

Page 15: ...anguage 830 System capabilities localFileReadDisable 832 System capabilities manufacturer 833 System capabilities os 834 System capabilities pixelAspectRatio 835 System capabilities playerType 836 Sys...

Page 16: ...90 TextField html 891 TextField htmlText 892 TextField length 893 TextField maxChars 894 TextField maxhscroll 895 TextField maxscroll 896 TextField menu 897 TextField mouseWheelEnabled 898 TextField m...

Page 17: ...d 947 TextFormat bullet 948 TextFormat color 949 TextFormat font 950 TextFormat getTextExtent 951 TextFormat indent 954 TextFormat italic 955 TextFormat leading 956 TextFormat leftMargin 957 TextForma...

Page 18: ...XML cloneNode 1017 XML contentType 1019 XML createElement 1020 XML createTextNode 1021 XML docTypeDecl 1023 XML firstChild 1024 XML getBytesLoaded 1026 XML getBytesTotal 1027 XML hasChildNodes 1028 XM...

Page 19: ...tring specific 1077 ge greater than or equal to string specific 1078 gt greater than string specific 1079 _highquality 1080 inequality 1081 ifFrameLoaded 1082 int 1083 le less than or equal to string...

Page 20: ...20 Contents...

Page 21: ...A file s Publish Settings dialog box There are two types of entries in this manual Individual entries for operators keywords functions variables properties methods and statements Class entries which p...

Page 22: ...e The required portion of the syntax is in code font Both the code that you provide and data type information are in italicized code font Data types can be distinguished from code that you provide by...

Page 23: ...standard elements usage description and so on of other entries Method property and event handler listings The methods properties and event handlers of a class are listed alphabetically after the clas...

Page 24: ...24 Chapter 1 Introduction...

Page 25: ...rator expression subtracts 1 from expression and returns the result The post decrement form of the operator expression subtracts 1 from the expression and returns the initial value of expression the v...

Page 26: ...26 Chapter 2 ActionScript Language Reference The following example loops from 10 to 1 and each iteration of the loop decreases the counter variable i by 1 for var i 10 i 0 i trace i...

Page 27: ...tial 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 Number x trace x x traces x 2 t...

Page 28: ...9 10 This script shows the following result in the Output panel 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...

Page 29: ...true The following expressions illustrate the result of using the logical NOT operator true returns false false returns true For more information see Operator precedence and associativity in Using Ac...

Page 30: ...the expression 2 3 is equal to the expression 1 4 when compared by value Comparison by reference means that two expressions are equal only if they both refer to the same object array or function Valu...

Page 31: ...foo false The following example illustrates comparison by reference with two arrays var a Array 1 2 3 var b Array 1 2 3 trace a 1 2 3 trace b 1 2 3 trace a b true a b trace a 1 2 3 trace b 1 2 3 trac...

Page 32: ...ion of equal depends on the data types being compared as illustrated in the following list Numbers strings and Boolean values are compared by value Objects arrays and functions are compared by referen...

Page 33: ...strict inequality 33 trace s1 n true trace s1 b true See also logical NOT inequality logical AND logical OR equality strict equality...

Page 34: ...erator attempts to convert them to numbers The expression can be a number or string that converts to a numeric value For more information see Automatic data typing and Operator precedence and associat...

Page 35: ...c compound assignment assigns expression1 the value of expression1 expression2 The following two expressions are equivalent x y x x y For more information see Operator precedence and associativity in...

Page 36: ...ded 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 2147483648 or 0x800000000 nu...

Page 37: ...bitwise AND 37 trace 0xFFFFFFFF 1 1 trace 4294967295 1 1 trace 4294967295 4294967295 1 See Also bitwise AND assignment bitwise XOR bitwise XOR assignment bitwise OR bitwise OR assignment bitwise NOT...

Page 38: ...to true the final result is true otherwise it is false For more information see Operator precedence and associativity in Using ActionScript in Flash Example The following example uses the logical AND...

Page 39: ...logical AND 39 See also logical NOT inequality strict inequality logical OR equality strict equality...

Page 40: ...assigns expression1 the value of expression1 expression2 For example the following two expressions are equivalent x y x x y For more information see Operator precedence and associativity in Using Act...

Page 41: ...the normal precedence order and cause the expressions within the parentheses to be evaluated first When parentheses are nested the contents of the innermost parentheses are evaluated before the conten...

Page 42: ...bar b 10 trace foo bar a b outputs 23 Usage 3 The following example shows the use of parentheses with functions var today Date new Date trace today getFullYear traces current year function traceParam...

Page 43: ...en both expressions are integers the difference is an integer When either or both expressions are floating point numbers the difference is a floating point number For more information see Operator pre...

Page 44: ...product is an integer If either or both expressions are floating point numbers the product is a floating point number For more information see Operator precedence and associativity in Using ActionScr...

Page 45: ...n1 expression2 For example the following two expressions are equivalent x y x x y For more information see Operator precedence and associativity in Using ActionScript in Flash Example Usage 1 The foll...

Page 46: ...1 j 2 The following example uses the comma operator without the parentheses operator and illustrates that the comma operator returns only the value of the first expression without the parentheses ope...

Page 47: ...s example except for the addition of the parentheses operator and illustrates once again that when used with the parentheses operator the comma operator returns the value of the last expression in the...

Page 48: ...t operator 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 nested child movie clips variables or pro...

Page 49: ...r_mc createTextField date_txt this getNextHighestDepth 0 0 100 22 this container_mc date_txt autoSize true this container_mc date_txt text new Date The dot operator is used when targeting instances wi...

Page 50: ...a function parameter in a function definition this operator specifies the variable type expected for that parameter Types are a compile time only feature All types are checked at compile time and erro...

Page 51: ...ber function randomInt integer Number Number return Math round Math random integer trace randomInt 8 Usage 3 The following example defines a function named squareRoot that takes a parameter named val...

Page 52: ...f expression2 otherwise it returns the value of expression3 For more information see Operator precedence and associativity in Using ActionScript in Flash Example The following statement assigns the va...

Page 53: ...sion2 The result of the division operation is a double precision floating point number For more information see Operator precedence and associativity in Using ActionScript in Flash Example The followi...

Page 54: ...he ActionScript interpreter For more information see Deprecated Flash 4 operators in Using ActionScript in Flash Example The following script uses comment delimiters to identify the first third fifth...

Page 55: ...pting to nest comments also returns an error message After an opening comment tag is used the first closing comment tag will end the comment regardless of the number of opening comment tags placed bet...

Page 56: ...on Operator arithmetic compound assignment assigns expression1 the value of expression1 expression2 For example the following two statements are equivalent x y x x y For more information see Operator...

Page 57: ...ccesses elements in an array The array access operator lets you dynamically set and retrieve instance variable and object names It also lets you access object properties Usage 1 An array is an object...

Page 58: ...lowing line of code sends the number 6 to the Output panel name mc i left_corner For more information see Operator precedence and associativity in Using ActionScript in Flash Example The following exa...

Page 59: ...Script slash syntax you can use the eval function to accomplish the same result eval name_mc A i You can use the following ActionScript to loop over all objects in the _root scope which is useful for...

Page 60: ...are converted so the value is still 32 bit Negative numbers are converted to an unsigned hex value via the two s complement notation with the minimum being 2147483648 or 0x800000000 numbers less than...

Page 61: ...expression1 the value of expression1 expression2 For example the following two statements are equivalent x y x x y For more information see Operator precedence and associativity in Using ActionScript...

Page 62: ...pairs using the assignment operator The prototype of the newly created object is generically named the Object object This operator is also used to mark blocks of contiguous code associated with flow c...

Page 63: ...ous example and produces the same result using constructor functions var person Object new Object person name Gina Vechio person children new Array person children 0 Ruby person children 1 Chickie per...

Page 64: ...onverted so the value is still 32 bit Negative numbers are converted to an unsigned hex value via the two s complement notation with the minimum being 2147483648 or 0x800000000 numbers less than the m...

Page 65: ...R operator with any number of operands if any operand evaluates to true the result is true For more information see Operator precedence and associativity in Using ActionScript in Flash Example The fol...

Page 66: ...nction fx2 Boolean trace fx2 called return true if fx1 fx2 trace IF statement entered The following is sent to the Output panel fx1 called IF statement entered See also logical NOT inequality strict i...

Page 67: ...For example the following two statements are equivalent x y x x y For more information see Operator precedence and associativity in Using ActionScript in Flash Example The following example uses the...

Page 68: ...ach Floating point numbers are converted to integers by discarding any digits after the decimal point Positive integers are converted to an unsigned hex value with a maximum value of 4294967295 or 0xF...

Page 69: ...ruct a mask by using bitwise NOT on ReadOnlyFlag In the mask every bit is a 1 except for the read only flag Then use bitwise AND with the mask to clear the read only flag The following code constructs...

Page 70: ...cription Operator adds numeric expressions or concatenates combines strings If one expression is a string all other expressions are converted to strings and concatenated If both expressions are intege...

Page 71: ...hem var oldBalance Number 1345 23 var currentBalance deposit_txt text oldBalance trace currentBalance For example if a user enters 475 in the deposit text field the trace statement sends the value 475...

Page 72: ...x x y This operator also performs string concatenation All the rules of the addition operator apply to the addition assignment operator For more information see Operator precedence and associativity...

Page 73: ...pression1 expression2 A number or string Returns A Boolean value Description Operator comparison compares two expressions and determines whether expression1 is less than expression2 if so the operator...

Page 74: ...er than the maximum have their most significant digits discarded when they are converted so the value is still 32 bit Negative numbers are converted to an unsigned hex value via the two s complement n...

Page 75: ...t the bits have been pushed two spaces to the left 2 binary 0010 8 binary 1000 trace 2 2 output 8 See also bitwise right shift and assignment bitwise right shift bitwise left shift and assignment bitw...

Page 76: ...performs a bitwise left shift operation 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 assoc...

Page 77: ...pression1 expression2 A number or string Returns A Boolean value Description Operator comparison compares two expressions and determines whether expression1 is less than or equal to expression2 if it...

Page 78: ...er on the right to the variable array element or property in expression1 Assignment can be either by value or by reference Assignment by value copies the actual value of expression2 and stores it in e...

Page 79: ...ne Assignment by value is then used to assign the value of 49528 to the size property of the myObject object var mercury Object new Object mercury diameter 3030 in miles trace mercury diameter output...

Page 80: ...he following two statements 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 associativi...

Page 81: ...s are compared by reference Two such variables are 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...

Page 82: ...d example creates the thirdArray variable which points to the same array as the variable firstArray The equality operator will return true for these two arrays because the two variables refer to the s...

Page 83: ...ical Variables representing objects arrays and functions are compared by reference Two such variables are equal if they refer to the same object array or function Two separate arrays are never conside...

Page 84: ...avoid the use of the new operator with the String class Create a string variable using a literal value var str String asdf Create a variable that is a reference var stringRef String new String asdf T...

Page 85: ...Parameters expression1 expression2 A number or string Returns A Boolean value Description Operator comparison compares two expressions and determines whether expression1 is greater than expression2 if...

Page 86: ...Flash 4 file x y Converted Flash 5 or later file Number x Number y Usage expression1 expression2 Parameters expression1 expression2 A string integer or floating point number Returns A Boolean value De...

Page 87: ...rted to an unsigned hex value with a maximum value of 4294967295 or 0xFFFFFFFF values larger than the maximum have their most significant digits discarded when they are converted so the value is still...

Page 88: ...ious 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 significant bit farthest to the right to...

Page 89: ...ivalent A B A A B For more information see Operator precedence and associativity in Using ActionScript in Flash Example The following commented code uses the bitwise right shift and assignment operato...

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

Page 91: ...ssion that converts to an integer from 0 to 31 Returns A 32 bit integer Description Operator bitwise compound assignment performs an unsigned bitwise right shift operation and stores the contents as a...

Page 92: ...get and set accessible properties for a specific object such as a button movie clip or text field use the _accProps property To determine whether the player is running in an environment that supports...

Page 93: ...within one or two seconds of the first appearance of the Flash window in which your document is playing you might get a return value of false even if there is an active Microsoft Active Accessibility...

Page 94: ...dify the accessibility properties for multiple objects only one call to Accessibility updateProperties is necessary multiple calls can result in reduced performance and unintelligible screen reader re...

Page 95: ...l see The Flash Accessibility panel in Using Flash To determine whether the player is running in an environment that supports accessibility aids use System capabilities hasAccessibility The following...

Page 96: ...ps name Pet Store Accessibility updateProperties In contrast the following code sets the name property for a movie clip with the instance name price_mc to the string Price price_mc _accProps name Pric...

Page 97: ...other code here delete my_mc _accProps silent revert to default value The value of _accProps must be an object This means that if no _accProps object already exists you must create one before you can...

Page 98: ...ion is called in ActionScript an arguments object is automatically created for that function A local variable arguments is also created and lets you refer to the arguments object Property summary for...

Page 99: ...can use the arguments callee property to make an anonymous function that is recursive as shown in the following example factorial function x Number if x 1 return 1 else return x arguments callee x 1 t...

Page 100: ...lowing example defines two functions a caller function named function1 which calls a another function named function2 define the caller function named function1 var function1 Function function functio...

Page 101: ...param_arg2 String param_arg3 String return 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 followin...

Page 102: ...ing the array s index 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...

Page 103: ...for the Array class Method 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 elem...

Page 104: ...different types 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 param...

Page 105: ...ments The initial elements of the go_gos_array array are identified as shown in the following example go_gos_array 0 Belinda go_gos_array 1 Gina go_gos_array 2 Kathy go_gos_array 3 Charlotte go_gos_ar...

Page 106: ...Array new Array a b c var numeric_array Array new Array 1 2 3 var alphaNumeric_array Array alpha_array concat numeric_array trace alphaNumeric_array creates array a b c 1 2 3 The following code concat...

Page 107: ...rray with three elements Earth Moon and Sun It then joins the array three times first using the default separator a comma and a space then using a dash and then using a plus sign var a_array Array new...

Page 108: ...roperty that is shorter than the existing length the array will be truncated Example The following code explains how the length property is updated var my_array Array new Array trace my_array length i...

Page 109: ...e last element from an array and returns the value of that element Example The following code creates the myPets_array array containing four elements and then removes its last element var myPets_array...

Page 110: ...an array and returns the array s new length Example The following example creates the array myPets_array with two elements cat and dog The second line adds two elements to the array Because the push...

Page 111: ...None Returns Nothing Description Method reverses the array in place Example The following example uses this method to reverse the array numbers_array var numbers_array Array new Array 1 2 3 4 5 6 trac...

Page 112: ...irst element from an array and returns that element Example The following code creates the array myPets_array and then removes the first element from the array and assigns it to the variable shifted v...

Page 113: ...you don t pass any parameters a duplicate of my_array is created Example The following example creates an array of five pets and uses slice to populate a new array comprising only four legged pets var...

Page 114: ...alues are acceptable for option 1 or Array CASEINSENSITIVE 2 or Array DESCENDING 4 or Array UNIQUESORT 8 or Array RETURNINDEXEDARRAY 16 or Array NUMERIC For information on this parameter see Array sor...

Page 115: ...e Usage 1 The following example shows the use of Array sort with and without a value passed for option var fruits_array Array new Array oranges apples strawberries pineapples cherries trace fruits_arr...

Page 116: ...116 Chapter 2 ActionScript Language Reference trace Sorted displays Sorted trace passwords_array displays ana ring anne home jay mag mom glam regina silly See also bitwise OR Array sortOn...

Page 117: ...t each option see Description on page 117 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 118: ...wise OR operator or add the values of the flags together The following code shows three ways to specify a numeric descending sort my_array sortOn someFieldName 2 16 my_array sortOn someFieldName 18 my...

Page 119: ...2 age 35 my_array 3 age 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...

Page 120: ...y push name john city omaha zip 68144 rec_array push name john city kansas city zip 72345 rec_array push name bob city omaha zip 94010 for i 0 i rec_array length i trace rec_array i name rec_array i c...

Page 121: ...ents that were removed from the array Description Method adds and removes elements from an array This method modifies the array without making a copy Example The following example creates an array and...

Page 122: ...mber 0 for the deleteCount parameter and the string chair for the value parameter This does not remove anything from the original array and adds the string chair at index 1 var myFurniture_array Array...

Page 123: ...ndex my_array length 1 is converted to a concatenated string and separated by commas To specify a custom separator use Array join Example The following example creates my_array and converts it to a st...

Page 124: ...the beginning of the array Returns An integer representing the new length of the array Description Method adds one or more elements to the beginning of an array and returns the array s new length Exam...

Page 125: ...owing 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 playMP3 fun...

Page 126: ...published for Flash Player 7 or later the result is true if the string has a length greater than zero the value is false for an empty string If expression is undefined or NaN not a number the return...

Page 127: ...This example shows a significant difference between use of the Boolean function and the Boolean class The Boolean function creates a Boolean value and the Boolean class creates a Boolean object Boolea...

Page 128: ...y Flash Player 5 Usage new Boolean x Boolean Parameters x Any expression This parameter is optional Returns A reference to a Boolean object Description Constructor creates a Boolean object If you omit...

Page 129: ...od returns the string representation true or false of the Boolean object Example This example creates a variable of type Boolean and uses toString to convert the value to a string for use in the trace...

Page 130: ...A Boolean value Description Method returns true if the primitive value type of the specified Boolean object is true false otherwise Example The following example shows how this method works and also...

Page 131: ...e 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 break statement onl...

Page 132: ...132 Chapter 2 ActionScript Language Reference See also for for in do while while switch case continue throw try catch finally...

Page 133: ...s has a yellow rectangle around it Button _height The height of a button instance in pixels Button _quality The level of anti aliasing applied to the current SWF file Button menu A reference to an ass...

Page 134: ...ically scaling a button instance Event handler Description Button onDragOut Invoked when the mouse button is pressed over the button and the pointer then rolls outside the button Button onDragOver Inv...

Page 135: ...lue is 100 Objects in a button with _alpha set to 0 are active even though they are invisible Example The following code sets the _alpha property of a button named myBtn_btn to 50 when the user clicks...

Page 136: ...ked and the page cannot be reloaded Example The following example demonstrates how you can disable and enable buttons from being clicked Two buttons myBtn1_btn and myBtn2_btn are on the Stage and the...

Page 137: ...property controls the global _focusrect property It is a Boolean value This behavior was changed in Flash Player 6 and later to permit customizing the _focusrect property on an individual movie clip...

Page 138: ...pth You might notice that two of these buttons have the same depth value one in the main SWF file and one in the loaded SWF file This is misleading because buttonMovie swf was loaded at depth 999 whic...

Page 139: ...lash Player 6 Usage my_btn _height Number Description Property the height of the button in pixels Example The following example sets the height and width of a button called my_btn to a specified width...

Page 140: ...ed myBtn_btn The ContextMenu object contains a single menu item labeled Save with an associated callback handler function named doSave Add the button instance to the Stage and name it myBtn_btn var me...

Page 141: ...tn _name String Description Property instance name of the button specified by my_btn Example The following example traces all instance names of any Button instances within the current Timeline of a SW...

Page 142: ...ton and the pointer then dragged outside of the button You must define a function that executes when the event handler is invoked Example The following example demonstrates how you can execute stateme...

Page 143: ...d Example The following example defines a function for the onDragOver handler that sends a trace statement to the Output panel Create a button called my_btn on the Stage and enter the following Action...

Page 144: ...the Output panel is defined for the onKeyDown handler Create a button called my_btn on the Stage and enter the following ActionScript in a frame on the Timeline my_btn onKeyDown function trace onKeyDo...

Page 145: ...Button onKeyDown 145 See also Button onKeyUp...

Page 146: ...efine a function that executes when the event handler is invoked Example In the following example a function that sends text to the Output panel is defined for the onKeyDown handler Create a button ca...

Page 147: ...u select Control Disable Keyboard Shortcuts in the test environment Then press the Tab key until the button has focus a yellow rectangle appears around the my_btn instance and start pressing keys on y...

Page 148: ...newFocus contains the value null Example The following example demonstrates how statements can be executed when a button loses focus Create a button instance on the Stage called my_btn and add the fo...

Page 149: ...None Returns Nothing Description Event handler invoked when a button is pressed You must define a function that executes when the event handler is invoked Example In the following example a function...

Page 150: ...e Parameters None Returns Nothing Description Event handler invoked when a button is released You must define a function that executes when the event handler is invoked Example In the following exampl...

Page 151: ...when the mouse is released while the pointer is outside the button after the button is pressed while the pointer is inside the button You must define a function that executes when the event handler i...

Page 152: ...rs None Returns Nothing Description Event handler invoked when the pointer moves outside a button area You must define a function that executes when the event handler is invoked Example In the followi...

Page 153: ...urns Nothing Description Event handler invoked when the pointer moves over a button area You must define a function that executes when the event handler is invoked Example In the following example a f...

Page 154: ...nstance If there is no previously focused object oldFocus contains a null value Example The following example demonstrates how you can execute statements when the user of a SWF file moves focus from o...

Page 155: ...specify a relative path to movie clips or objects that are above the current movie clip or object You can use _parent to move up multiple levels in the display list as in the following this _parent _p...

Page 156: ...d using a 2 x 2 pixel grid but bitmaps are not smoothed This is suitable for movies that do not contain text HIGH High rendering quality Graphics are anti aliased using a 4 x 4 pixel grid and bitmaps...

Page 157: ...le rotates two buttons on the Stage Create two buttons on the Stage called control_btn and my_btn Make sure that my_btn is not perfectly round so you can see it rotating Then enter the following Actio...

Page 158: ...Description Property global an integer that specifies the number of seconds a sound prebuffers before it starts to stream Note Although you can specify this property for a Button object it is actuall...

Page 159: ...ript is used to set the tabEnabled property for one of four buttons to false However all four buttons one_btn two_btn three_btn and four_btn are placed in a custom tab order using tabIndex Although ta...

Page 160: ...ention 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 the tab order is determined by the orde...

Page 161: ...ve the new movie clip an instance name my_mc Delete the existing ActionScript in Frame 1 of the Timeline and replace it with my_mc my_btn onRelease function trace this _target displays my_mc my_btn To...

Page 162: ...trackAsMenu property at any time the modified button immediately takes on the new behavior Example The following example demonstrates how to track two buttons as a menu Place two button instances on t...

Page 163: ...Script in Frame 1 of the Timeline var one_btn Button var two_btn Button this createTextField output_txt 999 0 0 100 22 output_txt autoSize true one_btn onRelease function trace clicked one_btn trace t...

Page 164: ...r property at any time the modified button immediately takes on the new cursor behavior The useHandCursor property can be read out of a prototype object Example Create two buttons on the Stage with th...

Page 165: ...ty set to false are disabled Example Create two buttons on the Stage with the instance names myBtn1_btn and myBtn2_btn Enter the following ActionScript in Frame 1 of the Timeline myBtn1_btn onRelease...

Page 166: ...tion Property the width of the button in pixels Example The following example increases the width property of a button called my_btn and displays the width in the Output panel Enter the following Acti...

Page 167: ...clip that has transformations the button is in the local coordinate system of the enclosing movie clip Thus for a movie clip rotated 90 counterclockwise the enclosed button inherits a coordinate syst...

Page 168: ...following ActionScript in Frame 1 of the Timeline this createTextField mouse_txt 999 5 5 150 40 mouse_txt html true mouse_txt wordWrap true mouse_txt border true mouse_txt autoSize true mouse_txt sele...

Page 169: ...y property settings which are defined in pixels For example if the parent movie clip is scaled to 50 setting the _x property moves an object in the button by half the number of pixels that it would if...

Page 170: ...r movie clip that has transformations the button is in the local coordinate system of the enclosing movie clip Thus for a movie clip rotated 90 counterclockwise the enclosed button inherits a coordina...

Page 171: ...ionScript in Frame 1 of the Timeline this createTextField mouse_txt 999 5 5 150 40 mouse_txt html true mouse_txt wordWrap true mouse_txt border true mouse_txt autoSize true mouse_txt selectable false...

Page 172: ...registration point of the button expressed as a percentage The default registration point is 0 0 Example The following example scales a button called my_btn When you click and release the button it gr...

Page 173: ...amera 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 aspects of the c...

Page 174: ...ied access to the camera Camera name The name of the camera as specified by the camera hardware Camera names Class property in an array of strings reflecting the names of all available video capture d...

Page 175: ...mount of motion the camera detects using the activityLevel property The following example detects the amount of motion the camera detects using the activityLevel property and a ProgressBar instance Cr...

Page 176: ...instance name my_video Add a NumericStepper component instance to the Stage and give it the instance name bandwidth_nstep Then add the following ActionScript to Frame 1 of the Timeline var bandwidth_...

Page 177: ...rames per second that the camera captures data using the currentFps property and a ProgressBar instance Create a new video instance by selecting New Video from the Library options menu Add an instance...

Page 178: ...rate in frames per second that the camera captures data using the currentFps property and a ProgressBar instance Create a new video instance by selecting New Video from the Library options menu Add an...

Page 179: ...bjects that you create using the new constructor multiple calls to Camera get reference the same camera Thus if your script contains the lines first_cam Camera get and second_cam Camera get both first...

Page 180: ...ra get is called This is helpful if a user has forgotten to connect the camera if your SWF file provides a Try Again button that calls Camera get Flash can find the camera without the user having to r...

Page 181: ...ptions menu Add an instance to the Stage and give it the instance name my_video Add a Label component instance to the Stage and give it the instance name dimensions_lbl Then add the following ActionSc...

Page 182: ..._video Add a Label component instance to the Stage and give it the instance name camera_lbl Then add the following ActionScript to Frame 1 of the Timeline var camera_lbl mx controls Label var my_cam C...

Page 183: ...t the instance name motionLevel_lbl a NumericStepper with the instance name motionLevel_nstep and a ProgressBar with the instance name motion_pb Then add the following ActionScript to Frame 1 of the T...

Page 184: ...m onActivity function isActive Boolean If isActive equals true set the themeColor variable to haloGreen Otherwise set the themeColor to haloOrange var themeColor String isActive haloGreen haloOrange m...

Page 185: ...it the instance name motionLevel_lbl a NumericStepper with the instance name motionTimeOut_nstep and a ProgressBar with the instance name motion_pb Then add the following ActionScript to Frame 1 of t...

Page 186: ...186 Chapter 2 ActionScript Language Reference See also Camera onActivity Camera setMotionLevel...

Page 187: ...my_cam muted evaluates to true Create a new video instance by selecting New Video from the Library options menu Add an instance to the Stage and give it the instance name my_video Then add the followi...

Page 188: ...ows this name is the same as the device name listed in the Scanners and Cameras Control Panel Create a new video instance by selecting New Video from the Library options menu Add an instance to the St...

Page 189: ...see the Array class entry Calling the Camera names property requires an extensive examination of the hardware and it may take several seconds to build the array In most cases you can just use the def...

Page 190: ...you must create a function to process its activity value To specify the amount of motion required to invoke Camera onActivity true and the amount of time that must elapse without activity before invo...

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

Page 192: ...192 Chapter 2 ActionScript Language Reference trace Camera access granted break See also Camera get Camera muted System showSettings System onStatus...

Page 193: ...pper instance to specify the amount of compression applied to the camera feed Create a new video instance by selecting New Video from the Library options menu Add an instance to the Stage and give it...

Page 194: ...ameter This parameter is optional Returns Nothing Description Method sets the camera capture mode to the native mode that best meets the specified requirements If the camera does not have a native mod...

Page 195: ...tInput component instance with the instance name fps_ti Then add the following ActionScript to Frame 1 of the Timeline var my_cam Camera Camera get var my_video Video my_video attachVideo my_cam fps_t...

Page 196: ...o prevent the camera from detecting motion at all pass a value of 100 for sensitivity Camera onActivity is never invoked You would probably use this value only for testing purposes for example to temp...

Page 197: ...r number to see how different values affect motion detection Assumes a Video object named myVideoObject is on the Stage active_cam Camera get x 0 function motion mode trace x mode x active_cam onActiv...

Page 198: ...is generally applicable only if you are transmitting video using Flash Communication Server Use this method to specify which element of the outgoing video feed is more important to your application b...

Page 199: ...more than 8192 8K second is used to send video active_cam setQuality 8192 0 Ensure that no more than 8192 8K second is used to send video with a minimum quality of 50 active_cam setQuality 8192 50 En...

Page 200: ...om the Library options menu Add an instance to the Stage and give it the instance name my_video Add a Label component instance to the Stage and give it the instance name dimensions_lbl Then add the fo...

Page 201: ...de 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 from the statement...

Page 202: ...202 Chapter 2 ActionScript Language Reference See also break default strict equality switch...

Page 203: ...e class must match the name of the external file that contains the class The name of the external file must be the name of the class with the file extension as appended For example if you name a class...

Page 204: ...ng var bloomSeason String Following line is constructor because it has the same name as the class function Plant param_leafType String param_bloomSeason String Assign passed values to properties when...

Page 205: ...use the new operator to create a ImageLoader object var jakob_mc MovieClip this createEmptyMovieClip jakob_mc this getNextHighestDepth var jakob ImageLoader new ImageLoader http www macromedia com de...

Page 206: ...setInterval Example 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 c...

Page 207: ...ctor 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 Example The fo...

Page 208: ...ast setRGB call Example The following code retrieves the RGB value for the Color object my_color converts the value to a hexadecimal string and assigns it to the myValue variable To see this code work...

Page 209: ...ransform object and then sets new percentages for colors and alpha of my_mc relative to their current values To see this code work place a multicolored movie clip on the Stage with the instance name m...

Page 210: ...the number is a hexadecimal value Description Method specifies an RGB color for a Color object Calling this method overrides any previous Color setTransform settings Returns Nothing Example This exam...

Page 211: ...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 212: ...ent place it on Frame 1 on the main Timeline and place a movie clip on the Stage with the instance name my_mc as in the following code Create a color object called my_color for the target my_mc var my...

Page 213: ...ard menu which appears when you right click in Flash Player the edit menu which appears when you right click over a selectable or editable text field and an error menu which appears when a SWF file ha...

Page 214: ...tate 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 Ex...

Page 215: ...andler obj menuObj if showItem false menuObj customItems 0 enabled false else menuObj customItems 0 enabled true function itemHandler obj item put code here trace selected this menu my_cm When the use...

Page 216: ...s example the built in Quality and Print menu items are disabled for the ContextMenu object my_cm which is attached to the current Timeline of the SWF file var my_cm ContextMenu new ContextMenu my_cm...

Page 217: ...enu 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 my_cm ContextMenu new ContextMenu my_cm h...

Page 218: ...or more information about creating new menu items see the ContextMenuItem class entry Example The following example creates a new custom menu item called menuItem_cm with a caption of Send e mail and...

Page 219: ...it does not affect items that appear in the edit or error menus For more information about the different menu types see the ContextMenu class entry This method works by setting all the Boolean members...

Page 220: ...ler called when a user invokes the Flash Player context menu but before the menu is actually displayed This lets you customize the contents of the context menu based on the current application state Y...

Page 221: ...lines 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 whether the mat...

Page 222: ...he default 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...

Page 223: ...ption text displayed in the context menu Example The following example displays the caption for the selected menu item Pause Game in the Output panel var my_cm ContextMenu new ContextMenu var menuItem...

Page 224: ...creates a new ContextMenuItem object named original_cmi with the caption Pause and a callback handler set to the function onPause The example then creates a copy of the ContextMenuItem object and ass...

Page 225: ...ber 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 ContextMenu var startMenuItem...

Page 226: ...ndler receives 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 s...

Page 227: ...n Save and Print A separator bar divides the Save and Print items The menu items are then added to the ContextMenu object s customItems array Finally the menu is attached to the current Timeline of th...

Page 228: ...n Stop is selected the number of milliseconds that have elapsed since the SWF file started is displayed The Start menu item is made visible and the Stop menu item is made invisible var my_cm ContextMe...

Page 229: ...le In the following while loop continue causes the Flash interpreter to skip the rest of the loop body and jump to the top of the loop where the condition is tested trace example 1 var i Number 0 whil...

Page 230: ...uals 0 then the trace i statement is skipped trace example 3 for var i 0 i 10 i if i 3 0 continue trace i In the following for in loop continue causes the Flash interpreter to skip the rest of the loo...

Page 231: ...e methods to build SWF files that are extensions of the Flash authoring tool Such an extension could for example use the Flash Application Protocol to navigate a UDDI repository and download web servi...

Page 232: ...ter is located it is read in its entirety and returned as a string Example The following example lists the custom actions in a ComboBox instance and gets the custom action when a Button instance is cl...

Page 233: ...finition file must be a simple filename without the xml file extension and without any directory separators or If a custom actions file already exists with the name customName it is overwritten If the...

Page 234: ...trace success CustomActions install dogclass this firstChild trace CustomActions list my_xml load dogclass xml Select Control Test Movie and if the XML loads successfully you will see true and an arra...

Page 235: ...a ComboBox instance and gets the custom action when a Button instance is clicked Drag an instance of a ComboBox Button and TextArea onto the Stage Give the ComboBox an instance name of customActionNam...

Page 236: ...ample installs a new custom action and displays an array containing the names of all the custom actions that are registered with the Flash authoring tool in the Output panel When the uninstall_btn is...

Page 237: ...matically adjusts its output for daylight saving time The time zone information database in Mac OS X is used to determine whether any date or time in the present or past should have a daylight saving...

Page 238: ...onth Returns the month according to universal time Date getUTCSeconds Returns the seconds according to universal time Date getYear Returns the year according to local time Date setDate Sets the day of...

Page 239: ...s parameter is optional Returns A reference to a Date object Date setUTCHours Sets the hour according to universal time Returns the new time in milliseconds Date setUTCMilliseconds Sets the millisecon...

Page 240: ...ew Date object for Mary s birthday August 12 1974 because the month parameter is zero based the example uses 7 for the month not 8 var maryBirthday Date new Date 74 7 12 The following example creates...

Page 241: ...ording to local time Local time is determined by the operating system on which Flash Player is running Example The following example creates a new Date object and concatenates the returned values of D...

Page 242: ...and so on of the specified Date object according to local time Local time is determined by the operating system on which Flash Player is running Example The following example creates a new Date object...

Page 243: ...number such as 2000 of the specified Date object according to local time Local time is determined by the operating system on which Flash Player is running Example The following example uses the constr...

Page 244: ...s running Example The following example uses the constructor to create a Date object based on the current time and uses the getHours method to display hour values from that object var my_date Date new...

Page 245: ...eger from 0 to 999 of the specified Date object according to local time Local time is determined by the operating system on which Flash Player is running Example The following example uses the constru...

Page 246: ...utes an integer from 0 to 59 of the specified Date object according to local time Local time is determined by the operating system on which Flash Player is running Example The following example uses t...

Page 247: ...urrent time and uses the getMonth method to return the month value from that object var my_date Date new Date trace my_date getMonth The following example uses the constructor to create a Date object...

Page 248: ...onds an integer from 0 to 59 of the specified Date object according to local time Local time is determined by the operating system on which Flash Player is running Example The following example uses t...

Page 249: ...ary 1 1970 universal time for the specified Date object Use this method to represent a specific instant in time when comparing two or more Date objects Example The following example uses the construct...

Page 250: ...following example returns the difference between the local daylight saving time for San Francisco and universal time Daylight saving time is factored into the returned result only if the date defined...

Page 251: ...o 31 in the specified Date object according to universal time Example The following example creates a new Date object and uses Date getUTCDate and Date getDate The value returned by Date getUTCDate ca...

Page 252: ...object according to universal time Example The following example creates a new Date object and uses Date getUTCDay and Date getDay The value returned by Date getUTCDay can differ from the value retur...

Page 253: ...owing example creates a new Date object and uses Date getUTCFullYear and Date getFullYear The value returned by Date getUTCFullYear may differ from the value returned by Date getFullYear if today s da...

Page 254: ...ording to universal time Example The following example creates a new Date object and uses Date getUTCHours and Date getHours The value returned by Date getUTCHours may differ from the value returned b...

Page 255: ...s An integer Description Method returns the milliseconds an integer from 0 to 999 of the specified Date object according to universal time Example The following example creates a new Date object and u...

Page 256: ...ers 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 The following example creates a new Date obj...

Page 257: ...following example creates a new Date object and uses Date getUTCMonth and Date getMonth The value returned by Date getUTCMonth can differ from the value returned by Date getMonth if today s date is t...

Page 258: ...ers None Returns An integer Description Method returns the seconds an integer from 0 to 59 of the specified Date object according to universal time Example The following example creates a new Date obj...

Page 259: ...the operating system on which Flash Player is running The year is the full year minus 1900 For example the year 2000 is represented as 100 Example The following example creates a Date object with the...

Page 260: ...te object according to local time and returns the new time in milliseconds Local time is determined by the operating system on which Flash Player is running Example The following example initially cre...

Page 261: ...to local time and returns the new time in milliseconds If the month and date parameters are specified they are set to local time Local time is determined by the operating system on which Flash Player...

Page 262: ...te object according to local time and returns the new time in milliseconds Local time is determined by the operating system on which Flash Player is running Example The following example initially cre...

Page 263: ...turns the new time in milliseconds Local time is determined by the operating system on which Flash Player is running Example The following example initially creates a new Date object setting the date...

Page 264: ...t according to local time and returns the new time in milliseconds Local time is determined by the operating system on which Flash Player is running Example The following example initially creates a n...

Page 265: ...thod sets the month 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 f...

Page 266: ...bject 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 following example initially creates a new Dat...

Page 267: ...Example The following example initially creates a new Date object setting the time and date to 8 00 a m on May 15 2004 and uses Date setTime to change the time to 8 30 a m var my_date Date new Date 2...

Page 268: ...seconds 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 week changes as a result of callin...

Page 269: ...ds Optionally this method can also set the month and date represented by the specified Date object Calling this method does not modify the other fields of the specified Date object but Date getUTCDay...

Page 270: ...to 999 This parameter is optional Returns An integer Description Method sets the hour for the specified Date object in universal time and returns the new time in milliseconds Example The following ex...

Page 271: ...ed Date object in universal time and returns the new time in milliseconds Example The following example initially creates a new Date object setting the date to 8 30 a m on May 15 2004 with the millise...

Page 272: ...om 0 to 999 This parameter is optional Returns An integer Description Method sets the minute for the specified Date object in universal time and returns the new time in milliseconds Example The follow...

Page 273: ...d returns the new time in milliseconds Calling this method does not modify the other fields of the specified Date object but Date getUTCDay and Date getDay might report a new value if the day of the w...

Page 274: ...Returns An integer Description Method sets the seconds for the specified Date object in universal time and returns the new time in milliseconds Example The following example initially creates a new Da...

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

Page 276: ...Example The following example returns the information in the dateOfBirth_date Date object as a string var dateOfBirth_date Date new Date 74 7 12 18 15 trace dateOfBirth_date trace dateOfBirth_date toS...

Page 277: ...tion Method returns the number of milliseconds between midnight on January 1 1970 universal time and the time specified in the parameters This is a static method that is invoked through the Date objec...

Page 278: ...ave 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 compile...

Page 279: ...ally 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...

Page 280: ...defined 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 r...

Page 281: ...e 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...

Page 282: ...282 Chapter 2 ActionScript Language Reference See also break continue while...

Page 283: ...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 following exa...

Page 284: ...unctions however can still be type checked for return type and parameter types This behavior is especially useful when you work with MovieClip objects because there are many different ways of adding p...

Page 285: ...aig 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 Pe...

Page 286: ...curly braces used to 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 u...

Page 287: ...dition 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 curly braces and run...

Page 288: ...Flash Player 6 Usage endinitclip Parameters None Returns Nothing Description Compiler directive indicates the end of a block of initialization actions Example initclip initialization actions go here e...

Page 289: ...eters 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 its...

Page 290: ...hapter 2 ActionScript Language Reference throw new Error Strings to not match try compareStrings Dog dog output Strings to not match catch e_err Error trace e_err toString See also throw try catch fin...

Page 291: ...numbers can be divided SUCCESS and the number are shown Specific errors are shown if you try to divide by 0 or enter only 1 parameter function divideNum num1 Number num2 Number Number if isNaN num1 is...

Page 292: ...ror divideNum function requires two numeric parameters else if denominator 0 throw new DivideByZeroError return numerator denominator try var theNum Number divideNumber 1 0 trace SUCCESS theNum output...

Page 293: ...ined Example In the following example a function throws an error with a specified message if the two strings that are passed to it are not identical function compareStrings str1_str String str2_str St...

Page 294: ...symbol is used to introduce escape characters and is not equivalent to the modulo operator Example The following code produces the result someuser 40somedomain 2Ecom var email String someuser somedoma...

Page 295: ...named in expression cannot be found undefined is returned In Flash 4 eval was used to simulate arrays in Flash 5 or later you should use the Array class to simulate arrays In Flash 4 you can also use...

Page 296: ...296 Chapter 2 ActionScript Language Reference You can also use the following ActionScript for var i 1 i 3 i this square i _mc _rotation 5 See also Array class set variable...

Page 297: ...The subclass inherits all the methods properties functions and so on that are defined in the superclass For more information see Creating subclasses in Using ActionScript in Flash Interfaces can also...

Page 298: ...var fullSizeSpare Boolean function Car param_numDoors Number param_color String param_fullSizeSpare Boolean this numDoors param_numDoors this color param_color this fullSizeSpare param_fullSizeSpare f...

Page 299: ...rts false to a string it becomes false For more information see Automatic data typing in Using ActionScript in Flash Example This example shows how automatic data typing converts false to a number and...

Page 300: ...Manager overrides Flash Player s focus handling including use of this global property Example The following example demonstrates how to hide the yellow rectangle around any instances in a SWF file whe...

Page 301: ...nd then starts a looping sequence The looping sequence begins by evaluating the condition expression If the condition expression evaluates to true statement is executed and the next expression is eval...

Page 302: ...Reference The following example shows that curly braces are not necessary if only one statement will execute var sum Number 0 for var i Number 1 i 100 i sum i trace sum output 5050 See also increment...

Page 303: ...Properties of the object are enumerated first then properties of its immediate prototype then properties of the prototype s prototype and so on The for in statement does not enumerate the same propert...

Page 304: ...s the typeof operator with for in to iterate over a particular type of child for var name in this if typeof this name movieclip trace I have a movie clip child named name Note If you have several movi...

Page 305: ...the command and parameters parameters of the fscommand function to control a SWF file playing in Flash Player including projectors Command Parameters Purpose quit None Closes the projector fullscreen...

Page 306: ...tion see the Director Support Center at www macromedia com support director Usage 4 In Visual Basic Visual C and other programs that can host ActiveX controls the fscommand function sends a VB event w...

Page 307: ...nd parameters as in the following example fscommand messagebox Hello name welcome to our website To test the SWF file select File Publish Preview HTML Note If you publish your SWF file using the Flash...

Page 308: ...rent parameters to 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...

Page 309: ...is defined and used in the same script the function definition may appear after using the function var y Number sqr 3 trace y output 9 function sqr x Number return Math pow x 2 The following function...

Page 310: ...are represented by Function objects which are instances of the Function class Method summary for the Function class Method Description Function apply Invokes the function represented by a Function ob...

Page 311: ...ed as an Array object unlike Function call which specifies parameters as a comma delimited list This is often useful when the number of parameters to be passed is not known until the script actually e...

Page 312: ...apply var firstArray Array new Array 1 2 3 var secondArray Array new Array a b c use apply to set the value of this to be myObj and send firstArray theFunction apply myObj firstArray output this myOb...

Page 313: ...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 314: ...314 Chapter 2 ActionScript Language Reference var obj Object new myObject myMethod call obj obj The trace statement displays this obj true See also Function apply...

Page 315: ...you have defined in external class files Using implicit get methods lets you access properties of objects without accessing the property directly Implicit get set methods are syntactic shorthand for t...

Page 316: ...t in a frame on the Timeline var giants Team new Team San Fran SFO trace giants name giants name San Francisco trace giants name output San Fran San Francisco When you trace giants name you use the ge...

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

Page 318: ...tion Function returns the number of milliseconds that have elapsed since the SWF file started playing Example In the following example the getTimer and setInterval functions are used to create a simpl...

Page 319: ...les The POST method sends the variables in a separate HTTP header and is used for sending long strings of variables Returns Nothing Description Function loads a document from a specific URL into a win...

Page 320: ...OST for sending variables The following example uses GET to append variables to a URL var firstName String Gus var lastName String Richardson var age Number 92 myBtn_btn onRelease function getURL http...

Page 321: ...he following examples trace the version 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 trac...

Page 322: ...imilar to the Math or Date object Unlike Timeline declared or locally declared variables and functions global variables and functions are visible to every Timeline and scope in the SWF file provided t...

Page 323: ...current scene You can use the scene parameter only on the root Timeline not within Timelines for movie clips or other objects in the document Example In the following example a document has two scene...

Page 324: ...frame in the current scene You can use the scene parameter only on the root Timeline not within Timelines for movie clips or other objects in the document Example In the following example a document...

Page 325: ...ing example the condition inside the parentheses evaluates the variable name to see if it has the literal value Erica If it does the play function inside the curly braces runs if name Erica play The f...

Page 326: ...326 Chapter 2 ActionScript Language Reference else this _parent message_txt text Very good you hit the button in difference seconds See also else...

Page 327: ...ettings dialog box This keyword is supported only when used in external script files not in scripts written in the Actions panel Description Keyword specifies that a class must define all the methods...

Page 328: ...lass files in the package working_directory macr utils users that you want to access you can import them all in a single statement as shown in the following example import macr util users You must iss...

Page 329: ...import 329 For more information on importing see Importing classes and Using packages in Using ActionScript in Flash...

Page 330: ...ss files You can specify no path a relative path or an absolute path for the file to be included If you don t specify a path the AS file must be in one of the following locations The same directory as...

Page 331: ...for a file to be included in your script Note that include statements do not end with a semicolon AS file is in same directory as FLA file or script or is in the global Include directory or the First...

Page 332: ...e Infinity Availability Flash Player 5 Usage Infinity Description Constant specifies the IEEE 754 value representing positive infinity The value of this constant is the same as Number POSITIVE_INFINIT...

Page 333: ...s on Frame 1 of the SWF file Otherwise they execute immediately before the frame actions of the frame that contains the first instance of the associated movie clip symbol Initialization actions execut...

Page 334: ...ngs to a specified 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...

Page 335: ...the interface Only public members are allowed in an interface definition instance and class members are not permitted The get and set statements are not allowed in interface definitions For more infor...

Page 336: ...Number Number return x x function o Void trace o external script or Actions panel 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 implement...

Page 337: ...c keyword was created specifically to enable compile time type checking for built in classes and objects and global variables and functions This keyword was not meant for general purpose use but may b...

Page 338: ...function return 2 this radius this setRadius function param_radius this radius param_radius ActionScript 2 0 code that uses the Circle class var myCircle Circle new Circle 5 trace myCircle getArea tra...

Page 339: ...n Function evaluates expression and returns true if it is a finite number or false if it is infinity or negative infinity The presence of infinity or negative infinity indicates a mathematical error c...

Page 340: ...the isNaN function 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 m...

Page 341: ...ssed Key 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 k...

Page 342: ...for the Right Arrow key 39 Key SHIFT The key code value for the Shift key 16 Key SPACE The key code value for the Spacebar 32 Key TAB The key code value for the Tab key 9 Key UP The key code value fo...

Page 343: ...fines a function for onKeyDown and onKeyUp The last line uses addListener to register the listener with the Key object so that it can receive notification from the key down and key up events var myLis...

Page 344: ...Reference myListener onKeyDown myOnKeyDown Key addListener myListener my_btn onPress myOnPress my_btn _accProps shortcut Ctrl 7 Accessibility updateProperties See also Key getCode Key isDown Key onKey...

Page 345: ...or onKeyDown The last line uses addListener to register the listener with the Key object so that it can receive notification from the key down event var keyListener Object new Object keyListener onKey...

Page 346: ...es addListener to register the listener with the Key object so that it can receive notification from the key down event var keyListener Object new Object keyListener onKeyDown function if Key isDown K...

Page 347: ...about the shortcut available to screen readers see _accProps In this example when you press Control 7 the myOnPress function displays the text hello in the Output panel function myOnPress trace hello...

Page 348: ...NextHighestDepth var mouseListener Object new Object mouseListener onMouseDown function this drawing true canvas_mc moveTo _xmouse _ymouse canvas_mc lineStyle 3 0x99CC00 100 mouseListener onMouseUp fu...

Page 349: ...u 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_o...

Page 350: ...350 Chapter 2 ActionScript Language Reference Key END Availability Flash Player 5 Usage Key END Number Description Property constant associated with the key code value for the End key 35...

Page 351: ...t var DISTANCE Number 5 var keyListener Object new Object keyListener onKeyDown function switch Key getCode case Key LEFT car_mc onEnterFrame function this _x DISTANCE break case Key UP car_mc onEnter...

Page 352: ...isplays information that includes how long it took you to press the key var keyListener Object new Object keyListener onKeyDown function if Key isDown Key ESCAPE get the current timer convert the valu...

Page 353: ...n Flash The keyListener object is then registered to the Key object which broadcasts the onKeyDown message whenever a key is pressed while the SWF file plays var keyListener Object new Object keyListe...

Page 354: ...The keyListener object is then registered to the Key object which broadcasts the onKeyDown message whenever a key is pressed while the SWF file plays var keyListener Object new Object keyListener onKe...

Page 355: ...tes of 0 0 When you press the Home key car_mc returns to 0 0 Create a movie clip that has a linkage ID car_id and add the following ActionScript to Frame 1 of the Timeline this attachMovie car_id car_...

Page 356: ...owing example creates a new listener object and defines a function for onKeyDown The last line uses addListener to register the listener with the Key object so that it can receive notification from th...

Page 357: ...keyboard see Appendix C Keyboard Keys and Key Code Values in Using ActionScript in Flash Returns A Boolean value Description Method returns true if the key specified in keycode is pressed false other...

Page 358: ...responds to the onKeyDown event by calling Key isToggled For more information see Using event listeners in Using ActionScript in Flash The keyListener object is then registered to the Key object whic...

Page 359: ...e true numLock_txt html true var keyListener Object new Object keyListener onKeyDown function capsLock_txt htmlText b Caps Lock b Key isToggled Key CAPSLOCK numLock_txt htmlText b Num Lock b Key isTog...

Page 360: ...und plays when you press the Spacebar Give a sound in the library a linkage identifier of horn_id for this example var DISTANCE Number 10 var horn_sound Sound new Sound horn_sound attachSound horn_id...

Page 361: ...stener with the Key object as shown in the following example var keyListener Object new Object keyListener onKeyDown function trace DOWN Code Key getCode tACSII Key getAscii tKey chr Key getAscii keyL...

Page 362: ...ster the listener with the Key object as shown in the following example var keyListener Object new Object keyListener onKeyDown function trace DOWN Code Key getCode tACSII Key getAscii tKey chr Key ge...

Page 363: ...ode value for the Page Down key 34 Example The following example rotates a movie clip called car_mc when you press the Page Down and Page Up keys var keyListener Object new Object keyListener onKeyDow...

Page 364: ...ed with the key code value for the Page Up key 33 Example The following example rotates a movie clip called car_mc when you press the Page Down and Page Up keys var keyListener Object new Object keyLi...

Page 365: ...ect s listener list the method returns false Description Method removes an object previously registered with Key addListener Example The following example moves a movie clip called car_mc using the Le...

Page 366: ...ound plays when you press the Spacebar Give a sound in the library a linkage identifier of horn_id for this example var DISTANCE Number 10 var horn_sound Sound new Sound horn_sound attachSound horn_id...

Page 367: ...the key code value for the Shift key 16 Example The following example scales car_mc when you press Shift var keyListener Object new Object keyListener onKeyDown function if Key isDown Key SHIFT car_mc...

Page 368: ...d plays when you press the Spacebar Give a sound in the library a linkage identifier of horn_id for this example var DISTANCE Number 10 var horn_sound Sound new Sound horn_sound attachSound horn_id va...

Page 369: ...date in the text field when you press Tab this createTextField date_txt this getNextHighestDepth 0 0 100 22 date_txt autoSize true var keyListener Object new Object keyListener onKeyDown function if...

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

Page 371: ...F file that you load into the Flash Player using loadMovieNum You can assign levels in any order If you assign a level that already contains a SWF file including _level0 the SWF file at that level is...

Page 372: ...ariables Returns Nothing Description Function loads a SWF or JPEG file into Flash Player while the original SWF file plays Tip If you want to monitor the progress of the download use MovieClipLoader l...

Page 373: ...e following loadMovie statement loads the SWF file sub swf from the same directory into a new movie clip called logo_mc that s created using createEmptyMovieClip this createEmptyMovieClip logo_mc 999...

Page 374: ...ile into a level in Flash Player while the originally loaded SWF file plays Tip If you want to monitor the progress of the download use MovieClipLoader loadClip instead of this function Normally Flash...

Page 375: ...Also in both cases the loaded file inherits rotation and scaling and the original content is overwritten in the specified level Use unloadMovieNum to remove SWF files or images that were loaded with l...

Page 376: ...te variables in the active SWF file with new values The text at the specified URL must be in the standard MIME format application x www form urlencoded a standard format used by CGI scripts Any number...

Page 377: ...e in the params txt file named done this createEmptyMovieClip target_mc this getNextHighestDepth loadVariables params txt target_mc function checkParamsLoaded if target_mc done undefined trace not yet...

Page 378: ...vel You can also use this function to update variables in the active SWF file with new values The text at the specified URL must be in the standard MIME format application x www form urlencoded a stan...

Page 379: ...sed to check the progress of the data being loaded into the SWF The script checks for a variable in the params txt file named done loadVariablesNum params txt 2 function checkParamsLoaded if _level2 d...

Page 380: ...Script name and value pairs rather than an XML DOM tree stored in the XML object The LoadVars class follows the same security restrictions as the XML class For information about using the LoadVars cla...

Page 381: ...send and load data Example The following example creates a LoadVars object called my_lv var my_lv LoadVars new LoadVars Property Description LoadVars contentType A string that indicates the MIME type...

Page 382: ...added or changed with this method Accept Ranges Age Allow Allowed Connection Content Length Content Location Content Range ETag Host Last Modified Locations Max Forwards Proxy Authenticate Proxy Autho...

Page 383: ...LoadVars addRequestHeader 383 See also XML addRequestHeader...

Page 384: ...call LoadVars send or LoadVars sendAndLoad The default is application x www form urlencoded Example The following example creates a LoadVars object and displays the default content type of the data th...

Page 385: ...adVars onData event handler Most users do not need to call this method directly If you override the LoadVars onData event handler you can explicitly call LoadVars decode to parse a string of variables...

Page 386: ...l file that resides on your hard disk this example will not work properly because in test movie mode Flash Player loads local files in their entirety To see this code work add a ProgressBar instance c...

Page 387: ...ars load command so that the parameter refers to a valid text file using HTTP If you attempt to use this example to load a local file that resides on your hard disk this example will not work properly...

Page 388: ...388 Chapter 2 my_lv load place a valid URL pointing to a text file here...

Page 389: ...this call A superdomain is derived by removing the left most component of a file s URL For example a SWF file at www someDomain com can load data from sources at store someDomain com because both file...

Page 390: ...and the Macromedia DevNet article Macromedia Flash MX and PHP at www macromedia com devnet mx flash articles flashmx_php html An example is also in the guestbook fla file in the HelpExamples folder Th...

Page 391: ...to false when the operation completes the loaded property is set to true If the operation has not completed or has failed with an error the loaded property remains set to false This property is simila...

Page 392: ...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 server Th...

Page 393: ...ult_ta and a Button instance called submit_button to the Stage When the user clicks the Login button instance in the following example two LoadVars objects are created send_lv and result_lv The send_l...

Page 394: ...e in the HelpExamples folder Typical paths to the HelpExamples folder are Windows Program Files Macromedia Flash MX 2004 Samples HelpExamples Macintosh HD Applications Macromedia Flash MX 2004 Samples...

Page 395: ...This is the same format used by loadVariables The MIME content type sent in the HTTP request headers is the value of my_lv contentType or the default application x www form urlencoded The POST method...

Page 396: ...sed to handle the information For example the script might check if the user got a high score and then insert that data into a database table var my_lv LoadVars new LoadVars my_lv playerName playerNam...

Page 397: ...s are downloaded into targetObject in the same manner as LoadVars load In SWF files running in a version of the player earlier than Flash Player 7 url must be in the same superdomain as the SWF file t...

Page 398: ...to Frame 1 of the Timeline var submitListener Object new Object submitListener click function evt Object var result_lv LoadVars new LoadVars result_lv onLoad function success Boolean if success resul...

Page 399: ...all enumerable variables in my_lv in the MIME content encoding application x www form urlencoded Example The following example instantiates a new LoadVars object creates two properties and uses toStri...

Page 400: ...22 result_txt border true var receiving_lc LocalConnection new LocalConnection receiving_lc methodToExecute function param1 Number param2 Number result_txt text param1 param2 receiving_lc connect lc_...

Page 401: ...methodToExecute function param1 Number param2 Number result_txt text param1 param2 receiving_lc connect lc_name The following SWF file sends the request to the first SWF file Code in the sending SWF...

Page 402: ...402 Chapter 2 ActionScript Language Reference See also LocalConnection connect LocalConnection send...

Page 403: ...gDomain this domain Use LocalConnection allowDomain to explicitly permit LocalConnection objects from specified domains or from any domain to execute methods of the receiving LocalConnection object If...

Page 404: ...he file is completely loaded The best way to determine when a child SWF file finishes loading is to use MovieClipLoader onLoadComplete The opposite situation can also occur You might create a child SW...

Page 405: ...an error break sending_lc send _mylc sayHello name_ti text send_button addEventListener click sendListener In the following example the receiving SWF file which resides in thisDomain com accepts comma...

Page 406: ...by 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...

Page 407: ...7 my_lc allowInsecureDomain function sendingDomain String return sendingDomain this domain my_lc sayHello function name String welcome_txt text Hello name my_lc connect lc_name See also LocalConnectio...

Page 408: ...The following example closes a connection called receiving_lc when you click a Button component instance called close_button this createTextField welcome_txt this getNextHighestDepth 10 10 100 22 this...

Page 409: ...he examples in this section By default Flash Player resolves connectionName into a value of superdomain connectionName where superdomain is the superdomain of the SWF file containing the LocalConnecti...

Page 410: ...rom 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 discu...

Page 411: ...a button called play_btn When you click the button it connects 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 di...

Page 412: ...The most common way to use this command is to include the domain name of the sending LocalConnection object as a parameter to the method you plan to invoke in the receiving LocalConnection object or...

Page 413: ...hat it will accept commands only from SWF files at mydomain com lines 51 to 53 The sending SWF file invokes the aSum method of a connection named mydomain com sum line 68 and passes the following para...

Page 414: ...domain 58 if getVersion 7 this getSWFVersion 7 59 split domain name into elements 60 var domainArray Array channelDomain split if more than two elements are found chop off first element to create supe...

Page 415: ...the method does not exist The only way to know for sure if the method was invoked is to have the receiving object send a reply to the sending object If the information object returned by this event ha...

Page 416: ...ct Object switch infoObject level case status status_ta text LocalConnection connected successfully break case error status_ta text LocalConnection encountered an error break sending_lc send lc_name s...

Page 417: ...onnection connect connectionName command the receiving LocalConnection object The object used with this command is called the sending LocalConnection object The SWF files that contain the sending and...

Page 418: ...connectionName in the receiving LocalConnection object you can only do this in the sending LocalConnection object Example For an example of communicating between LocalConnection objects located in the...

Page 419: ...alues 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 place of degrees...

Page 420: ...a tangent Property Description Math E Euler s constant and the base of natural logarithms approximately 2 718 Math LN2 The natural logarithm of 2 approximately 0 693 Math LOG2E The base 2 logarithm of...

Page 421: ...Usage Math abs x Number Number Parameters x A number Returns A number Description Method computes and returns an absolute value for the number specified by the parameter x Example The following examp...

Page 422: ...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 423: ...Parameters x A number from 1 0 to 1 0 Returns A number between negative pi divided by 2 and positive pi divided by 2 Description Method computes and returns the arc sine for the number specified in t...

Page 424: ...angent of an angle Returns A number between negative pi divided by 2 and positive pi divided by 2 Description Method computes and returns the value in radians of the angle whose tangent is specified i...

Page 425: ...inate of the point x A number specifying the x coordinate of the point Returns A number Description Method computes and returns the angle of the point y x in radians when measured counterclockwise fro...

Page 426: ...that Flash Player 5 supports Usage Math ceil x Number Number Parameters x A number or expression Returns An integer that is both closest to and greater than or equal to parameter x Description Method...

Page 427: ...e 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 419 of the Mat...

Page 428: ...ue of e is 2 71828182845905 Example This example shows how Math E is used to compute continuously compounded interest for a simple case of 100 percent interest over a one year period var principal Num...

Page 429: ...ts Usage Math exp x Number Number Parameters x The exponent a number or expression Returns A number Description Method returns the value of the base of the natural logarithm e to the power of the expo...

Page 430: ...ports 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 returns the floor of the...

Page 431: ...ctions that Flash Player 5 supports Usage Math log x Number Number Parameters x A number or expression with a value greater than 0 Returns The logarithm of parameter x Description Method returns the l...

Page 432: ...operties 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 LN2 Number Description Constant a m...

Page 433: ...nd might not be as accurate as the non emulated math functions that Flash Player 5 supports Usage Math LN10 Number Description Constant a mathematical constant for the natural logarithm of 10 expresse...

Page 434: ...t be as accurate as the non emulated math functions that Flash Player 5 supports Usage Math LOG2E Number Parameters None Returns Nothing Description Constant a mathematical constant for the base 2 log...

Page 435: ...t be as accurate as the non emulated math functions that Flash Player 5 supports Usage Math LOG10E Number Description Constant a mathematical constant for the base 10 logarithm of the constant e Math...

Page 436: ...e Math max x Number y Number Number Parameters x A number or expression y A number or expression Returns A number Description Method evaluates x and y and returns the larger value Example The followin...

Page 437: ...r y Number Number Parameters x A number or expression y A number or expression Returns A number Description Method evaluates x and y and returns the smaller value Example The following example display...

Page 438: ...aws a circle using the mathematical constant pi and the Drawing API drawCircle this 100 100 50 function drawCircle mc MovieClip x Number y Number r Number Void mc lineStyle 2 0xFF0000 100 mc moveTo x...

Page 439: ...Clip canvas_mc this getNextHighestDepth var mouseListener Object new Object mouseListener onMouseDown function this origX _xmouse this origY _ymouse mouseListener onMouseUp function this newX _xmouse...

Page 440: ...dom Number Parameters None Returns A number Description Method returns a pseudo random number n where 0 n 1 The number returned is a pseudo random number because it is not generated by a truly random...

Page 441: ...Description Method rounds the value of the parameter x up or down to the nearest integer and returns the value If parameter x is equidistant from its two nearest integers that is the number ends in 5...

Page 442: ...g example draws a circle using the mathematical constant pi the sine of an angle and the Drawing API drawCircle this 100 100 50 function drawCircle mc MovieClip x Number y Number r Number Void mc line...

Page 443: ...e this createEmptyMovieClip canvas_mc this getNextHighestDepth var mouseListener Object new Object mouseListener onMouseDown function this origX _xmouse this origY _ymouse mouseListener onMouseUp func...

Page 444: ...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 constant for the square...

Page 445: ...approximations and might not be as accurate as the non emulated math functions that Flash Player 5 supports Usage Math SQRT2 Description Constant a mathematical constant for the square root of 2 with...

Page 446: ...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 0xFF0...

Page 447: ...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 microphone shou...

Page 448: ...rophone silenceLevel The amount of sound required to activate the microphone Microphone silenceTimeOut The number of milliseconds between the time the microphone stops detecting sound and Microphone o...

Page 449: ...perty is set to 1 Example The following example displays the activity level of the current microphone in a ProgressBar instance called activityLevel_pb var activityLevel_pb mx controls ProgressBar act...

Page 450: ...gain_pb to display and a NumericStepper instance called gain_nstep to set the microphone s gain value this createEmptyMovieClip sound_mc this getNextHighestDepth var active_mic Microphone Microphone g...

Page 451: ...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 452: ...in use by another application or there are no microphones installed on the system To determine whether any microphones are installed use Microphones names length To display the Flash Player Microphon...

Page 453: ...microphone You can use the ComboBox to switch between the devices var mic_lbl mx controls Label var mic_cb mx controls ComboBox this createEmptyMovieClip sound_mc this getNextHighestDepth var active_...

Page 454: ...specifies whether the user has denied access to the microphone true or allowed access false When this value changes Microphone onStatus is invoked For more information see Microphone get Example This...

Page 455: ...n your computer system including an array of names and the default device var status_ta mx controls TextArea status_ta html false status_ta setStyle fontSize 9 var microphone_array Array Microphone na...

Page 456: ...try Calling Microphone names requires an extensive examination of the hardware and it may take several seconds to build the array In most cases you can just use the default microphone Example The foll...

Page 457: ...ed use Microphone setSilenceLevel Example The following example displays the amount of activity level in a ProgressBar instance called activityLevel_pb When the microphone detects sound it invokes the...

Page 458: ...nd this event handler is invoked with an information object whose code property is Microphone Muted and whose level property is Status To determine whether the user has denied or allowed access to the...

Page 459: ...s a href asfunction System showSettings u infoObj code u a this createTextField status_txt this getNextHighestDepth 0 0 100 22 status_txt html true status_txt autoSize true status_txt htmlText font si...

Page 460: ...rate_cb to change the rate at which your microphone captures sound The current rate displays in a Label instance called rate_lbl this createEmptyMovieClip sound_mc this getNextHighestDepth var active_...

Page 461: ...his setting like a volume knob on a stereo 0 is no volume and 50 is normal volume numbers below 50 specify lower than normal volume while numbers above 50 specify higher than normal volume Example The...

Page 462: ...values 5 8 11 22 or 44 If it is not the value is rounded to the nearest acceptable value that the sound capture device supports active_mic setRate userRate The following example lets you use a ComboB...

Page 463: ...Microphone setRate 463 See also Microphone rate...

Page 464: ...detect when audio levels suggest that a person is talking When someone is not talking bandwidth can be saved because there is no need to send the associated audio stream This information can also be...

Page 465: ...minimum 0 silenceLevel_nstep maximum 100 silenceLevel_nstep value active_mic silenceLevel var nstepListener Object new Object nstepListener change function evt Object active_mic setSilenceLevel evt ta...

Page 466: ...eadset on the same computer If your SWF file allows users to specify the sound output device you may want to call Microphone setUseEchoSuppression true if they indicate they are using speakers and wil...

Page 467: ...crophone setUseEchoSuppression 467 active_mic setUseEchoSuppression evt target selected useEchoSuppression_ch addEventListener click chListener See also Microphone setGain Microphone useEchoSuppressio...

Page 468: ...umericStepper this createEmptyMovieClip sound_mc this getNextHighestDepth var active_mic Microphone Microphone get sound_mc attachAudio active_mic silenceLevel_pb label Activity level 3 silenceLevel_p...

Page 469: ...Microphone silenceLevel 469 See also Microphone gain Microphone setSilenceLevel...

Page 470: ...it displays the activity level of the audio stream var silenceLevel_pb mx controls ProgressBar var silenceTimeOut_nstep mx controls NumericStepper this createEmptyMovieClip sound_mc this getNextHighes...

Page 471: ...Microphone silenceTimeOut 471 silenceLevel_pb label Activity level inactive See also Microphone setSilenceLevel...

Page 472: ...tyLevel_pb displays the current activity level of the audio stream var useEchoSuppression_ch mx controls CheckBox var activityLevel_pb mx controls ProgressBar this createEmptyMovieClip sound_mc this g...

Page 473: ...a user runs a JSAPI script by selecting Commands Run Command However you can use this function in an ActionScript script to call a JSAPI command directly If you use MMExecute in a script on Frame 1 of...

Page 474: ...he bottom of the Window Other Panels menu The ActionScript trace function does not work from a Flash panel this example uses the JavaScript fl trace version to get the output It might be easier to cop...

Page 475: ...for the Mouse class Listener summary for the Mouse class Method Description Mouse addListener Registers an object to receive onMouseDown onMouseMove onMouseWheel and onMouseUp notification Mouse hide...

Page 476: ...useMove onMouseUp or onMouseWheel method invoked Multiple objects can listen for mouse notifications If the listener newListener is already registered no change occurs See also Mouse onMouseDown Mouse...

Page 477: ...e animation fla file in the HelpExamples Folder The following list shows typical paths to the HelpExamples Folder Windows Program Files Macromedia Flash MX 2004 Samples HelpExamples Macintosh HD Appli...

Page 478: ...the cursor_mc movie clip instance to the x and y cursor position Create a movie clip and set its Linkage identifier to cursor_id Add the following ActionScript to Frame 1 of the Timeline to use this...

Page 479: ...following example uses the Drawing API to draw a rectangle whenever the user clicks drags and releases the mouse at runtime this createEmptyMovieClip canvas_mc this getNextHighestDepth var mouseListen...

Page 480: ...480 Chapter 2 ActionScript Language Reference See also Mouse addListener...

Page 481: ...rs enable different 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 us...

Page 482: ...identifier to pointer_id Add the following ActionScript to Frame 1 of the Timeline to use this script you need a symbol in your library with a Linkage Identifier of pointer_id this attachMovie pointer...

Page 483: ...cause 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 user draws...

Page 484: ...use wheel To 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 Mou...

Page 485: ...heel 485 mouseListener onMouseWheel function delta Number line_mc _rotation delta mouseListener onMouseDown function trace Down Mouse addListener mouseListener See also Mouse addListener TextField mou...

Page 486: ...dds the mouse listener after it is removed so the user can draw lines again Add the following ActionScript to Frame 1 of the Timeline Add an instance of the Button component to be placed in the Librar...

Page 487: ...r Object new Object stopDrawingListener click function evt Object Mouse removeListener mouseListener evt target enabled false startDrawing_button enabled true stopDrawing_button addEventListener click...

Page 488: ...ible by default Example The following example attaches a custom cursor from the library when it rolls over a movie clip called my_mc Give a movie clip in the Library a Linkage identifier of cursor_hel...

Page 489: ...reates an empty movie clip MovieClip createTextField Creates an empty text field MovieClip duplicateMovieClip Duplicates the specified movie clip MovieClip getBounds Returns the minimum and maximum x...

Page 490: ...prevFrame Sends 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 duplicateMo...

Page 491: ...lip _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 a movi...

Page 492: ...specifying the 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 m...

Page 493: ...pointer is over a movie clip MovieClip onReleaseOutside Invoked when the mouse is clicked over a movie clip and released while the pointer is outside the movie clip s area MovieClip onRollOut Invoked...

Page 494: ...lers of the MovieClip class by creating a subclass For more information see Assigning a class to a movie clip symbol in Using ActionScript in Flash Example The following code sets the _alpha property...

Page 495: ...ream connection Add a new Video symbol by opening the Library panel and selecting New Video from the Library options menu Give it the instance name my_video Dynamically load the FLV video at runtime U...

Page 496: ...me_txt text Volume audio_sound getVolume The following example specifies a microphone as the audio source for a dynamically created movie clip instance called audio_mc var active_mic Microphone Microp...

Page 497: ...All properties of initObject are copied into the new instance The properties specified with initObject are available to the constructor function This parameter is optional Returns A reference to the...

Page 498: ...ll associated with it that path is closed with a line and then filled This is similar to what happens when MovieClip endFill is called You can extend the methods and event handlers of the MovieClip cl...

Page 499: ...tios An array of color distribution ratios valid values are 0 255 This value defines the percentage of the width where the color is sampled at 100 percent matrix A transformation matrix that is an obj...

Page 500: ...he parent clip for the upper left corner of the gradient w is the width of the gradient h is the height of the gradient and r is the rotation in radians of the gradient The following example uses a be...

Page 501: ...object for the matrix parameter are missing or invalid You can extend the methods and event handlers of the MovieClip class by creating a subclass For more information see Assigning a class to a movie...

Page 502: ...502 Chapter 2 ActionScript Language Reference endFill See also MovieClip beginFill MovieClip endFill MovieClip lineStyle MovieClip lineTo MovieClip moveTo...

Page 503: ...ox graphic it removes the graphic from the Stage this createEmptyMovieClip box_mc this getNextHighestDepth box_mc onRelease function this clear drawBox box_mc 10 10 320 240 function drawBox mc MovieCl...

Page 504: ...method but you don t need to provide an external linkage identifier for the new movie clip The registration point for a newly created empty movie clip is the upper left corner This method fails if any...

Page 505: ...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 506: ...ass to a movie clip symbol in Using ActionScript in Flash Example The following example creates a text field with a width of 300 a height of 100 an x coordinate of 100 a y coordinate of 100 no border...

Page 507: ...property returns the number of the frame in which the playhead is located in the Timeline specified by my_mc Example The following example uses the _currentframe property to direct the playhead of the...

Page 508: ...ine style from the current drawing position to anchorX anchorY using the control point specified by controlX controlY The current drawing position is then set to anchorX anchorY If the movie clip you...

Page 509: ...n Math PI 8 r x r y x r y mc curveTo Math tan Math PI 8 r x r y Math sin Math PI 4 r x Math sin Math PI 4 r y mc curveTo r x Math tan Math PI 8 r y r x y mc curveTo r x Math tan Math PI 8 r y Math sin...

Page 510: ...are using ActionScript 2 0 which does not support slash syntax Example The following example evaluates the _droptarget property of the garbage_mc movie clip instance and uses eval to convert it from s...

Page 511: ...creates an instance of the specified movie clip while the SWF file is playing Duplicated movie clips always start playing at Frame 1 no matter what frame the original movie clip is on when the duplic...

Page 512: ...ie clip if a movie clip is playing it continues to play The movie clip continues to receive movie clip events for example mouseDown mouseUp keyDown and keyUp The enabled property only governs the butt...

Page 513: ...ed with a line and then filled Example The following example creates a square with red fill on the Stage this createEmptyMovieClip square_mc this getNextHighestDepth square_mc beginFill 0xFF0000 squar...

Page 514: ...tion Property if the value is undefined or false a movie clip cannot receive input focus unless it is a button If the focusEnabled property value is true a movie clip can receive input focus even if i...

Page 515: ...ndividual movie clip basis Example This example demonstrates how to hide the yellow rectangle around a specified movie clip instance in a SWF file when it has focus in a browser window Create three mo...

Page 516: ...at the SWF file is loading until a specified frame in the SWF file has finished loading Example The following example uses the _framesloaded property to start a SWF file when all the frames are loaded...

Page 517: ...local coordinates respectively You can extend the methods and event handlers of the MovieClip class by creating a subclass For more information see Assigning a class to a movie clip symbol in Using A...

Page 518: ...518 Chapter 2 ActionScript Language Reference See also MovieClip globalToLocal MovieClip localToGlobal...

Page 519: ...more information see Assigning a class to a movie clip symbol in Using ActionScript in Flash Example The following example uses the _framesloaded property to start a SWF file when all the frames are l...

Page 520: ...For more information see Assigning a class to a movie clip symbol in Using ActionScript in Flash Example The following example uses the _framesloaded property to start a SWF file when all the frames a...

Page 521: ...Flash You can extend the methods and event handlers of the MovieClip class by creating a subclass For more information see Assigning a class to a movie clip symbol in Using ActionScript in Flash Examp...

Page 522: ...Clip to determine if the depth parameter you want to pass to any of these methods already contains a movie clip For more information see Managing movie clip depths in Using ActionScript in Flash You c...

Page 523: ...s in Using ActionScript in Flash You can extend the methods and event handlers of the MovieClip class by creating a subclass For more information see Assigning a class to a movie clip symbol in Using...

Page 524: ...if an error occurs and Flash can t determine the SWF version of my_mc 1 is returned You can extend the methods and event handlers of the MovieClip class by creating a subclass For more information see...

Page 525: ...lash However other products may do so for example Macromedia FlashPaper The contents of the TextSnapshot object aren t dynamic that is if the movie clip moves to a different frame or is altered in som...

Page 526: ...htmlText textformat The following text appears in text_mc textSnapshot_txt getTextRunInfo type Function setSelectColor type Function findText type Function hitTestTextNearPos type Function getSelecte...

Page 527: ...all numbers of variables POST sends the variables in a separate HTTP header and is used for long strings of variables Returns Nothing Description Method loads a document from the specified URL into th...

Page 528: ...dd the following ActionScript to a FLA or AS file in the same directory as an image called photo1 jpg this createTextField coords_txt this getNextHighestDepth 10 10 100 22 coords_txt html true coords_...

Page 529: ...MovieClip globalToLocal 529 See also MovieClip getBounds MovieClip localToGlobal...

Page 530: ...nformation see Assigning a class to a movie clip symbol in Using ActionScript in Flash Example The following example uses the _framesloaded property to start a SWF file when all the frames are loaded...

Page 531: ...lass to a movie clip symbol in Using ActionScript in Flash Example The following example uses the _framesloaded property to start a SWF file when all the frames are loaded If all the frames aren t loa...

Page 532: ...ip in the Output panel this createEmptyMovieClip image_mc this getNextHighestDepth var image_mcl MovieClipLoader new MovieClipLoader var mclListener Object new Object mclListener onLoadInit function t...

Page 533: ...s on the new hit area behavior The movie clip designated as the hit area does not need to be visible its graphical shape although not visible is hit tested The hitArea property can be read out of a pr...

Page 534: ...specified hit area false otherwise Description Method evaluates the instance specified by my_mc to see if it overlaps or intersects with the hit area identified by the target or x and y coordinate pa...

Page 535: ...MovieClip hitTest 535 See also MovieClip getBounds MovieClip globalToLocal MovieClip localToGlobal...

Page 536: ...value is less than 0 Flash uses 0 if the value is greater than 100 Flash uses 100 Returns Nothing Description Method specifies a line style that Flash uses for subsequent calls to lineTo and curveTo...

Page 537: ...call lineTo before any calls to the moveTo method the current drawing position defaults to 0 0 If any of the parameters are missing this method fails and the current drawing position is not changed Yo...

Page 538: ...e the original SWF file is playing Tip If you want to monitor the progress of the download use MovieClipLoader loadClip instead of this function Without the loadMovie method Flash Player displays a si...

Page 539: ...e picture jpg into a movie clip and use the MovieClip onPress method to make the image act like a button Loading a JPEG using loadMovie replaces the movie clip with the image but doesn t give you acce...

Page 540: ...of variables This method can also be used to update variables in the active movie clip with new values This method requires that the text of the URL be in the standard MIME format application x www fo...

Page 541: ...to check the loading progress The script checks for a variable in the params txt file named done this createEmptyMovieClip target_mc this getNextHighestDepth target_mc loadVariables params txt functi...

Page 542: ...mation see Assigning a class to a movie clip symbol in Using ActionScript in Flash Example The following example converts x and y coordinates of the my_mc object from the movie clip s local coordinate...

Page 543: ...swf from someone else s site into chess_mc you can set its _lockroot property when you load it as shown below In this case Chess swf can be published for any version of Flash Player as long as Games s...

Page 544: ...oot swf this createEmptyMovieClip nolockroot_mc this getNextHighestDepth nolockroot_mc loadMovie nolockroot swf function dumpRoot trace from current SWF file for i in _root trace i _root i trace dumpR...

Page 545: ...ent SWF file dumpRoot type Function version WIN 7 0 19 0 nolockroot_mc _level0 nolockroot_mc lockroot_mc _level0 lockroot_mc from nolockroot swf myOtherVar 2 myVar 1 from lockroot swf myOtherVar 2 myV...

Page 546: ...age 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 createEmptyMovi...

Page 547: ...the current drawing position is not changed You can extend the methods and event handlers of the MovieClip class by creating a subclass For more information see Assigning a class to a movie clip symb...

Page 548: ...context menu to view information about that instance Add several movie clips with instance names and then add the following ActionScript to your AS or FLA file var menu_cm ContextMenu new ContextMenu...

Page 549: ...subclass For more information see Assigning a class to a movie clip symbol in Using ActionScript in Flash Example The following example loads content into a SWF file using _framesloaded and nextFrame...

Page 550: ...e invoked when a specific movie clip receives data you must use onClipEvent instead of this handler The latter handler is invoked when any movie clip receives data Example The following example illust...

Page 551: ...vieClip onData 551 Therefore this function is invoked when symbol_mc is instantiated and also when replacement swf is loaded OnClipEvent data trace The movie clip has received data See also onClipEven...

Page 552: ...efine a function that executes when the event handler is invoked You can define the function on the Timeline or in a class file that extends the MovieClip class or is linked to a symbol in the library...

Page 553: ...n that executes when the event handler is invoked You can define the function on the Timeline or in a class file that extends the MovieClip class or is linked to a symbol in the library For more infor...

Page 554: ...rame actions that are attached to the affected frames You must define a function that executes when the event handler is invoked You can define the function on the Timeline or in a class file that ext...

Page 555: ...nt 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 must be given focus This can be d...

Page 556: ...u tab to the movie clip and press a key key was pressed displays in the Output panel However this does not occur after you move the mouse because the movie clip loses focus Therefore you should use Ke...

Page 557: ...movie clip symbol in Using ActionScript in Flash 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 fo...

Page 558: ...when the event handler is invoked You can define the function on the Timeline or in a class file that extends the MovieClip class or is linked to a symbol in the library For more information see Assig...

Page 559: ...ed with a class If you want an event handler to be invoked when a specific movie clip loads for example when you use MovieClip loadMovie to load a SWF file dynamically you must use onClipEvent load in...

Page 560: ...createEmptyMovieClip tester_mc 1 var mclListener Object new Object mclListener onLoadInit function target_mc MovieClip trace movie loaded var image_mcl MovieClipLoader new MovieClipLoader image_mcl a...

Page 561: ...that executes when the event handler is invoked You can define the function on the Timeline or in a class file that extends the MovieClip class or is linked to a symbol in the library For more inform...

Page 562: ...tion that executes when the event handler is invoked You can define the function on the Timeline or in a class file that extends the MovieClip class or is linked to a symbol in the library For more in...

Page 563: ...that executes when the event handler is invoked You can define the function on the Timeline or in a class file that extends the MovieClip class or is linked to a symbol in the library For more inform...

Page 564: ...lip You must define a function that executes when the event handler is invoked You can define the function on the Timeline or in a class file that extends the MovieClip class or is linked to a symbol...

Page 565: ...unction that executes when the event handler is invoked You can define the function on the Timeline or in a class file that extends the MovieClip class or is linked to a symbol in the library For more...

Page 566: ...the movie clip area You must define a function that executes when the event handler is invoked You can define the function on the Timeline or in a class file that extends the MovieClip class or is li...

Page 567: ...function that executes when the event handler is invoked You can define the function on the Timeline or in a class file that extends the MovieClip class or is linked to a symbol in the library For mor...

Page 568: ...st 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 lib...

Page 569: ...t 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 or is linked to a symbol in the library For more informatio...

Page 570: ...handler before attaching any actions to the affected frame 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 tha...

Page 571: ...ve up multiple levels in the display list as in the following this _parent _parent _alpha 20 Example The following example traces the reference to a movie clip and its relationship to the main Timelin...

Page 572: ...vie clip symbol in Using ActionScript in Flash Example Use the following ActionScript to play the main Timeline of a SWF file This ActionScript is for a movie clip button called my_mc on the main Time...

Page 573: ...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 Add content to a series of frames on...

Page 574: ...using a 2 x 2 pixel grid but bitmaps are not smoothed This is suitable for movies that do not contain text HIGH High rendering quality Graphics are anti aliased using a 4 x 4 pixel grid and bitmaps ar...

Page 575: ...s to a movie clip symbol in Using ActionScript in Flash Example Each time you click a button in the following example you attach a movie clip instance to the Stage in a random position When you click...

Page 576: ...e rotation Values outside this range are added to or subtracted from 360 to obtain a value within the range For example the statement my_mc _rotation 450 is the same as my_mc _rotation 90 Example The...

Page 577: ...ample my_mc setMask my_mc If you create a mask layer that contains a movie clip and then apply the setMask method to it the setMask call takes priority and this is not reversible For example you could...

Page 578: ...Description Property global an integer that specifies the number of seconds a sound prebuffers before it starts to stream Note Although you can specify this property for a MovieClip object it is actu...

Page 579: ...to MovieClip stopDrag or until another movie clip is made draggable Only one movie clip is draggable at a time You can extend the methods and event handlers of the MovieClip class by creating a subcla...

Page 580: ...ption Method stops the movie clip currently playing You can extend the methods and event handlers of the MovieClip class by creating a subclass For more information see Assigning a class to a movie cl...

Page 581: ...ee Assigning a class to a movie clip symbol in Using ActionScript in Flash Example The following example creates a draggable movie clip instance called image_mc A MovieClipLoader object is used to loa...

Page 582: ...arent movie clip Swapping the depth level of movie clips has the effect of moving one movie clip in front of or behind the other If a movie clip is tweening when this method is called the tweening is...

Page 583: ...be excluded from tab ordering To do this the tabChildren property of the list box should be set to false The tabChildren property has no effect if the tabIndex property is used the tabChildren propert...

Page 584: ...ring If the tabIndex property is also set to a value the object is included in custom tab ordering as well If tabEnabled is false the object is not included in automatic or custom tab ordering even if...

Page 585: ...properties The tabIndex property must be a positive integer The objects are ordered according to their tabIndex properties in ascending order An object with a tabIndex value of 1 precedes an object wi...

Page 586: ...the movie clip instance specified by my_mc in slash notation Use the eval function to convert the target path to dot notation Example The following example displays the target paths of movie clip ins...

Page 587: ...s the playhead to the previous frame and the next_mc button moves the playhead to the next frame Add content to a series of frames on the Timeline and add the following ActionScript to Frame 1 of the...

Page 588: ...t the default behavior is false You can change the trackAsMenu property at any time the modified movie clip immediately takes on the new behavior Example The following example sets the trackAsMenu pro...

Page 589: ...he methods and event handlers of the MovieClip class by creating a subclass For more information see Assigning a class to a movie clip symbol in Using ActionScript in Flash Example The following examp...

Page 590: ...12x112 jpg image_mc The following example assigns the ContextMenu object menu_cm to the movie clip image_mc The ContextMenu object contains a custom menu item labeled View Image in Browser that has an...

Page 591: ...p If useHandCursor is false the arrow pointer is used instead You can change the useHandCursor property at any time the modified movie clip immediately takes on the new cursor behavior The useHandCurs...

Page 592: ...on in a movie clip with _visible set to false cannot be clicked Example The following example sets the _visible property for two movie clips called myMC1_mc and myMC2_mc The property is set to true fo...

Page 593: ...in the Output panel this createEmptyMovieClip image_mc this getNextHighestDepth var image_mcl MovieClipLoader new MovieClipLoader var mclListener Object new Object mclListener onLoadInit function tar...

Page 594: ...p s children inherit a coordinate system that is rotated 90 counterclockwise The movie clip s coordinates refer to the registration point position Example The following example attaches a movie clip w...

Page 595: ...on to a movie clip on the Stage called my_mc this createTextField mouse_txt this getNextHighestDepth 0 0 150 66 mouse_txt html true mouse_txt multiline true var row1_str String nbsp t b _xmouse t b b...

Page 596: ...ie were set at 100 Example The following example creates a movie clip at runtime called box_mc The Drawing API is used to draw a box in this instance and when the mouse rolls over the box horizontal a...

Page 597: ...coordinate system that is rotated 90 counterclockwise The movie clip s coordinates refer to the registration point position Example The following example attaches a movie clip with the linkage identi...

Page 598: ...and in relation to a movie clip on the Stage called my_mc this createTextField mouse_txt this getNextHighestDepth 0 0 150 66 mouse_txt html true mouse_txt multiline true var row1_str String nbsp t b _...

Page 599: ...Example The following example creates a movie clip at runtime called box_mc The Drawing API is used to draw a box in this instance and when the mouse rolls over the box horizontal and vertical scalin...

Page 600: ...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 601: ...lipLoader loadClip See also MovieClipLoader addListener Listener Description MovieClipLoader onLoadComplete Invoked when a file loaded with MovieClipLoader loadClip has completely downloaded MovieClip...

Page 602: ...EmptyMovieClip image_mc this getNextHighestDepth var mclListener Object new Object mclListener onLoadInit function target_mc MovieClip target_mc _x Stage width 2 target_mc _width 2 target_mc _y Stage...

Page 603: ...le dynamically created movie clip called image_mc The number of bytes loaded and the total number of bytes for the loaded image display in a dynamically created text field called filesize_txt this cre...

Page 604: ...antages The following handlers are implemented by the use on a listener object which is registered with the MovieClipLoader class using MovieClipLoader addListener listenerObject The MovieClipLoader o...

Page 605: ...er onLoadProgress function target_mc MovieClip loadedBytes Number totalBytes Number trace First my_mcl instance Progress trace onLoadProgress called back on movie clip target_mc trace loadedBytes byte...

Page 606: ...onLoadComplete function target_mc MovieClip trace Second my_mcl instance trace Your load is done on movie clip target_mc var loadProgress Object my_mcl getProgress target_mc trace loadProgress bytesL...

Page 607: ...the way they work with your SWF file The onLoadComplete event is called after the SWF or JPEG file has loaded but before the application has been initialized At this point it is impossible to access t...

Page 608: ...width 22 target_mc timer_txt text loaded in timerMS ms var image_mcl MovieClipLoader new MovieClipLoader image_mcl addListener mclListener image_mcl loadClip http www macromedia com images shared prod...

Page 609: ...MovieClipLoader onLoadStart was called but MovieClipLoader onLoadComplete was not called For example if MovieClipLoader onLoadStart is called but the download is interrupted due to server overload ser...

Page 610: ...t function target_mc MovieClip trace success trace image_mcl getProgress target_mc bytesTotal bytes loaded var image_mcl MovieClipLoader new MovieClipLoader image_mcl addListener mclListener image_mcl...

Page 611: ...r ActionScript 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 imag...

Page 612: ...612 Chapter 2 ActionScript Language Reference See also MovieClipLoader onLoadStart...

Page 613: ...es parameters The value for target_mc identifies the movie clip 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 p...

Page 614: ...Listener onLoadProgress function target_mc MovieClip bytesLoaded Number bytesTotal Number progressBar_mc bar_mc _xscale Math round bytesLoaded bytesTotal 100 mclListener onLoadComplete function target...

Page 615: ...mage 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 text field called time...

Page 616: ...616 Chapter 2 ActionScript Language Reference See also MovieClipLoader onLoadError MovieClipLoader onLoadInit MovieClipLoader onLoadComplete...

Page 617: ...gress information is displayed in the Output panel this createEmptyMovieClip image_mc this getNextHighestDepth var mclListener Object new Object mclListener onLoadStart function target_mc MovieClip tr...

Page 618: ...618 Chapter 2 ActionScript Language Reference start_button enabled true stop_button enabled false image_mcl removeListener mclListener stop_button enabled false...

Page 619: ...into a movie clip called image_mc If you click the movie clip the movie clip is removed and information is displayed in the Output panel this createEmptyMovieClip image_mc this getNextHighestDepth var...

Page 620: ...ce 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 621: ...ability Flash Player 5 Usage Infinity Description Constant specifies the IEEE 754 value representing negative infinity The value of this constant is the same as Number NEGATIVE_INFINITY CHAPTER 2 Acti...

Page 622: ...nication Server documentation Usage new NetConnection NetConnection Parameters None Returns A reference to a NetConnection object Description Constructor creates a NetConnection object that you can us...

Page 623: ...NetConnection class 623 See also NetStream class Video attachVideo...

Page 624: ...ion Constructor 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...

Page 625: ...ript in Flash Method summary for the NetStream class The following methods and properties of the NetConnection and NetStream classes are used to control FLV playback Property summary for the NetStream...

Page 626: ...h the specified NetConnection object Example The following code first constructs a new NetConnection object connection_nc and uses it to construct a new NetStream object called stream_ns Select New Vi...

Page 627: ...ber of seconds that are currently in the buffer The text field also displays the buffer length that the video is set to and percentage of buffer that is filled this createTextField buffer_txt this get...

Page 628: ...re currently in the buffer The text field also displays the buffer length that the video is set to and percentage of buffer that is filled this createTextField buffer_txt this getNextHighestDepth 10 1...

Page 629: ...A text field called loaded_txt is dynamically created to display information about the loading progress as well var connection_nc NetConnection new NetConnection connection_nc connect null var stream...

Page 630: ...eckBytesLoaded my_ns NetStream var pctLoaded Number Math round my_ns bytesLoaded my_ns bytesTotal 100 loaded_txt text Math round my_ns bytesLoaded 1000 of Math round my_ns bytesTotal 1000 KB loaded pc...

Page 631: ...m_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 createEmptyMovieClip prog...

Page 632: ...loaded_txt text Math round my_ns bytesLoaded 1000 of Math round my_ns bytesTotal 1000 KB loaded pctLoaded progressBar_mc bar_mc _xscale pctLoaded if pctLoaded 100 clearInterval loaded_interval See al...

Page 633: ...kes the stream available for another use This command also deletes the local copy of an FLV file that was downloaded using HTTP Example The following onDisconnect function closes a connection and dele...

Page 634: ...ue during testing to help you determine how much compression to apply when exporting the file Example The following example creates a text field that displays the current number of frames per second t...

Page 635: ...at is either status or error In addition to this onStatus handler Flash also provides a super function called System onStatus If onStatus is invoked for a particular object and there is no function as...

Page 636: ...new NetConnection connection_nc connect null var stream_ns NetStream new NetStream connection_nc my_video attachVideo stream_ns stream_ns play video1 flv stream_ns onStatus function infoObject Object...

Page 637: ...t is called on a specified stream it pauses play and the next time it is called it resumes play This parameter is optional Returns Nothing Description Method pauses or resumes playback of a stream The...

Page 638: ...ect to control some aspects of the audio For more information see MovieClip attachAudio If the FLV file can t be found the NetStream onStatus event handler is invoked If you want to stop a stream that...

Page 639: ...NetStream play 639 See also MovieClip attachAudio NetStream close NetStream pause Video attachVideo...

Page 640: ...me n 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...

Page 641: ...fSeconds The number of seconds of data to be buffered before Flash begins displaying data The default value is 0 1 one tenth of a second Description Method specifies how long to buffer messages before...

Page 642: ...it an instance name my_video Add the following ActionScript to your FLA or AS file var connection_nc NetConnection new NetConnection connection_nc connect null var stream_ns NetStream new NetStream c...

Page 643: ...ntheses 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 th...

Page 644: ...nk 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 displa...

Page 645: ...arrow key the playhead goes to the previous frame and stops The listener is initialized to wait for the arrow key to be pressed and the init variable is used to prevent the listener from being redefin...

Page 646: ...ghestDepth nextscene_mc createTextField nextscene_txt this getNextHighestDepth 200 0 100 22 nextscene_mc nextscene_txt autoSize true nextscene_mc nextscene_txt border true nextscene_mc nextscene_txt t...

Page 647: ...a 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...

Page 648: ...lue is NaN If expression is undefined the return value is as follows In files published for Flash Player 6 or earlier the result is 0 In files published for Flash Player 7 or later the result is NaN T...

Page 649: ...Number 649 See also NaN Number class...

Page 650: ...er Number new 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_V...

Page 651: ...ject Description Constructor creates a new Number object You must use the Number constructor when using Number toString and Number valueOf You do not use a constructor when using the properties of a N...

Page 652: ...double precision IEEE 754 This number is approximately 1 79e 308 Example The following ActionScript displays the largest and smallest representable numbers to the Output panel trace Number MIN_VALUE...

Page 653: ...ion IEEE 754 This number is approximately 5e 324 Example The following ActionScript displays the largest and smallest representable numbers to the Output panel trace Number MIN_VALUE Number MIN_VALUE...

Page 654: ...654 Chapter 2 ActionScript Language Reference Number NaN Availability Flash Player 5 Usage Number NaN Description Property the IEEE 754 value representing Not A Number NaN See also isNaN NaN...

Page 655: ...Negative infinity is a special numeric value that is returned when a mathematical operation or function returns a negative value larger than can be represented Example This example compares the resul...

Page 656: ...tant Infinity Positive infinity is a special numeric value that is returned when a mathematical operation or function returns a value larger than can be represented Example This example compares the r...

Page 657: ...ation of the specified Number object myNumber Example The following example uses 2 and 8 for the radix parameter and returns a string that contains the corresponding representation of the number 9 var...

Page 658: ...5 Usage myNumber valueOf Number Parameters None Returns Number Description Method returns the primitive value type of the specified Number object Example The following example results in the primative...

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

Page 660: ...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 661: ...bject Description Constructor creates an Object object and stores a reference to the object s constructor method in the object s constructor property Example The following example creates a generic ob...

Page 662: ...s a function with no parameters Its return value can be of any type Its type can change between invocations The return value is treated as the current value of the property A set function is a functio...

Page 663: ...s of Catcher in the Rye The previous example works but the properties bookcount and bookname are added to every instance of the Book object which requires having two properties for every instance of t...

Page 664: ...ting Book prototype you define the Book class in an external file named Book as For more information see Creating and using classes in Using ActionScript in Flash The following code must be in a separ...

Page 665: ...tr String new String sven trace my_str constructor String output true If you use the instanceof operator you can also determine if an object belongs to a specified class var my_str String new String s...

Page 666: ...totype property of the constructor function that created myObject The __proto__ property is automatically assigned to all objects when they are created The ActionScript interpreter uses the __proto__...

Page 667: ...instance of the specified movie clip symbol is created by using MovieClip attachMovie or MovieClip duplicateMovieClip it is registered to the class specified by theClass rather than to the MovieClip c...

Page 668: ...f the properties or methods are actually defined This property is useful for enabling highly transparent client server communication and is the recommended way of invoking server side methods Example...

Page 669: ...for __resolve to call myObject myFunction function name trace Method name was called define the __resolve function myObject __resolve function name trace Resolve called for name to check when __resol...

Page 670: ...creating a functor that accepts parameters This example makes extensive use of the arguments object and uses several methods of the Array class instantiate a new object var myObject Object new Object...

Page 671: ...Object __resolve 671 myObject someOtherMethod hello world output Method someOtherMethod was called with arguments hello world...

Page 672: ...time Array toString returns the array contents as a comma delimited string var myArray Array new Array one two trace myArray toString output one two Number toString returns the number value as a stri...

Page 673: ...ode to place into a FLA file var myVehicle Vehicle new Vehicle 2 red trace myVehicle toString output A vehicle that is red and has 2 doors for comparison purposes this is a call to valueOf there is no...

Page 674: ...ject property that should no longer be watched Returns A Boolean value true if the watchpoint is successfully removed false otherwise Description Method removes a watchpoint that Object watch created...

Page 675: ...following examples show the return values for the built in classes Date and Array and compares them to the return values of Object toString Create a new Date object set to February 1 2004 8 15 AM The...

Page 676: ...r can use the return statement in your callback method definition to affect the value of the property you are watching The value returned by your callback method is assigned to the watched object prop...

Page 677: ...pt properties such as _x _y _width and _height are getter setter properties and cannot be watched with Object watch Example The following example uses watch to check whether the speed property exceeds...

Page 678: ...n rolls outside the button area dragOver While the pointer is over the button the mouse button has been pressed then rolled outside the button and then rolled back over the button keyPress key The spe...

Page 679: ...on 679 on release trace X this _x trace Y this _y stopDrag See also onClipEvent...

Page 680: ...rame actions 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 mou...

Page 681: ...layhead 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 onClipEvent wit...

Page 682: ...ters tab in the Components inspector onUpdate is invoked The onUpdate function does something to update itself For instance if the component includes a color parameter the onUpdate function might alte...

Page 683: ...onUpdate 683 buttonLabel textColor my_mc labelColor...

Page 684: ...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 685: ...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 characters Example Th...

Page 686: ...ginning with 0 or specifying 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 us...

Page 687: ...parseInt 687 The following examples show octal number parsing and return 511 which is the decimal representation of the octal 777 parseInt 0777 parseInt 777 8 See also NaN parseFloat...

Page 688: ...e there are two movie clip instances on the Stage with the instance names stop_mc and play_mc The ActionScript stops the SWF file s playback when the stop_mc movie clip instance is clicked Playback re...

Page 689: ...e current frame is Frame 1 the playhead does not move Example When the user clicks a button called myBtn_btn and the following ActionScript is placed on a frame in the Timeline for that button the pla...

Page 690: ...age Reference prevScene Availability Flash 2 Usage prevScene Void Parameters None Returns Nothing Description Function sends the playhead to Frame 1 of the previous scene See also nextScene CHAPTER 2...

Page 691: ...in your movie clip vary in size bframe Indicates that the bounding box of each printable frame should be used as the print area for that frame which changes the print area for each frame and scales th...

Page 692: ...er_mc 999 holder_mc loadMovie http www macromedia com devnet mx blueprint articles nielsen spotlight_jnielsen jpg this myBtn_btn onRelease function print this _parent holder_mc bframe In the previous...

Page 693: ...rames in your movie clip vary in size bframe Indicates that the bounding box of each printable frame should be used as the print area for that frame This changes the print area for each frame and scal...

Page 694: ...lowing example prints all the printable frames in holder_mc with a print area defined by the bounding box of the frame this createEmptyMovieClip holder_mc 999 holder_mc loadMovie http www macromedia c...

Page 695: ...f each printable frame should be used as the print area for that frame This changes the print area for each frame and scales the objects to fit the print area Use bframe if you have objects of differe...

Page 696: ...Non PostScript printers convert vectors to bitmaps Example The following example prints the contents of the Stage when the user clicks the button myBtn_btn The area to print is defined by the boundin...

Page 697: ...uch as page height width and orientation and you can configure your document to dynamically format Flash content that is appropriate for the printer settings These user layout properties are read only...

Page 698: ...ecified area to print job repeat once for each page to be printed if my_pj addPage params pagesToPrint if my_pj addPage params pagesToPrint if my_pj addPage params pagesToPrint send pages from the spo...

Page 699: ...e the following equivalencies to convert inches or centimeters to twips or points a twip is 1 20 of a point 1 point 1 72 inch 20 twips 1 inch 72 points 1440 twips 1 cm 567 twips You can t reliably con...

Page 700: ...nd the spooled pages to the printer If this method returns false for example if you haven t called PrintJob start or the user canceled the print job any subsequent calls to PrintJob addPage will fail...

Page 701: ...yMax 500 printAsBitmap true 1 pageCount Starting 50 pixels to the right of 0 0 and 70 pixels down print an area 500 pixels wide and 600 pixels high of frame 4 of level 5 in vector format if my_pj addP...

Page 702: ...702 Chapter 2 ActionScript Language Reference If addPage was successful at least once print the spooled pages if pageCount 0 my_pj send delete my_pj See also PrintJob send PrintJob start...

Page 703: ...nter Because calls to PrintJob send will not be successful if related calls to PrintJob start and PrintJob addpage failed you should check that calls to PrintJob addpage and PrintJob start were succes...

Page 704: ...the read only height width and orientation properties this method populates to format the printout Because the user sees information such as Printing page 1 immediately after clicking OK you should ca...

Page 705: ...o addPage is possible var pageAdded Boolean false check the user s printer orientation setting and add appropriate print area to print job if my_pj orientation portrait Here the printArea measurements...

Page 706: ...e Indicates that the bounding box of each printable frame should be used as the print area for that frame This changes the print area for each frame and scales the objects to fit the print area Use bf...

Page 707: ...or function For more information see Controlling member access in Using ActionScript in Flash You can use this keyword only in class definitions not in interface definitions Example The following exa...

Page 708: ...th trace gus username output Gus trace gus password output undefined trace gus loginPassword error Because loginPassword is a private variable you cannot access it from outside the Login as class file...

Page 709: ...y for stylistic reasons For example you might want to use it for reasons of consistency in a block of code that also contains private or static variables Example The following example shows how you ca...

Page 710: ...are not smoothed MEDIUM Medium rendering quality Graphics are anti aliased using a 2 x 2 pixel grid but bitmaps are not smoothed Suitable for movie clips that do not contain text HIGH High rendering q...

Page 711: ...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 getNextHighestDepth...

Page 712: ...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 713: ...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 the Timeline of t...

Page 714: ...of the selection span Returns 1 if there is no index or currently selected field Selection getCaretIndex Returns the current caret insertion point position in the currently focused selection span Retu...

Page 715: ...pt object named focusListener This object defines for itself an onSetFocus property to which it assigns a function The function takes two parameters a reference to the text field that lost focus and o...

Page 716: ...tput_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 ContextMenu...

Page 717: ...other text field this createTextField pos_txt this getNextHighestDepth 50 20 100 22 this createTextField content_txt this getNextHighestDepth 50 50 400 300 content_txt border true content_txt type inp...

Page 718: ...upper or lower case function convertCase target menuItem var beginIndex Number Selection getBeginIndex var endIndex Number Selection getEndIndex var tempString String make sure that text is actually...

Page 719: ...file for the entire script Typical paths to the HelpExamples folder are Windows Program Files Macromedia Flash MX 2004 Samples HelpExamples Macintosh HD Applications Macromedia Flash MX 2004 Samples...

Page 720: ...ther a TextField object Button object Component instance nor button movie clip has focus this method returns null Example The following example displays the currently focused selection s target path i...

Page 721: ...addListener someListener Listeners enable different pieces of code to cooperate because multiple listeners can receive notification about a single event Example The following example demonstrates how...

Page 722: ...htmlText textformat tabStops 20 80 status_txt htmlText nbsp toldFocus t oldFocus status_txt htmlText nbsp tnewFocus t newFocus status_txt htmlText nbsp tgetFocus t Selection getFocus status_txt htmlT...

Page 723: ...text field instances When you select a text field information displays in the Output panel When you click the remove_btn instance the listener is removed and information no longer displays in the Outp...

Page 724: ...en it is running in a browser window If the user does not fill in one of the required text fields username_txt and password_txt the cursor automatically focuses in the text field that s missing data F...

Page 725: ...ection setFocus username_txt return false if password_txt text length 0 status_txt text fill in password Selection setFocus password_txt return false status_txt text success Selection setFocus null re...

Page 726: ...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 first position is 0 the second position is 1 and so on...

Page 727: ...s Using implicit set methods lets you modify the value of an object s property without accessing the property directly Implicit get set methods are syntactic shorthand for the Object addProperty metho...

Page 728: ...rame 1 of the Timeline 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...

Page 729: ...you use this statement to set a variable to a value whose data type is different from the data type associated with the variable in a class file no compiler error is generated A subtle but important...

Page 730: ...set name Jakob trace name 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 tr...

Page 731: ...ed as close to interval as possible You must use the updateAfterEvent function to make sure that the screen refreshes often enough If interval is greater than the SWF file s frame rate the interval fu...

Page 732: ...t for our MovieClipLoader instance var listenerObjectbject new Object listenerObject onLoadInit function target_mc MovieClip trace start interval after the target movie clip loaded create a callback w...

Page 733: ...to Frame 1 var me User new User Gary this deleteUser_btn onRelease function trace Goodbye me username delete me Then create a FLA in the same directory called User as Enter the following ActionScript...

Page 734: ...a movie clip 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 cl...

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

Page 736: ...no size limit in Flash Player that runs from the authoring environment Method summary for the SharedObject class Property summary for the SharedObject class Event handler summary for the SharedObject...

Page 737: ...d my_so is now empty Example The following example sets data in the shared object and then empties all of the data from the shared object var my_so SharedObject SharedObject getLocal superfoo my_so da...

Page 738: ...All attributes of a shared object s data property are saved if the object is persistent and the shared object contains the following information userName Ramona adminPrivileges true itemNumbers 101 3...

Page 739: ...object Object Example The following example saves text from a TextInput component instance to a shared object named my_so for the complete example see SharedObject getLocal create listener object and...

Page 740: ...t to 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 SharedObj...

Page 741: ...erride Boolean settings Object var my_so SharedObject SharedObject getLocal soName http www mydomain com app sys settings list index var i For each specified value in settings If override is true set...

Page 742: ...ter s importance Returns A reference to a shared object that is persistent locally and is available only to the current client If Flash can t create or find the shared object for example if localPath...

Page 743: ...e your localPath parameter options for the portfolio shared object created by the SWF file at www myCompany com apps stockwatcher swf are apps or apps stockwatcher swf You will need to determine which...

Page 744: ...for this user if my_so data user undefined this user my_so data user this gotoAndStop my_so data frame The following code block is placed on each SWF file frame On each frame call the rememberme funct...

Page 745: ...the longer it takes to estimate its size For this reason estimating object size can have significant processing time Therefore you might want to avoid using this method unless you have a specific need...

Page 746: ...n called 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 e...

Page 747: ...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 748: ...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 749: ...s all of the sounds in the movie Example The 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 va...

Page 750: ...parameter to the specified Sound object The sound must be in the library of the current SWF file and specified for export in the Linkage Properties dialog box You must call Sound start to start playin...

Page 751: ...onds my_sound loadSound song1 mp3 true The following example loads several songs into a SWF file A progress bar created using the Drawing API displays the loading progress When the music starts and co...

Page 752: ...sound Sound new Sound my_sound onLoad function success Boolean if success trace sound loaded my_sound onSoundComplete function clearInterval my_interval trace Cleared interval my_sound loadSound song3...

Page 753: ...when the file finishes loading Add the following ActionScript to your FLA or AS file this createTextField message_txt this getNextHighestDepth 10 10 300 22 this createTextField status_txt this getNex...

Page 754: ...cript Language Reference status_txt text the_sound getBytesLoaded of the_sound getBytesTotal bytes pct newline status_txt text the_sound position of the_sound duration milliseconds pos newline See als...

Page 755: ...BytesTotal Number Parameters None Returns An integer indicating the total size in bytes of the specified Sound object Description Method returns the size in bytes of the specified Sound object Example...

Page 756: ...g the Drawing API When the user drags the slider bar the pan level of the loaded sound changes The current pan level is displayed in a dynamically created text field Add the following ActionScript to...

Page 757: ...ase function this stopDrag var multiplier Number 100 this right this left 2 var pan Number this _x this left bar_width 2 multiplier my_sound setPan pan pan_txt text my_sound getPan var my_sound Sound...

Page 758: ...to your FLA or AS file var my_sound Sound new Sound my_sound loadSound song1 mp3 true var transform_obj Object my_sound getTransform this createEmptyMovieClip transform_mc this getNextHighestDepth tr...

Page 759: ...0 knob_rr left knob_rr _x knob_rr right knob_rr _x knob_rr _y knob_rr _y 100 transform_obj rr knob_rr onPress pressKnob knob_rr onRelease releaseKnob knob_rr onReleaseOutside releaseKnob updateTransfo...

Page 760: ...the sound playing in the SWF file Add the following ActionScript to your AS or FLA file var my_sound Sound new Sound my_sound loadSound song3 mp3 true this createEmptyMovieClip knob_mc this getNextHi...

Page 761: ...761 this isDragging 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...

Page 762: ...rt ID3 1 0 and ID3 1 1 tags Flash Player 7 adds support for ID3 2 0 tags specifically 2 3 and 2 4 The following table lists the standard ID3 2 0 tags and the type of content the tags represent you que...

Page 763: ...formers TORY Original release year TOWN File owner licensee TPE1 Lead performers soloists TPE2 Band orchestra accompaniment TPE3 Conductor performer refinement TPE4 Interpreted remixed or otherwise mo...

Page 764: ...f song mp3 to the Output panel var my_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 attachSou...

Page 765: ...fore 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 Playback begins when sufficient...

Page 766: ...id with 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...

Page 767: ...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 768: ...must 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_...

Page 769: ...sound position Number Description Read only property the number of milliseconds a sound has been playing If the sound is looped the position is reset to 0 at the beginning of each loop Example See Sou...

Page 770: ...only the left channel 100 uses only the right channel and 0 balances the sound evenly between the two channels Returns An integer Description Method determines how the sound is played in the left and...

Page 771: ...ay 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 of the...

Page 772: ...using setTransform as follows my_sound setTransform mySoundTransformObject The following example plays a stereo sound as mono the soundTransformObjectMono object has the following parameters var mySou...

Page 773: ...Parameters volume A number from 0 to 100 representing a volume level 100 is full volume and 0 is no volume The default setting is 100 Returns Nothing Description Method sets the volume for the Sound o...

Page 774: ...d or starting at the point in the sound specified by the secondOffset parameter Example The following example creates a new Sound object and loads a sound Loading the sound is handled by the onLoad ha...

Page 775: ...o parameter is specified or just the sound specified in the idName parameter Example The following example uses two buttons stop_btn and play_btn to control the playback of a sound that loads into a S...

Page 776: ...t to buffer 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...

Page 777: ...d Description Stage addListener Adds a listener object that detects when a SWF file is resized Stage removeListener Removes a listener object from the Stage object Property Description Stage align Ali...

Page 778: ...reate a listener object Stage listener objects receive notification from Stage onResize Example This example creates a new listener object called stageListener It then uses myListener to call onResize...

Page 779: ...ile Add a ComboBox instance to your document with the instance name stageAlign_cb Add the following ActionScript to your FLA or AS file var stageAlign_cb mx controls ComboBox stageAlign_cb dataProvide...

Page 780: ...creates a new listener object called stageListener It then uses myListener to call onResize and define a function that will be called when onResize is triggered Finally the code adds the myListener ob...

Page 781: ...this event handler to write a function that lays out the objects on the Stage when a SWF file is resized Example The following example displays a message in the Output panel when the Stage is resized...

Page 782: ...remove_btn Add the following ActionScript to Frame 1 of the Timeline this createTextField stageSize_txt this getNextHighestDepth 10 10 100 22 stageSize_txt autoSize true stageSize_txt border true var...

Page 783: ...e settings for the SWF file Add a ComboBox instance to your document with the instance name scaleMode_cb Add the following ActionScript to your FLA or AS file var scaleMode_cb mx controls ComboBox sca...

Page 784: ...dia Flash Player items appear Example The following example creates a clickable text link that lets the user enable and disable the Flash Player context menu this createTextField showMenu_txt this get...

Page 785: ...e value of width will stay constant as you resize the player window Example This example creates a new listener object called stageListener It then uses myListener to call onResize and define a functi...

Page 786: ...can be dragged 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 calle...

Page 787: ...class by using the syntax someClassName name If you do create an instance of the class you can also access a static member using the instance You can use this keyword in class definitions only not in...

Page 788: ...788 Chapter 2 ActionScript Language Reference See also private public...

Page 789: ...eters 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 gotoAndStop MovieClip go...

Page 790: ...stop_mc the 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...

Page 791: ...drag operation Example The following code placed in the main Timeline stops the drag action on the movie clip instance my_mc when the user releases the mouse button my_mc onPress function startDrag t...

Page 792: ...f no such property exists If expression is undefined the return values are as follows In files published for Flash Player 6 or earlier the result is an empty string In files published for Flash Player...

Page 793: ...y 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 of code creates...

Page 794: ...nstead of the constructor for the String class unless you have a good reason to use a String object rather than a string literal See also String string delimiter String substring Returns the character...

Page 795: ...ription Method returns the character in the position specified by the parameter index If index is not a number from 0 to string length 1 an empty string is returned This method is similar to String ch...

Page 796: ...r Description Method returns a 16 bit integer from 0 to 65535 that represents the character specified by index If index is not a number from 0 to string length 1 NaN is returned This method is similar...

Page 797: ...ring 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 example creates two...

Page 798: ...ers that represent ASCII values Returns A string Description Method returns a string comprising the characters represented by the ASCII values in the parameters Example The following example uses from...

Page 799: ...r after startIndex within the calling string This index is zero based meaning that the first character in a string is considered to be at index 0 not index 1 If substring is not found the method retur...

Page 800: ...within the calling string This index is zero based meaning that the first character in a string is considered to be at index 0 not index 1 If substring is not found the method returns 1 Example The f...

Page 801: ...s from 0 to my_str length The code checks the characters within a string and if the string contains the character true displays in the Output panel If it does not contain the character then false disp...

Page 802: ...If 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 retu...

Page 803: ...ice 3 my_str slice 3 slice 3 em An example is also in the Strings fla file in the HelpExamples folder The following list gives typical paths to this folder Windows Program Files Macromedia Flash MX 20...

Page 804: ...ng is placed as an element in the array If the delimiter parameter is undefined the entire string is placed into the first element of the returned array Example The following example returns an array...

Page 805: ...trings fla file in the HelpExamples folder The following list gives typical paths to this folder Windows Program Files Macromedia Flash MX 2004 Samples HelpExamples Macintosh HD Applications Macromedi...

Page 806: ...rom the index specified in the start parameter through the number of characters specified in the length parameter The substr method does not change the string specified by my_str it returns a new stri...

Page 807: ...points specified by the start and end parameters If the end parameter is not specified the end of the substring is the end of the string If the value of start equals the value of end the method retur...

Page 808: ...ing using toLowerCase to convert all uppercase characters to lowercase characters var upperCase String LOREM IPSUM DOLOR var lowerCase String upperCase toLowerCase trace upperCase upperCase output upp...

Page 809: ...then creates a copy of that string using toUpperCase var lowerCase String lorem ipsum dolor var upperCase String lowerCase toUpperCase trace lowerCase lowerCase output lowerCase lorem ipsum dolor tra...

Page 810: ...rical value 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...

Page 811: ...constructor 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 initializati...

Page 812: ...mySock getColor mySock setColor Orange trace mySock getColor The following result is displayed in the Output panel Clothes I am the constructor Socks I am the constructor Socks I am getColor Clothes...

Page 813: ...of 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 throug...

Page 814: ...814 Chapter 2 ActionScript Language Reference 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 if...

Page 815: ...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 propertie...

Page 816: ...running 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...

Page 817: ...iption Read only property a Boolean value that specifies whether access to the user s camera and microphone has been administratively prohibited true or allowed false The server string is AVD Example...

Page 818: ...property a Boolean value that is true if the player is running in an environment that supports communication between Flash Player and accessibility aids false otherwise The server string is ACC Exampl...

Page 819: ...capabilities hasAudio Boolean Description Read only property a Boolean value that is true if the player is running on a system that has audio capabilities false otherwise The server string is A Exampl...

Page 820: ...bilities hasAudioEncoder Boolean Description Read only property a Boolean value that is true if the player can encode an audio stream such as that coming from a microphone false otherwise The server s...

Page 821: ...capabilities hasEmbeddedVideo Boolean Description Read only property a Boolean value that is true if the player is running on a system that supports embedded video false otherwise The server string i...

Page 822: ...e System capabilities hasMP3 Boolean Description Read only property a Boolean value that is true if the player is running on a system that has an MP3 decoder false otherwise The server string is MP3 E...

Page 823: ...tem 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 string is PR Exa...

Page 824: ...adcast Boolean Description Read only property a Boolean value that is true if the player supports the development of screen broadcast applications to be run through the Flash Communication Server fals...

Page 825: ...k Boolean Description Read only property a Boolean value that is true if the player supports the playback of screen broadcast applications that are being run through the Flash Communication Server fal...

Page 826: ...r65 Usage System capabilities hasStreamingAudio Boolean Description Read only property a Boolean value that is true if the player can play streaming audio false otherwise The server string is SA Examp...

Page 827: ...5 Usage System capabilities hasStreamingVideo Boolean Description Read only property a Boolean value that is true if the player can play streaming video false otherwise The server string is SV Example...

Page 828: ...bilities hasVideoEncoder Boolean Description Read only property a Boolean value that is true if the player can encode a video stream such as that coming from a web camera false otherwise The server st...

Page 829: ...ies isDebugger Boolean Description Read only property a Boolean value that indicates whether the player is an officially released version false or a special debugging version true The server string is...

Page 830: ...nglish 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...

Page 831: ...age 831 Example The following example traces the value of this read only property trace System capabilities language Russian ru Simplified Chinese zh CN Spanish es Swedish sv Traditional Chinese zh TW...

Page 832: ...nable to read files including the first SWF file that 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 LoadMovie or LoadV...

Page 833: ...facturer String Description Read only property a string that indicates the manufacturer of Flash Player in the format Macromedia OSName OSName could be Windows Macintosh Linux or Other OS Name The ser...

Page 834: ...g that indicates the 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...

Page 835: ...h Player 6 Usage System capabilities pixelAspectRatio Number Description Read only property an integer that indicates the pixel aspect ratio of the screen The server string is AR Example The following...

Page 836: ...yer This property can have one of the following values StandAlone for the Flash StandAlone Player External for the Flash Player version used by test movie mode PlugIn for the Flash Player browser plug...

Page 837: ...String Description Read only property a string that indicates the screen color This property can have the value color gray or bw which represents color grayscale and black and white respectively The...

Page 838: ...layer 6 Usage System capabilities screenDPI Number Description Read only property a number that indicates the dots per inch dpi resolution of the screen in pixels The server string is DP Example The f...

Page 839: ...ties screenResolutionX Number Description Read only property an integer that indicates the maximum horizontal resolution of the screen The server string is R which returns both the width and height of...

Page 840: ...ilities screenResolutionY Number Description Read only property an integer that indicates the maximum vertical resolution of the screen The server string is R which returns both the width and height o...

Page 841: ...t specifies values for each System capabilities property as shown in the following example A t SA t SV t EV t MP3 t AE t VE t ACC f PR t SP t SB f DEB t V WIN 207 2C0 2C 19 2C0 M Macromedia 20Windows...

Page 842: ...6 Usage System capabilities version String Description Read only property a string containing the Flash Player platform and version information for example WIN 7 0 19 0 The server string is V Example...

Page 843: ...allowDomain Lets SWF files in the identified domains access objects and variables in the calling SWF file or in any other SWF file from the same domain as the calling SWF file System security allowIn...

Page 844: ...to allow access by SWF files that are running in Flash Player 7 or later System security allowDomain www domain com store domain com Also for files running in Flash Player 7 or later you can t use thi...

Page 845: ...will already be loaded by the time the child loads Example The SWF file located at www macromedia com MovieA swf contains the following lines System security allowDomain www shockwave com loadMovie ht...

Page 846: ...ayer 6 can use System security allowDomain to permit HTTP to HTTPS access However because security is implemented differently in Flash Player 7 you must use System Security allowInsecureDomain to perm...

Page 847: ...System security allowInsecureDomain 847 See also System security allowDomain System exactSettings...

Page 848: ...Player 7 0 19 0 can load policy files from arbitrary locations as shown in the following example System security loadPolicyFile http foo com sub dir pf xml This causes Flash Player to retrieve a poli...

Page 849: ...ify the ports to which access is granted When a policy file comes from a port lower than 1024 it can grant access to any ports when a policy file comes from port 1024 or higher it can grant access onl...

Page 850: ...or the System class Method Description System setClipboard Replaces the contents of the system Clipboard with a text string System showSettings Displays a Flash Player Settings panel Method Descriptio...

Page 851: ...perty is false in a SWF file hosted at here xyz com and true in a SWF file hosted at xyz com both files will use the same settings and data namely those in the xyz com directory If this isn t the beha...

Page 852: ...the player has stored the shared objects created by the Flash Player 6 SWF file in a folder that s specific to the superdomain of that SWF file you should use superdomain rules for shared object retri...

Page 853: ...ned an onStatus function for that particular instance then Flash uses the function you define for System onStatus instead Note The Camera and Microphone classes also have onStatus handlers but do not...

Page 854: ...string Example The following example places the phrase Hello World onto the system Clipboard System setClipboard Hello world The following example creates two text fields at runtime called in_txt and...

Page 855: ...icrophone gain and echo suppression settings For example if your application requires the use of a camera you can tell the user to select Allow in the Privacy Settings panel and then issue a System sh...

Page 856: ...epage to true Add the following code as the first line of code in the first frame of the SWF file that is loading the data System useCodepage true When this code is present Flash Player interprets ext...

Page 857: ...he 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 notation us...

Page 858: ...e Formatting text with Cascading Style Sheets in Using ActionScript in Flash Method summary for the TextField StyleSheet class Event handler summary for the TextField StyleSheet class L Method Descrip...

Page 859: ...e following ActionScript to your AS or FLA file var my_styleSheet TextField StyleSheet new TextField StyleSheet my_styleSheet onLoad function success Boolean if success trace Styles loaded var styles_...

Page 860: ...styles from the my_styleSheet object are removed Create a new style sheet object var my_styleSheet TextField StyleSheet new TextField StyleSheet my_styleSheet onLoad function success Boolean if succes...

Page 861: ...following code import TextField StyleSheet class StyleSheetTracer StyleSheetTracer displayFromURL This method displays the CSS style sheet at URL url to the Output Panel static function displayFromURL...

Page 862: ...e In styles css heading font family Arial Helvetica sans serif font size 24px font weight bold mainBody font family Arial Helvetica sans serif font size 12px font weight normal And finally in a FLA or...

Page 863: ...yleSheet that contains two styles heading and bodyText It then invokes the style sheet object s getStyleNames method assigns the results to the array names_array and displays the contents of the array...

Page 864: ...y loading style sheets using ActionScript 2 0 see the entry for TextField StyleSheet getStyle The following example loads the CSS file named styles css into the style sheet object styleObj When the fi...

Page 865: ...inished loading successfully the style sheet object is applied to a TextField object named news_txt this createTextField news_txt 999 10 10 320 240 news_txt multiline true news_txt wordWrap true news_...

Page 866: ...ing subclasses in Using ActionScript in Flash Example The following example parses the CSS in css_str The ActionScript displays information about whether it parsed successfully and then displays the p...

Page 867: ...le The following code adds a style named emphasized to the style sheet myStyleSheet The style includes two style properties color and fontWeight The style object is defined with the operator myStyleSh...

Page 868: ...olor 000000 Note The line of code delete styleObj deletes the original style object passed to setStyle While not necessary this step reduces memory usage because Flash Player creates a copy of the sty...

Page 869: ...properties Description Method extends the CSS parsing capability Advanced developers can override this method by extending the TextField StyleSheet class For more information see Creating subclasses...

Page 870: ...nts on the player s host system as an array TextField getDepth Returns the depth of a text field TextField getNewTextFormat Gets the default text format assigned to newly inserted text TextField getTe...

Page 871: ...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 872: ...ther 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 Th...

Page 873: ...er 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 statement to send the instance name of the text...

Page 874: ...874 Chapter 2 ActionScript Language Reference my_txt addListener txtListener See also TextField onChanged TextField onScroller TextField removeListener...

Page 875: ...th a text field Example The following code sets the _alpha property of a text field named my_txt to 20 Create a new font symbol in the library by selecting New Font from the Library options menu Then...

Page 876: ...eaning the right side of the text field will remain fixed and any resizing of a single line text field will be on the left side If the text includes a line break for example n or r then the bottom sid...

Page 877: ...define a function that executes when a user clicks the mouse myMouseListener onMouseDown function left_txt autoSize left left_txt text This is much longer text center_txt autoSize center center_txt t...

Page 878: ...kground fill If false the text field has no background fill Example The following example creates a text field with a button that toggles the background color of the field this createTextField my_txt...

Page 879: ...Number Description Property the color of the text field background Default is 0xFFFFFF white This property may be retrieved or set even if there currently is no background but the color is only visib...

Page 880: ...n Property if true the text field has a border If false the text field has no border Example The following example creates a text field called my_txt sets the border property to true and displays some...

Page 881: ...0000 black This property may be retrieved or set even if there is currently no border Example The following example creates a text field called my_txt sets the border property to true and displays som...

Page 882: ...g example 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 getNextH...

Page 883: ...e The following example creates two text fields called first_txt and second_txt The white space is removed from the second text field Add the following ActionScript to your FLA or AS file var my_str S...

Page 884: ...mple In this example you need to create a dynamic text field called my_txt and then use the following ActionScript to embed fonts and rotate the text field The reference to my font refers to a Font sy...

Page 885: ...pths Create a dynamic text field on the Stage Add the following ActionScript to your FLA or AS file which dynamically creates two text fields at runtime and outputs their depths this createTextField f...

Page 886: ...ch as my_txt when you call this method This method returns names of fonts on the player s host system as an array It does not return names of all fonts in currently loaded SWF files The names are of t...

Page 887: ...ewly inserted text such as text inserted with the replaceSel method or text entered by a user receives When getNewTextFormat is invoked the TextFormat object returned has all of its properties defined...

Page 888: ...d meaning that it has different values at different points in the text has a value of null Usage 2 Returns a TextFormat object containing a copy of the text field s text format at index Usage 3 Return...

Page 889: ...ight Availability Flash Player 6 Usage my_txt _height Number Description Property the height of the text field in pixels Example The following code example sets the height and width of a text field my...

Page 890: ...there are multiple fonts on a line the height of the line adjusts to fit the largest font in use Note The hscroll property is zero based not one based like the vertical scrolling property TextField s...

Page 891: ...l property is true the text field is an HTML text field If html is false the text field is a non HTML text field Example The following example creates a text field that sets the html property to true...

Page 892: ...ot an HTML text 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 tru...

Page 893: ...roperty returns the same value as text length but is faster A character such as tab t counts as one character Example The following example outputs the number of characters in the date_txt text field...

Page 894: ...an 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 a user can enter Example The follow...

Page 895: ...croll 895 TextField maxhscroll Availability Flash Player 6 Usage my_txt maxhscroll Number Description Read only property indicates the maximum value of TextField hscroll Example See the example for Te...

Page 896: ...Down_btn to scroll the text field Add the following ActionScript to your FLA or AS file this createTextField scroll_txt this getNextHighestDepth 10 10 160 20 this createTextField my_txt this getNextHi...

Page 897: ...add resizing functionality not shown this createTextField news_txt this getNextHighestDepth 10 10 320 240 news_txt border true news_txt wordWrap true news_txt multiline true news_txt text To see the c...

Page 898: ...lable_txt field has the mouseWheelEnabled property set to true so scrollable_txt scrolls when you click the field and roll the mouse wheel The nonscrollable_txt field does not scroll if you click the...

Page 899: ...e if the value is false the text field is a single line text field Example The following example creates a multiline text field called fontList_txt that displays a long multiline list of fonts var fon...

Page 900: ...he following ActionScript to your FLA or AS file which dynamically creates two text fields at runtime and displays their depths in the Output panel this createTextField first_mc this getNextHighestDep...

Page 901: ...txt as the parameter that is passed to the onChanged event handler The parameter is then used in a trace statement to send the instance name of the text field to the Output panel this createTextField...

Page 902: ...value null Example The following example creates two text fields called first_txt and second_txt When you give focus to a text field information about the text field with current focus and the text f...

Page 903: ...e of the text field to the Output panel myTextField onScroller function my_txt TextField trace my_txt _name scrolled The TextField onScroller event handler is commonly used to implement scroll bars Sc...

Page 904: ...or AS file this createTextField scroll_txt this getNextHighestDepth 10 10 160 20 this createTextField my_txt this getNextHighestDepth 10 30 320 240 my_txt multiline true my_txt wordWrap true for var i...

Page 905: ...Event handler invoked when a text field receives keyboard focus The oldFocus parameter is the object that loses the focus For example if the user presses the Tab key to move the input focus from a bu...

Page 906: ...text fields and outputs information about the _parent of each object The first text field first_txt is created on the main Timeline The second text field second_txt is created inside the movie clip ca...

Page 907: ...g the shortcuts to discover a password on an unattended computer Example The following example creates two text fields username_txt and password_txt Text is entered into both text fields however passw...

Page 908: ...ty The _quality property can be set to the following values LOW Low rendering quality Graphics are not anti aliased and bitmaps are not smoothed MEDIUM Medium rendering quality Graphics are anti alias...

Page 909: ...TextField addListener Example The following example creates an input text field called my_txt When the user types into the field information about the number of characters in the text field is displa...

Page 910: ...hen you call this method the text field is removed This method is similar to MovieClip removeMovieClip Example The following example creates a text field that you can remove from the Stage when you cl...

Page 911: ...text field with text on the Stage When you select some text and then right click or Control click over the text field you can select Enter current date from the context menu This selection calls a fu...

Page 912: ...called my_txt and assigns the text dog house net to the field The indexOf method is used to find the first occurrence of the specified symbol If the symbol is found the specified text between the inde...

Page 913: ...ted characters If the string does not begin with no characters are initially accepted and succeeding characters in the string are included in the set of accepted characters Example The following examp...

Page 914: ...ot supported for text files that use device fonts You must use embedded fonts to use _rotation with a text field Example In this example you need to create a dynamic text field called my_txt and then...

Page 915: ...ine the height of the line adjusts to fit the largest font in use For more information on scrolling text see Creating scrolling text in Using Flash Example The following example sets the maximum value...

Page 916: ...text in the text field does not respond to selection commands from the mouse or keyboard and the text cannot be copied using the Copy command If selectable is set to true the text in the text field ca...

Page 917: ...the default new text format The new default text format is specified by textFormat which is a TextFormat object Example In the following example a new text field called my_txt is created at runtime an...

Page 918: ...Any property of textFormat that is set to null will not be applied By default all of the properties of a newly created TextFormat object are set to null There are two types of formatting information i...

Page 919: ...and applied to the my_txt text field var format1_fmt TextFormat new TextFormat format1_fmt font Arial var format2_fmt TextFormat new TextFormat format2_fmt font Courier var string1 String Sample strin...

Page 920: ...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 createTextField news_txt this getNextHighe...

Page 921: ...e text field Save the following two CSS files in the same directory as the FLA or AS file you created previously in styles css important color FF0000 bold font weight bold headline color 000000 font f...

Page 922: ...Example The following example creates several 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 aut...

Page 923: ...r in the tab ordering is undefined The custom tab ordering defined by the tabIndex property is flat This means that no attention is paid to the hierarchical relationships of objects in the SWF file Al...

Page 924: ...924 Chapter 2 ActionScript Language Reference one_txt tabIndex 3 two_txt tabIndex 1 three_txt tabIndex 2 four_txt tabIndex 4 See also Button tabIndex MovieClip tabIndex...

Page 925: ...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 Example The following ActionScript creates a tex...

Page 926: ...HTML formatted string of text to the field When you trace the htmlText property the Output panel displays the HTML formatted string When you trace the value of the text property the unformatted strin...

Page 927: ...o represent color values Each digit has sixteen possible values or characters The characters range from 0 to 9 and then A to F Black is represented by 000000 and white at the opposite end of the color...

Page 928: ...operty is then used to resize the text field and the new height and width will also be displayed in the Output panel this createTextField my_txt 99 10 10 100 300 my_txt text Sample text trace textHeig...

Page 929: ...th 929 TextField textWidth Availability Flash Player 6 Usage my_txt textWidth Number Description Property indicates the width of the text Example See the example for TextField textHeight See Also Text...

Page 930: ...t and password_txt Text is entered into both text fields however password_txt has the password property set to true Therefore the characters display as asterisks instead of as characters in the passwo...

Page 931: ...at loads into it this createTextField my_txt 1 10 10 100 22 trace my_txt _url var mclListener Object new Object mclListener onLoadInit function target_mc MovieClip trace target_mc _url var holder_mcl...

Page 932: ...property is String Example The following example creates a text field called my_txt and associates the variable today_date with the text field When you change the variable today_date then the text tha...

Page 933: ...isible _visible property set to false are disabled Example The following example creates a text field called my_txt A button called visible_btn toggles the visibility of my_txt this createTextField my...

Page 934: ...rder 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...

Page 935: ...s not have word wrap Example The following example demonstrates how wordWrap affects long text in a text field that s created at runtime this createTextField my_txt 99 10 10 100 200 my_txt text This i...

Page 936: ...kwise the enclosed text field inherits a coordinate system that is rotated 90 counterclockwise The text field s coordinates refer to the registration point position Example The following example creat...

Page 937: ...relation to the my_txt instance Add the following ActionScript to a FLA or AS file this createTextField mouse_txt this getNextHighestDepth 10 10 200 22 mouse_txt border true this createTextField textf...

Page 938: ...default registration point is 0 0 Example The following example scales the my_txt instance when you click the scaleUp_btn and scaleDown_btn instances this createTextField my_txt 99 10 40 100 22 my_tx...

Page 939: ...corner of the Stage as 0 0 If the text field is inside another movie clip that has transformations the text field is in the local coordinate system of the enclosing movie clip Thus for a movie clip r...

Page 940: ...Field _ymouse Availability Flash Player 6 Usage my_txt _ymouse Number Description Read only property indicates the y coordinate of the mouse position relative to the text field Example See the example...

Page 941: ...e Number Description Property the vertical scale of the text field as applied from the registration point of the text field expressed as a percentage The default registration point is 0 0 Example See...

Page 942: ...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 943: ...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 944: ...any omitted parameters are treated as null Example The following example creates a TextFormat object formats the stats_txt text field and creates a new text field to display the text in Define a TextF...

Page 945: ...ragraph is centered If right the paragraph is right aligned The default value is null which indicates that the property is undefined Example The following example creates a text field with a border an...

Page 946: ...normal indentation TextFormat indent affects only the first line of each paragraph If this property is null the TextFormat object does not specify block indentation Example This example creates a tex...

Page 947: ...cates that the property is undefined If the value is true then the text is boldface Example The following example creates a text field that includes characters in boldface var my_fmt TextFormat new Te...

Page 948: ...t value is null Example The following example creates a new text field at runtime and enters a string with a line break into the field The TextFormat class is used to format the characters by adding b...

Page 949: ...ents for example 0xFF0000 is red and 0x00FF00 is green Example The following example creates a text field and sets the text color to red var my_fmt TextFormat new TextFormat my_fmt blockIndent 20 this...

Page 950: ...default value is null which indicates that the property is undefined Example The following example creates a text field and sets the font to Courier this createTextField mytext 1 100 100 100 100 myte...

Page 951: ...h 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 provi...

Page 952: ...bject and 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_...

Page 953: ...w with improved text metrics Obtain text measurement information for the string wrapped at 100 pixels var metrics Object my_fmt getTextExtent textToDisplay 100 Create a new TextField object using the...

Page 954: ...aph The default value is null which indicates that the property is undefined Example The following example creates a text field and sets the indentation to 10 this createTextField mytext 1 100 100 100...

Page 955: ...fault value is null which indicates that the property is undefined Example The following example creates a text field and sets the text style to italic this createTextField mytext 1 100 100 100 100 my...

Page 956: ...es The default value is null which indicates that the property is undefined Example The following example creates a text field and sets the leading to 10 var my_fmt TextFormat new TextFormat my_fmt le...

Page 957: ...null which indicates that the property is undefined Example The following example creates a text field and sets the left margin to 20 points this createTextField mytext 1 100 100 100 100 mytext multil...

Page 958: ...value is null which indicates that the property is undefined Example The following example creates a text field and sets the right margin to 20 points this createTextField mytext 1 100 100 100 100 my...

Page 959: ...which indicates that the property is undefined Example The following example creates a text field and sets the text size to 20 points this createTextField mytext 1 100 100 100 100 mytext multiline tru...

Page 960: ...e creates two text fields one with tab stops every 20 pixels and the other with tab stops every 40 pixels this createTextField mytext 1 100 100 200 100 mytext multiline true mytext wordWrap true mytex...

Page 961: ...frame and _top specifies the top level frame in the current window If the TextFormat url property is an empty string or null you can get or set this property but the property will have no effect Examp...

Page 962: ...U tag but the latter is not true underlining because it does not skip descenders correctly The default value is null which indicates that the property is undefined Example The following example creat...

Page 963: ...yperlink The default value is null which indicates that the property is undefined Example This example creates a text field that is a hyperlink to the Macromedia website var myformat TextFormat new Te...

Page 964: ...of the first occurrence of specified text TextSnapshot getCount Returns the number of characters TextSnapshot getSelected Specifies whether any of the text in the specified range has been selected by...

Page 965: ...match the case of the string in textToFind Returns The zero based index position of the first occurrence of the specified text or 1 Description Method searches the specified TextSnapshot object and r...

Page 966: ...ters in a TextSnapshot object Example The following example illustrates how you can output the number of characters in a specified TextSnapshot object To use this code place a static text field contai...

Page 967: ...eturns A Boolean value of true if at least one character in the given range has been selected by the corresponding TextSnapshot setSelected command false otherwise Description Method returns a Boolean...

Page 968: ...ected text is returned without any characters added Example The following example illustrates how to use this method To use this code place a static text field containing the text TextSnapshot Example...

Page 969: ...TextSnapshot getSelectedText 969 When you test the SWF file you see a colored rectangle around the specified characters See also TextSnapshot getSelected...

Page 970: ...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 971: ...TextSnapshot getText 971 trace count output 20 trace theText output TextSnapshot Example See also TextSnapshot getSelectedText...

Page 972: ...or pass a value of 0 for maxDistance the location specified by the x y coordinates must lie inside the bounding box of my_snap This method functions correctly only for fonts that include character me...

Page 973: ...ch character the mouse pointer is over if any var hitIndex Number my_ts hitTestTextNearPos _xmouse _ymouse 0 deselect everything my_ts setSelected 0 my_ts getCount false if hitIndex 0 select the singl...

Page 974: ...this add a dynamic text field that uses that font select Character Options for that dynamic text field and then specify that font outlines should be embedded for at least one character It doesn t mat...

Page 975: ...t setSelectColor 975 trace theText output Txt trace firstCharIsSelected output true trace secondCharIsSelected output false When you test the SWF file you see a colored rectangle around the specified...

Page 976: ...ding box is defined by TextSnapshot setSelectColor To select or deselect all characters pass a value of 0 for from and TextSnapshot getCount or any very large number for to To specify a single charact...

Page 977: ...t Number my_snap getCount my_snap setSelectColor 0xFF0000 Set the selection color to red my_snap setSelected 0 4 true Select the first four characters my_snap setSelected 1 2 false Deselect the second...

Page 978: ...r to a variable defined in a class file Create ApplyThis as and enter the following code class ApplyThis var str String Defined in ApplyThis as function conctStr x String String return x x function ad...

Page 979: ...Number Void this radius radius this area Math PI Math pow radius 2 var myCircle new Circle 4 trace myCircle area In the following statement assigned to a frame inside a movie clip the keyword this re...

Page 980: ...Email email String if email indexOf 1 throw new Error Invalid email address checkEmail someuser_theirdomain com The following code then calls the checkEmail function within a try code block If the ema...

Page 981: ...Of 1 throw new InvalidEmailAddress try checkEmail Joe Smith catch e this createTextField error_txt this getNextHighestDepth 0 0 100 22 error_txt autoSize true error_txt text e toString See also Error...

Page 982: ...on parameter to check whether a condition exists or to display values in the Output panel The trace statement is similar to the alert function in JavaScript You can use the Omit Trace Actions command...

Page 983: ...nt 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 trace your statements...

Page 984: ...s if the try block 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...

Page 985: ...e 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 myInterval setInterval this...

Page 986: ...rows 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 MalformedReco...

Page 987: ...the RecordSet class It defines catch blocks for each type of error that is thrown by sortRows import RecordSet var myRecordSet RecordSet new RecordSet try myRecordSet sortRows trace everything is fin...

Page 988: ...ether the expression 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...

Page 989: ...null When null and undefined are compared with the equality operator they compare as equal However when null and undefined are compared with the strict equality operator they compare as not equal Exa...

Page 990: ...990 Chapter 2 ActionScript Language Reference The following result is displayed in the Output panel The value of x is undefined x is undefined typeof x is undefined null and undefined are equal...

Page 991: ...t 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 tra...

Page 992: ...age into that 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...

Page 993: ...ans of loadMovieNum from Flash Player To unload a SWF or image that was loaded with MovieClip loadMovie use unloadMovie instead of unloadMovieNum Example The following example loads an image into a SW...

Page 994: ...n works 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 handle...

Page 995: ...When you use var you can strictly type the variable For more information see Strict data typing in Using ActionScript in Flash Note You must also use var when declaring properties inside class definit...

Page 996: ...deo stream first place a Video object on the Stage Then use Video attachVideo to attach the video stream to the Video object To place a Video object on the Stage 1 If the Library panel isn t visible s...

Page 997: ...ains only audio the audio portion of an FLV files is played automatically when the NetStream play command is issued If you want to control the audio associated with an FLV file you can use MovieClip a...

Page 998: ...having to hide the Video object Example The following example pauses and clears video1 flv that is playing in a Video object called my_video when the user clicks the pause_btn instance var pause_btn...

Page 999: ...example plays video1 flv in the my_video video object and lets the user change the deblocking filter behavior on video1 flv Add a video object called my_video and a ComboBox instance called deblockin...

Page 1000: ...with a code property of NetStream Buffer Full If you call it when the code property is NetStream Play Start the height and width values will be 0 because the Video object doesn t yet have the height...

Page 1001: ...Video height 1001 my_mc _height my_mc my_video height See also MovieClip _height Video width...

Page 1002: ...perty that is applied to the video my_video when it plays in a SWF file Create a button called smoothing_btn and add the following ActionScript to your FLA or AS file this createTextField smoothing_tx...

Page 1003: ...e same as the Camera width property of the Camera object that is capturing the video stream For FLV files this value is the width of the file that was exported as an FLV file You may want to use this...

Page 1004: ...d to test for undefined values if someUndefinedVariable void 0 trace someUndefinedVariable is undefined The previous code can also be written in the following way if someUndefinedVariable undefined tr...

Page 1005: ...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 execution resumes...

Page 1006: ...1006 Chapter 2 ActionScript Language Reference i 3 The following result is displayed in the Output panel 0 3 6 9 12 15 18 See also do while continue for for in...

Page 1007: ...tionScript starts at the beginning of the scope chain specified by the object and searches for the identifier at each level of the scope chain in a specific order The scope chain used by the with stat...

Page 1008: ...p 3 The following code snippet shows how to write the preceding code without using a with statement someOther_mc _x 50 someOther_mc _y 100 someOther_mc gotoAndStop 3 The with statement is useful for a...

Page 1009: ...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 the...

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

Page 1011: ...any of the methods of the XML class Note Use the createElement and createTextNode methods to add elements and text nodes to an XML document tree Example The following example creates a new empty XML...

Page 1012: ...de to set the same header name each successive value replaces the value set in the previous call You cannot add or change the following standard HTTP headers using this method Accept Ranges Age Allow...

Page 1013: ...ode is placed in the new tree structure after it is removed from its existing parent node Example This example does the following things in the order shown Creates two empty XML documents doc1 and doc...

Page 1014: ...cloneNode true doc1 appendChild clone trace doc1 doc1 output doc1 root trace doc2 doc2 output doc2 root create a new node to append to root node named clone of doc1 var newNode XMLNode doc1 createElem...

Page 1015: ...bute named color you would retrieve 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 exam...

Page 1016: ...s create a new XML document var doc XML new XML create a root node var rootNode XMLNode doc createElement rootNode create three child nodes var oldest XMLNode doc createElement oldest var middle XMLNo...

Page 1017: ...previousSibling all have a value of null If the deep parameter is set to false or the my_xml node has no child nodes firstChild and lastChild are also null Example The following example shows how to u...

Page 1018: ...dded rootNode oldest middle middle youngest rootNode create a copy of rootNode using cloneNode to demonstrate a deep copy var rootClone XMLNode rootNode cloneNode true insert the clone which contains...

Page 1019: ...ument and checks its default content type create a new XML document var doc XML new XML trace the default content type trace doc contentType output application x www form urlencoded The following exam...

Page 1020: ...at represents the element This method and the XML createTextNode method are the constructor methods for creating nodes for an XML object Example The following example creates three XML nodes using the...

Page 1021: ...nodes using the createTextNode method and places them into existing XML nodes create an XML document var doc XML new XML create three XML nodes using createElement var element1 XMLNode doc createEleme...

Page 1022: ...1022 Chapter 2 ActionScript Language Reference See also XML createElement...

Page 1023: ...XML parser is not a validating parser The DOCTYPE declaration is read by the parser and stored in the XML docTypeDecl property but no DTD validation is performed If no DOCTYPE declaration was encounte...

Page 1024: ...de var rootNode XMLNode doc createElement rootNode create three child nodes var oldest XMLNode doc createElement oldest var middle XMLNode doc createElement middle var youngest XMLNode doc createEleme...

Page 1025: ...sterArray i j stringNode firstChild nodeValue To view the entire script see XML_languagePicker fla in the HelpExamples folder Windows Program Files Macromedia Flash MX 2004 Samples HelpExamples Macint...

Page 1026: ...the parameter refers to a valid XML file using HTTP If you attempt to use this example to load a local file that resides on your hard disk this example will not work properly because in test movie mod...

Page 1027: ...tal Availability Flash Player 6 Usage my_xml getBytesTotal Number Parameters None Returns An integer Description Method returns the size in bytes of the XML document Example See example for XML getByt...

Page 1028: ...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_xml XML new XML login username hank username password rudolp...

Page 1029: ...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 this examp...

Page 1030: ...will be preserved set the ignoreWhite property to false default value flooring ignoreWhite false output line breaks added for clarity house kitchen ceramic tile kitchen bathroom linoleum bathroom foye...

Page 1031: ...ode into the XML object s child list before the beforeNode node If the beforeNode parameter is undefined or null the node is added using the appendChild method If beforeNode is not a child of my_xml t...

Page 1032: ...st 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 createElement rootNo...

Page 1033: ...w XML document var doc XML new XML rootNode oldest middle youngest rootNode var rootNode XMLNode doc firstChild use lastChild to iterate through the child nodes of rootNode for var aNode XMLNode rootN...

Page 1034: ...at store someDomain com because both files are in the same superdomain of someDomain com In SWF files of any version running in Flash Player 7 or later the url parameter must be in exactly the same d...

Page 1035: ...XML object flooring onLoad function success trace flooring load the XML into the flooring object flooring load flooring xml For the contents of the flooring xml file and the output that this example...

Page 1036: ...g example uses the XML loaded property in a simple script var my_xml XML new XML my_xml ignoreWhite true my_xml onLoad function success Boolean trace success success trace loaded my_xml loaded trace s...

Page 1037: ...property cannot be used to manipulate child nodes use the appendChild insertBefore and removeNode methods to manipulate child nodes Example The following example is an excerpt from the example for th...

Page 1038: ...MLNode 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...

Page 1039: ...XML nodeName 1039 trace aNode nodeName t aNode firstChild nodeValue The following node names are displayed in the Output panel output username hank password rudolph See also XML nodeType...

Page 1040: ...class only supports 1 ELEMENT_NODE and 3 TEXT_NODE Example The following example creates an element node and a text node and checks the node type of each create an XML document var doc XML new XML cr...

Page 1041: ...ype 1041 var myTextNode XMLNode doc createTextNode textNode place the new node into the XML tree myNode appendChild myTextNode trace myNode nodeType trace myTextNode nodeType output 1 3 See also XML n...

Page 1042: ...ppendChild myNode create an XML text node using createTextNode var myTextNode XMLNode doc createTextNode myTextNode place the new node into the XML tree myNode appendChild myTextNode trace myNode node...

Page 1043: ...i my_xml firstChild childNodes length i trace t my_xml firstChild childNodes i firstChild nodeValue The following information is displayed in the Output panel using firstChild morton good amp evil us...

Page 1044: ...of using the Flash XML parser The src parameter is a string that contains XML text downloaded from the server unless an error occurs during the download in which case the src parameter is undefined By...

Page 1045: ...default implementation you must assign a function that contains custom actions Example The following example includes ActionScript for a simple e commerce storefront application The sendAndLoad method...

Page 1046: ...the parent node of the username node in the Output panel var my_xml XML new XML login username morton username password good amp evil password login first child is the login node var rootNode XMLNode...

Page 1047: ...ML object with the resulting XML tree Any existing trees in the XML object are discarded Example The following example creates and parses an XML packet var xml_str String state name California city Sa...

Page 1048: ...sibling node This property cannot be used to manipulate child nodes use the XML appendChild XML insertBefore and XML removeNode methods to manipulate child nodes Example The following example is an e...

Page 1049: ...packet and then deletes the specified 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_...

Page 1050: ...al if you do not specify a window parameter it is the same as specifying _self Returns Nothing Description Method encodes the specified XML object into an XML document and sends it to the specified UR...

Page 1051: ...a SWF file at www someDomain com can load data from sources at store someDomain com because both files are in the same superdomain of someDomain com In SWF files of any version running in Flash Player...

Page 1052: ..._xml ignoreWhite true myLoginReply_xml onLoad myOnLoad my_xml sendAndLoad http www flash mx com mm login_xml cfm myLoginReply_xml function myOnLoad success Boolean if success if myLoginReply_xml first...

Page 1053: ...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 1054: ...Message Out of memory break case 8 errorMessage An attribute value was not properly terminated break case 9 errorMessage A start tag was not matched with an end tag break case 10 errorMessage An end t...

Page 1055: ...ring method outputs the document s XML declaration stored in the XML xmlDecl property followed by the document s DOCTYPE declaration stored in the XML docTypeDecl property followed by the text represe...

Page 1056: ...field displays properties of the XML packet that loads into the SWF file The doc type declaration displays in my_txt Add the following ActionScript to your FLA or AS file var my_fmt TextFormat new Tex...

Page 1057: ...XML xmlDecl 1057 See also XML docTypeDecl XML toString...

Page 1058: ...g XML class entries See also XML class Property method or collection Corresponding XML class entry appendChild XML appendChild attributes XML attributes childNodes XML childNodes cloneNode XML cloneNo...

Page 1059: ...is restriction is that the server daemons that communicate with the XMLSocket object must also be assigned to port numbers greater than or equal to 1024 Port numbers below 1024 are often used by syste...

Page 1060: ...o a server Example The following example creates an XMLSocket object var socket XMLSocket new XMLSocket Method Description XMLSocket close Closes an open socket connection XMLSocket connect Establishe...

Page 1061: ...urns Nothing Description Method closes the connection specified by XMLSocket object Example The following simple example creates an XMLSocket object attempts to connect to the server and then closes t...

Page 1062: ...com specifying null for the host parameter is the same as entering the IP address for www yoursite com In SWF files running in a version of the player earlier than Flash Player 7 host must be in the...

Page 1063: ...a connection could not be established Example The following example uses XMLSocket connect to connect to the host where the SWF file resides and uses trace to display the return value indicating the...

Page 1064: ...tion is closed by the server The default implementation of this method performs no actions To override the default implementation you must assign a function containing custom actions Example The follo...

Page 1065: ...ng the constructor method the script defines the custom function to be executed when the onConnect event handler is invoked The function controls the screen to which users are taken depending on wheth...

Page 1066: ...1066 Chapter 2 ActionScript Language Reference if socket connect null 2000 gotoAndStop connectionFailed else gotoAndStop waitForConnection See also function XMLSocket connect...

Page 1067: ...is a useful if you re transmitting arbitrarily formatted data packets and you d prefer to manipulate the data directly when it arrives rather than have Flash Player parse the data as XML By default t...

Page 1068: ...ion 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...

Page 1069: ...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 1070: ...1070 Chapter 2 ActionScript Language Reference...

Page 1071: ...1 APPENDIX Deprecated Language Elements The evolution of ActionScript has deprecated many elements of the language This appendix lists the deprecated items in alphabetical order and suggests alternati...

Page 1072: ...string2 A string Returns Nothing Description Operator concatenates two or more strings The add operator replaces the Flash 4 operator Flash Player 4 files that use the operator are automatically conve...

Page 1073: ...logical AND operator Usage condition1 and condition2 Parameters condition1 condition2 Conditions or expressions that evaluate to true or false Returns Nothing Description Operator performs a logical...

Page 1074: ...to apply anti aliasing this smooths bitmaps if the SWF file does not contain animation and is the default value Specify 0 low quality to prevent anti aliasing Example Add a button instance on the Sta...

Page 1075: ...ed frame without moving the playhead to that frame Local variables do not exist after the script executes If variables are not declared inside a block but the action list was executed with a call acti...

Page 1076: ...favor of String fromCharCode Usage chr number Parameters number An ASCII code number Returns Nothing Description String function converts ASCII code numbers to characters Example The following example...

Page 1077: ...perator Usage expression1 eq expression2 Parameters expression1 expression2 Numbers strings or variables Returns Nothing Description Operator comparison compares two expressions for equality and retur...

Page 1078: ...or equal to operator Usage expression1 ge expression2 Parameters expression1 expression2 Numbers strings or variables Returns Nothing Description Operator comparison compares the string representation...

Page 1079: ...the greater than operator Usage expression1 gt expression2 Parameters expression1 expression2 Numbers strings or variables Description Operator comparison compares the string representation of express...

Page 1080: ...file Specify 2 best quality to apply high quality with bitmap smoothing always on Specify 1 high quality to apply anti aliasing this will smooth bitmaps if the SWF file does not contain animation Spec...

Page 1081: ...Operator inequality tests for the exact opposite of the equality operator If expression1 is equal to expression2 the result is false As with the equality operator the definition of equal depends on th...

Page 1082: ...label that must be loaded before the next statement is executed statement s The instructions to execute if the specified scene or scene and frame are loaded Returns Nothing Description Action checks w...

Page 1083: ...rameters value A number to be rounded to an integer Returns Nothing Description Function converts a decimal number to an integer value by truncating the decimal value This function is equivalent to Ma...

Page 1084: ...n favor of the less than or equal to operator Usage expression1 le expression2 Parameters expression1 expression2 Numbers strings or variables Returns Nothing Description Operator comparison compares...

Page 1085: ...o perform the same operations Usage length expression length variable Parameters expression A string variable The name of a variable Returns The length of the specified string or variable Description...

Page 1086: ...s deprecated in Flash 5 in favor of the less than operator Usage expression1 lt expression2 Parameters expression1 expression2 Numbers strings or variables Description Operator comparison compares exp...

Page 1087: ...l Description Read only property indicates the line number of the top line of visible text in a text field when the bottom line in the field is also visible The maxscroll property works with the scrol...

Page 1088: ...function was deprecated in favor of the String fromCharCode method Usage mbchr number Parameters number The number to convert to a multibyte character Returns A string Description String function con...

Page 1089: ...ability Flash Player 4 This function was deprecated in favor of the String class Usage mblength string Parameters string A string Returns A number Description String function returns the length of the...

Page 1090: ...unction was deprecated in Flash 5 in favor of String charCodeAt Usage mbord character Parameters character The character to convert to a multibyte number Returns A number Description String function c...

Page 1091: ...s value The multibyte string from which to extract a new multibyte string index The number of the first character to extract count The number of characters to include in the extracted string not inclu...

Page 1092: ...ile Specify 2 best quality to apply high quality with bitmap smoothing always on Specify 1 high quality to apply anti aliasing this will smooth bitmaps if the SWF file does not contain animation Speci...

Page 1093: ...in favor of the inequality operator Usage expression1 ne expression2 Parameters expression1 expression2 Numbers strings or variables Returns A Boolean value Description Operator comparison compares ex...

Page 1094: ...er 4 This operator was deprecated in favor of the logical NOT operator Usage not expression Parameters expression A variable or other expression that converts to a Boolean value Description Operator p...

Page 1095: ...al OR operator Usage condition1 or condition2 Parameters condition1 2 An expression that evaluates to true or false Returns Nothing Description Operator evaluates condition1 and condition2 and if eith...

Page 1096: ...function was deprecated in favor of the methods and properties of the String class Usage ord character Parameters character The character to convert to an ASCII code number Returns Nothing Description...

Page 1097: ...f Math random Usage random value Parameters value An integer Returns An integer Description Function returns a random integer between 0 and one less than the integer specified in the value parameter E...

Page 1098: ...roll property defines where the text field begins displaying content after you set it Flash Player updates it as the user scrolls through the text field The scroll property is useful for directing use...

Page 1099: ...string from which to extract the new string index The number of the first character to extract count The number of characters to include in the extracted string not including the index character Retu...

Page 1100: ...articular frame in that clip For example you might assign tellTarget to buttons that stop or start movie clips on the Stage or prompt movie clips to jump to a particular frame In Flash 5 or later you...

Page 1101: ...1 If you need to issue multiple commands to the ball instance you can use the with action as shown in the following statement on release with _parent ball gotoAndPlay 2 _alpha 15 _xscale 50 _yscale 50...

Page 1102: ...hquality Description Property global specifies the level of anti aliasing applied to the current SWF file Specify 2 best quality to apply high quality with bitmap smoothing always on Specify 1 high qu...

Page 1103: ...Nothing Description Function turns anti aliasing on and off in Flash Player Anti aliasing smooths the edges of objects and slows down SWF playback This action affects all SWF files in Flash Player Ex...

Page 1104: ...1104 Appendix Deprecated Language Elements...

Reviews: