20.5. Alphabetical Language ReferenceThe following entries document ActionScript's objects and classes. Refer to the index for the operators and statements covered elsewhere in this book.
AvailabilityFlash 5 Synopsisarguments[elem] arguments.propertyName Properties
DescriptionThe Arguments object is stored in the local arguments variable of every function and is accessible only while a function is executing. Arguments is both an array and an object. As an array, arguments stores the values of the parameters passed to the currently executing function. For example, arguments[0] is the first passed parameter, arguments[1] is the second passed parameter, and so on. As an object, Arguments stores the callee property, which can be used to identify or invoke the current function. See Also"The arguments Object" in Chapter 9, "Functions"
AvailabilityFlash 5 Synopsisarguments.callee AccessRead/write DescriptionThe callee property stores a reference to the function currently executing. We may use this reference to execute the current function again or to identify the current function through comparison. Examplefunction someFunction ( ) { trace(arguments.callee == someFunction); // Displays: true } // An unnamed recursive function countToTen = function ( ) { i++; trace(i); if (i < 10) { arguments.callee( ); } };
AvailabilityFlash 5 Synopsisarguments.length AccessRead/write DescriptionThe length property stores an integer representing the number of elements in the arguments array, which equates to the number of parameters passed to the currently executing function. ExampleWe can use the length property of arguments to determine whether a function was invoked with the correct number of parameters. The following example checks whether two arguments have been passed to someFunction( ). Checking whether the passed arguments are of the correct type is left as an exercise to the reader. (Hint: see the typeof operator.) Here's the code: function someFunction (y, z) { if (arguments.length != 2) { trace("Function invoked with wrong number of parameters"); return; } // Proceed with normal function body... }
AvailabilityFlash 5 Constructornew Array() new Array(len) new Array(element0, element1, element2,...elementn) Arguments
Properties
Methods
DescriptionWe use the properties and methods of the Array class to manipulate the data stored in the elements of an array object. See Chapter 11, "Arrays", for exhaustive details on what arrays are and how you can use them, plus detailed definitions of the terminology used in this section. See also the [] and . operators, which are used to access array elements as described in Chapter 5, "Operators". UsageIf the Array constructor is invoked with a single integer argument, that argument is used to set the length of the new array, not the value of the first element. If two or more arguments are supplied to the constructor or if a single non-numeric argument is supplied to the constructor, the arguments are used as the initial values for elements in the array, and the length of the array is determined by the number of arguments specified.
AvailabilityFlash 5 Synopsisarray.concat(value1, value2, value3,...valuen) Arguments
ReturnsA new array containing all the elements of array followed by the elements value1,...valuen. DescriptionThe concat( ) method returns a new array created by appending new elements to the end of an existing array. The original array is left unchanged. Use the push( ), splice( ), or shift( ) method to modify the original array. If an array is used as an argument to concat( ), each element of that array is appended separately. That is, the result of arrayX.concat(arrayY) will be an array formed by appending each element of arrayY to the end of arrayX. The resulting array will have a length equal to arrayY.length + arrayX.length. Nested arrays, however, are not similarly flattened. Example// Create an array myListA = new Array("apples", "oranges"); // Set myListB to ["apples", "oranges", "bananas"] myListB = myListA.concat("bananas"); // Create another new array myListC = new Array("grapes", "plums"); // Set myListD to ["apples", "oranges", "bananas", "grapes", "plums"] myListD = myListB.concat(myListC); // Set myListA to ["apples", "oranges", "bananas"] myListA = myListA.concat("bananas"); // Create an array settings = ["on", "off"]; // Append an array containing a nested array options = settings.concat(["brightness", ["high", "medium", "low"]]); // Sets options to: ["on", "off", "brightness", ["high", "medium", "low"]] // not: ["on", "off", "brightness", "high", "medium", "low"] See AlsoArray.push( ), Array.shift( ), Array.splice( ); Section 11.7.3.4, "The concat( ) method" in Chapter 11, "Arrays"
AvailabilityFlash 5 Synopsisarray.join() array.join(delimiter) Arguments
ReturnsA string composed of all the elements of array converted to strings and separated by delimiter. DescriptionThe join( ) method returns a string created by combining all the elements of an array, as follows:
Note that elements that are themselves arrays are converted to strings via the toString( ) method, so nested array elements are always delimited by commas, not the delimiter used in the join( ) invocation. Examplefruit = new Array("apples","oranges","bananas","grapes","plums"); // Set fruitString to "apples,oranges,bananas,grapes,plums" fruitString = fruit.join( ); // Set fruitString to "apples-oranges-bananas-grapes-plums" fruitString = fruit.join("-"); See AlsoArray.toString( ), String.split( ) ; Section 11.9.4, "The join( ) Method" in Chapter 11, "Arrays"
AvailabilityFlash 5 Synopsisarray.length AccessRead/write DescriptionThe length property is a non-negative integer specifying the number of elements in an array. An array with no elements has a length of 0, an array with 2 elements has a length of 2. Note that the index number of the first element in an array is 0, so length is always one greater than the index of the last element in the array. The length property of an array indicates how many numbered elements the array currently contains, including empty elements (those containing null or undefined). For example, an array may have values for elements 0, 1, 2, and 9, but elements 3 through 8 may be empty. Such an array has a length of 10 because it has 10 element positions (0 through 9) even though only 4 positions are occupied by useful values. Setting the length of an array changes the number of elements in the array. If we increase length, empty elements are added to the end of the array; if we decrease length, existing elements are removed from the end of the array. The length property changes automatically whenever any elements are added or removed via the Array class methods. The length property reflects numbered elements only; it does not include named array elements, which are treated as properties of the array. ExamplemyList = new Array("one", "two", "three"); trace(myList.length); // Displays: 3 // Loop through the array's elements for (var i = 0; i < myList.length; i++) { trace(myList[i]); } See Also"Determining the Size of an Array" in Chapter 11, "Arrays"
AvailabilityFlash 5 Synopsisarray.pop() ReturnsThe value of the last element of array, which is also deleted. DescriptionThe pop( ) method deletes the last element of an array, reduces the array's length by 1, and returns the value of the deleted element. Compare with the shift( ) method, which deletes the first element of an array. ExamplemyList = new Array("one", "two", "three"); trace ("Now deleting " + myList.pop( )); // myList is now: ["one", "two"] See AlsoArray.push( ), Array.shift( ), Array.splice( ); "Removing Elements from an Array" in Chapter 11, "Arrays", "The delete Operator" in Chapter 5, "Operators"
AvailabilityFlash 5 Synopsisarray.push(value1, value2,...valuen) Arguments
ReturnsThe new length of array. DescriptionThe push( ) method appends a list of values to the end of an array as new elements. Elements are added in the order provided. It differs from concat( ) in that push( ) modifies the original array, whereas concat( ) creates a new array. It differs from unshift( ) in that it adds elements at the end of an array, not the beginning. ExamplemyList = new Array (5, 6); myList.push(7); // myList is now [5, 6, 7] myList.push(10, 8, 9); // myList is now [5, 6, 7, 10, 8, 9] See AlsoArray.concat( ), Array.pop( ), Array.unshift( ); "Adding Elements to an Array" in Chapter 11, "Arrays"
AvailabilityFlash 5 Synopsisarray.reverse() DescriptionThe reverse method reverses the order of elements in an array, swapping the last element with the first element, the second-to-last element with the second element, and so on. ExamplemyList = new Array(3, 4, 5, 6, 7); myList.reverse( ); // myList is now [7, 6, 5, 4, 3] See AlsoArray.sort( )
AvailabilityFlash 5 Synopsisarray.shift() ReturnsThe value of the first element of array, which is also deleted. DescriptionThe shift( ) method deletes the first element of an array and then moves all the remaining elements of the array up one position. The affected array's length is reduced by 1. Note that shift( ) differs from the pop( ) method, which deletes the last element of an array. ExamplemyList = new Array ("a", "b", "c"); myList.shift( ); // myList becomes ["b", "c"] See AlsoArray.pop( ), Array.splice( ), Array.unshift( ); "Removing Elements from an Array" in Chapter 11, "Arrays"
AvailabilityFlash 5 Synopsisarray.slice(startIndex, endIndex) Arguments
ReturnsA new array containing the elements of array from startIndex to endIndex-1. DescriptionThe slice( ) method creates a new array by extracting a series of elements from an existing array. The new array is a subset of the elements of the original array, starting with array[startIndex] and ending with array[endIndex-1]. ExamplemyList = new Array("a", "b", "c", "d", "e"); // Set myOtherList to ["b", "c", "d"] myOtherList = myList.slice(1, 4); // Set anotherList to ["d", "e"] anotherList = myList.slice(3); // Set yetAnotherList to ["c", "d"] yetAnotherList = myList.slice(-3, -1); See AlsoArray.splice( ); Section 11.9.3, "The slice( ) Method" in Chapter 11, "Arrays", Section 5.11.4, "The delete Operator" in Chapter 5, "Operators"
AvailabilityFlash 5 Synopsisarray.sort() array.sort(compareFunction) Arguments
DescriptionWhen invoked without any arguments, the sort( ) method temporarily converts the elements of array to strings and orders the elements according to the code points of those strings (approximately alphabetical order). Alphabetic comparisons and code points are described in "Character order and alphabetic comparisons" in Chapter 4, "Primitive Datatypes". When invoked with a compareFunction argument, sort( ) reorders the elements of array according to the return value of compareFunction, which is a user-defined function that dictates how to arrange any two values in the array. Your user-defined compareFunction should be designed to accept two array elements as arguments. It should return a negative number if the first element should come before the second element; it should return a positive number if the first element should come after the second element; and it should return a if the elements should not be reordered. If additional elements are added to the array after it has been sorted, they are not added in sorted order. You must resort the array to reorder any newly added elements. Note that numbers are sorted according to their Latin 1 code points by default. Chapter 11, "Arrays" explains how to sort numbers by their numeric values. ExampleThe following example sorts an array of movie clips according to their horizontal location on screen: var clips = [clip1, clip2, clip3, clip4]; function compareXposition (element1, element2) { if (element1._x < element2._x) { return -1; } else if (element1._x > element2._x) { return 1; } else { return 0; // The clips have the same x position } } clips.sort(compareXposition); See AlsoArray.reverse( ); "The sort( ) method" in Chapter 11, "Arrays"
AvailabilityFlash 5 Synopsisarray.splice(startIndex) array.splice(startIndex, deleteCount) array.splice(startIndex, deleteCount, value1,...valuen) Arguments
ReturnsA new array containing the deleted elements (the original array is modified separately to reflect the requested changes). DescriptionThe splice( ) method removes the elements from array[startIndex] to array[startIndex + deleteCount-1] and then optionally inserts new elements starting at startIndex. The splice( ) method does not leaves gaps in array ; it moves elements up or down to ensure the contiguity of elements in the array. ExamplemyList = new Array (1, 2, 3, 4, 5); // Deletes the second and third elements from the list // and insert the elements "x", "y", and "z" in their place. // This changes myList to [1, "x", "y", "z", 4, 5]. myList.splice(1, 2, "x", "y", "z"); See AlsoArray.slice( ); Section 11.8.3.3, "The splice( ) method" in Chapter 11, "Arrays"
AvailabilityFlash 5 Synopsisarray.toString() ReturnsA comma-separated list of array 's elements converted to strings. DescriptionThe toString( ) method creates a string representation of array. The string returned by toString( ) is a list of array elements converted to strings and separated by commas (the same as is returned by the join( ) method when join( ) is invoked without parameters). An array's toString( ) method is automatically invoked whenever the array is used in a string context. Therefore, it is rarely necessary to manually execute toString( ) on an array. Normally, when we want a precise string representation of an array, we use the join( ) method, which offers us more control over the string we're creating. ExamplemyList = new Array("a", "b", "c"); // Create an array trace(myList.toString( )); // Displays: "a","b","c" myList = new Array([1, 2, 3], "a", "b", "c"); // Create a nested array trace(myList.toString( )); // Displays: "1,2,3,a,b,c" See AlsoArray.join( )
AvailabilityFlash 5 Synopsisarray.unshift(value1, value2,...valuen) Arguments
ReturnsThe new length of array. DescriptionThe unshift( ) method adds a series of elements to the beginning of an array. Elements are added in the order specified. To add elements at the end of an array, use push( ) . ExamplemyList = new Array (5, 6); myList.unshift(4); // myList becomes [4, 5, 6] myList.unshift(7, 1); // myList becomes [7, 1, 4, 5, 6] See AlsoArray.push( ), Array.shift( ); Section 11.7, "Adding Elements to an Array" in Chapter 11, "Arrays"
AvailabilityFlash 5 SynopsisBoolean(value) Arguments
ReturnsThe result of converting value to a primitive Boolean (either true or false). DescriptionThe Boolean( ) global function converts its argument to a primitive Boolean value and returns that converted value. The results of converting various types of data to a primitive Boolean are described in Table 3-3. It's normally not necessary to use the Boolean( ) function; ActionScript automatically converts values to the boolean type when appropriate. UsageBe sure not to confuse the global Boolean( ) function with the Boolean class constructor. The Boolean( ) function converts its argument to the boolean datatype, whereas the Boolean class constructor creates a new Boolean object. Note that in ECMA-262, all nonempty strings convert to true. In Flash 5, only strings that can be converted to a valid nonzero number convert to true. Therefore, even the string "true" converts to the Boolean false. Examplevar x = 1; if (Boolean(x)) { trace("x is true"); } See AlsoThe Boolean class; Section 3.4, "Datatype Conversion" in Chapter 3, "Data and Datatypes"
AvailabilityFlash 5 Constructornew Boolean(value) Arguments
Methods
DescriptionThe Boolean class creates a Boolean object which contains a primitive Boolean value in an inaccessible, internal property. Boolean objects are used purely for the sake of manipulating and examining primitive Boolean values using methods of the Boolean class. A Boolean object is, hence, known as a wrapper object because it simply packages a primitive Boolean value, giving it some object-like methods. Compare the Boolean class with the String and Number classes, which similarly wrap string and number primitive values, but with more useful results. For the most part, Boolean objects are used internally. They are created automatically by the interpreter whenever a method is invoked on a primitive Boolean value and are deleted automatically after each use. We can create Boolean objects ourselves using the Boolean constructor, but there is seldom reason to do so. UsageNote that in practice it is much more common to use the Boolean( ) global function as a datatype-conversion tool than it is to use the Boolean class. See AlsoBoolean( ) global function; "The Boolean Type" in Chapter 4, "Primitive Datatypes"
AvailabilityFlash 5 SynopsisbooleanObject.toString() ReturnsThe string "true" if the primitive value of booleanObject is true; "false" if the primitive value of booleanObject is false. The value of the Boolean object is specified when the object is constructed and stored internally thereafter. Although the internal value of a Boolean object is inaccessible, we can use toString( ) to convert it to its string equivalent. DescriptionThe toString( ) method retrieves the primitive value of a Boolean object, converts that value to a string, and returns the resulting string. Examplex = new Boolean(true); trace(x.toString( )); // Displays: "true" See AlsoObject.toString( )
AvailabilityFlash 5 SynopsisbooleanObject.valueOf() ReturnsThe Boolean value true if the primitive value of booleanObject is true; false if the primitive value of booleanObject is false. The value of the Boolean object is specified when the object is constructed and stored internally thereafter. DescriptionThe valueOf( ) method returns the primitive Boolean datum associated with a Boolean object. Although the internal value of a Boolean object is inaccessible, we can use valueOf( ) to convert it to its primitive equivalent. Examplex = new Boolean(0); trace(x.valueOf( )); // Displays: false See AlsoObject.valueOf( )
AvailabilityFlash 4; deprecated in Flash 5 Synopsiscall(frameLabel) call(frameNumber) Arguments
DescriptionThe call( ) function executes the script attached to the frame at frameLabel or frameNumber. For example, the following code runs the script on frame 20 of the current timeline: call(20); In Flash 4, call( ) was used to create a crude kind of reusable subroutine (one that could not accept parameters or return any value). In Flash 5, the function statement is preferred. Note that in Flash 5, when a script is executed remotely via call( ), any variables declared with the var keyword are considered local to that execution and expire after the script completes. To create nonlocal variables in a remotely-executed script, omit the var keyword: var x = 10; // Local variable; dies after script completes x = 10; // Timeline variable; persists after script completes To invoke call( ) on frames outside the current timeline, use the tellTarget( ) function. The following example executes the script on frame 10 of the box clip: tellTarget ("box") { call(10); } See AlsoChapter 9, "Functions"; Appendix C, "Backward Compatibility"
AvailabilityConstructornew Color(target) Arguments
Methods
DescriptionWe use objects of the Color class to programmatically dictate the color and transparency of a movie clip or main movie. Once we've created an object of the Color class for a specific target, we can then invoke the methods of that object to affect its target's color and transparency. For example, suppose we have a clip instance named ball that we want to make red. We first make a Color object with a target of ball and store it in the variable ballColor. Then we use ballColor.setRGB( ) to assign ball the color red, as follows: var ballColor = new Color("ball"); ballColor.setRGB(0xFF0000); // Pass setRGB( ) the hex value for red The preceding example provides color control for simple applications. But to handle more complex scenarios, we need to know more about how color is represented in Flash. Every individual color displayed in a movie clip is defined by four separate components: Red, Green, Blue, and Alpha (or transparency). Those four components are combined in different amounts to generate each color we see on screen. The amount of Red, Green, Blue, and Alpha in a given color is described as a number between 0 and 255. The higher the value of Red, Green, or Blue, the more each of those colors contributes to the final color. However, remember that computer color is additive, not subtractive like paint, so higher values tend to be brighter, not darker. If all three RGB components are equal, the result is a shade of gray; if they are all 0, the result is black; if they are all 255, the result is white. The higher the value of Alpha, the more opaque the final color will be. (A color with an Alpha of is completely transparent, and a color with an Alpha of 255 is completely opaque.) For example, pure red would be described by the following values: Red: 255, Green: 0, Blue: 0, Alpha: 255 whereas a partially transparent red might have the values: Red: 255, Green: 0, Blue: 0, Alpha: 130 For the purposes of this discussion, we adopt the so-called RGB triplet notation (Red, Green, Blue) when talking about color values. Although ActionScript doesn't support decimal RGB triplets such as (255, 0, 255), it does support the hexadecimal equivalent form 0xRRGGBB, where RR, GG, and BB are two-digit hex numbers representing Red, Green and Blue. We'll also adopt the RGBA quadlet notation (Red, Green, Blue, Alpha) for convenience only in the following discussion. The initial Red, Green, Blue, and Alpha values for each color in a movie clip are set in the Flash authoring tool using the Mixer panel. (In the Mixer panel, Alpha is shown as a percentage, not a number from to 255.) To alter all the colors in a movie clip via ActionScript, we make universal adjustments (known as transformations ) to the Red, Green, Blue, and Alpha components of the clip's color. We have two means of setting transformations for each color component:
The final value of a color in a transformed clip is determined by combining its original (author-time) color component values with the transformation percentages and offsets set through the Color object, as follows: R = originalRedValue * (redTransformPercentage/100) + redTransformOffset G = originalGreenValue * (greenTransformPercentage/100) + greenTransformOffset B = originalBlueValue * (blueTransformPercentage/100) + blueTransformOffset A = originalAlphaValue * (alphaTransformPercentage/100) + alphaTransformOffset If no transformations have been performed through ActionScript, the initial transformation percentage for each component defaults to 100, while the initial offset defaults to 0. Let's look at how color transformations work with a practical example. Suppose that a clip contains an opaque red triangle (R:255, G:0, B:0, A:255) and an opaque green circle (R:0, G:255, B:0, A:255). Now further suppose that we apply a universal transformation to the clip, setting the percentage of Green to 50, the percentage of Alpha to 80, and the offset of Blue to 100 but leaving the other offsets and percentages at their defaults (0 or 100). Here's how the universal transformation affects our red triangle: R == 255 * (100/100) + 0 == 255 // No change to Red G == 0 * (50/100) + 0 == 0 // Green reduced to 50% B == 0 * (100/100) + 100 == 100 // Blue offset by 100 A == 255 * (80/100) + 0 == 204 // Alpha reduced to 80% The final transformed red triangle has the color value (R:255, G:0, B:100, A:204). Now here's how the transformation affects our green circle: R == 0 * (100/100) + 0 == 0 // No change to Red G == 255 * (50/100) + 0 == 127.5 // Green reduced to 50% B == 0 * (100/100) + 100 == 100 // Blue offset by 100 A == 255 * (80/100) + 0 == 204 // Alpha reduced to 80% The final transformed green circle has the color value (R:0, G:127.5, B:100, A:204). To actually apply our hypothetical color transformations to a real clip, we use a Color object as we saw earlier. To set a clip's universal color offset and percentage values we use the setRGB( ) or the setTransform( ) methods (see the entries for those methods for example code). Conversely, to examine the current color transformations of a clip, we use the getRGB( ) and getTransform( ) methods. The Color class methods can produce animated color effects such as fade-ins, fade-outs, and tinting. Furthermore, because we can apply tints to each clip instance individually, the Color class provides a very efficient way to create diverse graphics with minimal assets. For example, we could create a scene full of balloons from a single movie clip that was colorized and tinted in myriad ways, as shown under the Example heading that follows. UsageSome points of interest for Color objects:
ExampleThe first example shows how to generate a series of randomly colored balloon movie clips based on an existing clip called balloon: // Loop to make 20 duplicates of the clip balloon for (var i = 0; i < 20; i++) { // Duplicate this balloon balloon.duplicateMovieClip("balloon" + i, i); // Position this balloon on stage this["balloon" + i]._x = Math.floor(Math.random( ) * 550); this["balloon" + i]._y = Math.floor(Math.random( ) * 400); // Create a Color object for this balloon balloonColor = new Color(this["balloon" + i]); // Randomly assign this balloon's color using the setRGB( ) method balloonColor.setRGB(Math.floor(Math.random( ) * 0xFFFFFF)); } By setting the Red, Green, and Blue offsets to the same value, we can effectively brighten or darken a movie clip. For example, the following code darkens myClip: brightness = new Color("myClip"); brightnessTransform = new Object( ); brightnessTransform.rb = -30; brightnessTransform.bb = -30; brightnessTransform.gb = -30; brightness.setTransform(brightnessTransform); This last example contains code that brightens and darkens a clip according to the mouse position: onClipEvent (load) { var brightness = new Color(this); var brightnessTransform = new Object( ); var stageWidth = 550; } onClipEvent (mouseMove) { brightnessAmount = -255 + (_root._xmouse / stageWidth) * 510; brightnessTransform.rb = brightnessAmount; brightnessTransform.bb = brightnessAmount; brightnessTransform.gb = brightnessAmount; brightness.setTransform(brightnessTransform); updateAfterEvent( ); }
AvailabilityFlash 5 SynopsiscolorObj.getRGB() ReturnsA number representing the current RGB offsets of colorObj 's target. DescriptionThe getRGB( ) method returns a number ranging from -16777215 to 16777215 that represents the current color offsets for the Red, Green, and Blue components in a clip; to retrieve the color percentages, you must use getTransform( ). Because color offset values normally range from 0 to 255, it's convenient to work with the return value of getRGB( ) in hexadecimal, where each color offset can be represented by a two-digit hex number. To decipher the number returned by getRGB( ), we treat it as a six-digit hex number of the form 0xRRGGBB, where RR is the Red offset, GG is the Green offset, and BB is the Blue offset. For example, if getRGB( ) returns the number 10092339, we convert it to the hex number 0x99FF33 from which we derive the color offsets R:153, G:255, B:51. Or if getRGB( ) returns the number 255, we convert it to the hex number 0x0000FF from which we derive the color offsets R:0, G:0, B:255. The return value of getRGB( ) can be converted to hexadecimal with toString( ), as follows: // Create a Color object myColor = new Color("myClip"); // Set the Red offset to 255 (FF in hex) myColor.setRGB(0xFF0000); // Retrieve the RGB offset and convert it to hexadecimal hexColor = myColor.getRGB( ).toString(16); trace(hexColor); // Displays: ff0000 Hexadecimal color values are familiar to most web developers, as they are often used in HTML tags. For example, here we use a hexadecimal number to specify the background color of a page (full values for red and blue combine to form pink): <BODY BGCOLOR="#FF00FF"> The hex color format used in HTML tags is, in fact, the same as the format used by getRGB( ) and setRGB( ). However, it's not mandatory to use hexadecimal to interpret the return value of getRGB( ); we may also extract the individual Red, Green and Blue color offsets from the return value of getRGB( ) using the bitwise operators: var rgb = myColorObject.getRGB( ); var red = (rgb >> 16) & 0xFF; // Isolate the Red offset and assign it to red var green = (rgb >> 8) & 0xFF; // Isolate the Green offset and assign it to green var blue = rgb & 0xFF; // Isolate the Blue offset and assign it to blue With the offset values separated into individual variables, we may examine and manipulate them individually as decimal numbers. However, when we want to apply any offset value changes to a Color object, we must reassemble the offsets into a single number, as shown under the entry for the setRGB( ) method. UsageThe getRGB( ) and setRGB( ) methods are convenient when we're directly assigning new colors to a clip without reference to the clip's original color values. However, the getTransform( ) and setTransform( ) methods are better suited to modifying the RGB components of a clip's color transformation in relation to the clip's original colors. Color offsets are most easily read using getTransform( ), which returns each component separately rather than as a lump sum as getRGB( ) does. This is especially true when setting negative offsets with setTransform( ) due to the way that negative numbers are represented in binary. Example// Create a new Color object for a clip named box boxColor = new Color("box"); // Set a new RGB offset for "box" boxColor.setRGB(0x333366); // Check the RGB offset for "box" trace(boxColor.getRGB( )); // Displays: 3355494 See AlsoColor.getTransform( ), Color.setRGB( )
AvailabilityFlash 5 SynopsiscolorObj.getTransform() ReturnsAn object whose properties contain the color transformation values for the target clip of colorObj. DescriptionThe getTransform( ) method returns an object with properties that tell us which transformations are currently applied to the target of a Color object. The property names and values of the returned object are described in Table 20-4. Table 20-4. Properties of Object Returned by getTransform( )
UsageNote in Table 20-4 that both the percentage and the offset can have negative values; however, these are only one factor in calculating the RGB color components, which always range from 0 to 255. Values outside that range are clipped to the allowable range. See the Color class description for an explanation of the calculation used to determine final RGB and Alpha color components. ExampleWe can use getTransform( ) in combination with setTransform( ) to modify the Red, Green, Blue, or Alpha components of a color transformation individually. For example, in the following code, we adjust the Red and Alpha components of a clip named box: // Create a new Color object for a clip named box boxColor = new Color("box"); // Assign the return object of getTransform() to boxTransform boxTransform = boxColor.getTransform( ); // Now, make some modifications to the transform object's properties boxTransform.rb = 200; // Set Red offset to 200 boxTransform.aa = 60; // Set Alpha percentage to 60 // Apply the new transformations to box via boxColor boxColor.setTransform(boxTransform); See AlsoColor.setTransform( )
AvailabilityFlash 5 SynopsiscolorObj.setRGB(offset); Arguments
DescriptionThe setRGB( ) method assigns new transformation offsets for a movie clip's RGB components. The new offset is most easily specified as a six-digit hexadecimal number of the form 0xRRGGBB, where RR, GG, and BB are two-digit numbers between 00 and FF representing the Red, Green, and Blue components. For example, the RGB triplet (51, 51, 102) is equivalent to the hexadecimal value: 0x333366 Hence, to assign a gray RGB offset to a clip named menu, we could use: var menuColor = new Color("menu"); menuColor.setRGB(0x999999); Web developers comfortable with six-digit hexadecimal color values in HTML will have an easy time using setRGB( ) using the preceding hexadecimal format. For a primer on decimal, octal, and hexadecimal numbers see http://www.moock.org/asdg/technotes. Note that in addition to setting offsets, setRGB( ) also automatically sets the Red, Green, and Blue percentages of a clip's color transformation to 0, meaning that color changes performed via setRGB( ) behave as direct color assignments (not adjustments of the original colors in the clip). To adjust the color of a movie clip in relation to the clip's original colors, we must use the setTransform( ) method. ExampleHere's a handy technique for generating a number to use with the setRGB( ) method. Our custom combineRGB( ) function shifts the red and green numbers into the proper position in a 24-bit number and then combines the red, green, and blue values using the bitwise OR operator (|). We use the result to assign a color value to the movie clip box: function combineRGB (red, green, blue) { // Combine the color values into a single number var RGB = (red<<16) | (green<<8) | blue; return RGB; } // Create the Color object var boxColor = new Color("box"); // Set the color of box to the RGB triplet (201, 160, 21) boxColor.setRGB(combineRGB(201, 160, 21)); For more information on bitwise operations, see Chapter 15, "Advanced Topics". See AlsoColor.getRGB( ), Color.setTransform( )
AvailabilityFlash 5 SynopsiscolorObj.setTransform(transformObject) Arguments
DescriptionThe setTransform( ) method gives us precise control over the percentage and offset of the Red, Green, Blue, and Alpha components of a movie clip's color. To use setTransform( ), we must first create an object with a series of predefined properties. The transformation we wish to apply to our Color object is expressed using those properties, which are listed in Table 20-4 for the getTransform( ) method (except that setTransform( ) specifies their values rather than reading their values). Once we have created an object with the properties described in Table 20-4, we pass that object to the setTransform( ) method. The values of the properties on our transformObject become the new offset and percentage transform values of colorObj and, hence, colorObj's target movie clip. The final color values in the clip are then determined according to the calculation discussed under the Color class. To examine the current offsets and percentages of a particular Color object, we use the getTransform( ) method. Example// Create a new Color object for the box clip boxColor = new Color("box"); // Create a new anonymous object and store it in boxTransform boxTransform = new Object( ); // Assign the required properties of boxTransform, setting our // transformation values as desired boxTransform.ra = 50; // Red percentage boxTransform.rb = 0; // Red offset boxTransform.ga = 100; // Green percentage boxTransform.gb = 25; // Green offset boxTransform.ba = 100; // Blue percentage boxTransform.bb = 0; // Blue offset boxTransform.aa = 40; // Alpha percentage boxTransform.ab = 0; // Alpha offset // Now that our transform object has been // prepared, pass it to setTransform( ) boxColor.setTransform(boxTransform); The preceding approach to creating a transform object is fairly labor-intensive. We may generate a new transform object more easily using the getTransform( ) method, as follows: // Create a new Color object for the box clip boxColor = new Color("box"); // Invoke getTransform( ) on boxColor, retrieving an appropriately // constructed transform object boxTransform = boxColor.getTransform( ); // Now alter only the desired properties of boxTransform, // leaving the others unchanged boxTransform.rb = 51; // Red offset boxTransform.aa = 40; // Alpha percentage // Use our transform object with setTransform( ) boxColor.setTransform(boxTransform); See Also
AvailabilityFlash 5 SynopsisDate() ReturnsA string containing the current date and time. DescriptionThe Date( ) function returns a human-readable string that expresses the current date and time relative to the local time zone. The string also includes the GMT offset (the number of hours difference between local time and Greenwich Mean Time). Be sure not to confuse the global Date( ) function with the Date( ) class constructor. The Date( ) function returns the date formatted as a standard, if terse, string. It is convenient for humans but not very useful inside a program where you need to manipulate dates and times. For that purpose, you are better off using objects of the Date class, which allow convenient independent access to the year, month, day, and time. ExampleTo place the current time and date in a text field with minimal fuss, we can use the Date( ) function as follows: myTextField = Date( ); // Sets myTextField to a string formatted as follows: // "Mon Aug 28 16:23:09 GMT-0400 2000" See AlsoThe Date class, Date.UTC( )
AvailabilityFlash 5 Constructornew Date() new Date(milliseconds) new Date(year, month, day, hours, minutes, seconds, ms) Arguments
Class Methods
Methods
DescriptionWe use objects of the Date class as a mechanism by which to determine the current time and date and as a means of storing arbitrary dates and times in a structured format. In ActionScript, a specific date is represented by the number of milliseconds before or after midnight of January 1, 1970. If the number of milliseconds is positive, the date comes after midnight, January 1, 1970; if the number of milliseconds is negative, the date comes before midnight, January 1, 1970. For example, if a date value is 10000, the date being described is 12:00:10, January 1, 1970. If a date value is -10000, the date being described is 11:59:50, December 31, 1969. Normally, however, we needn't worry about calculating the number of milliseconds to a particular date; the ActionScript interpreter takes care of that for us. When we construct a Date object, we simply describe our date as a year, month, day, hour, minute, second, and millisecond. The interpreter then converts that point in time to the internal milliseconds-from-1970 format. We may also ask the interpreter to create a new Date object using the current time. Once a Date object is created, we can use the Date class's methods to retrieve and set the date's year, month, day, hour, minute, second, and millisecond. There are three ways to make a new Date object:
Because dates are stored internally as a single number, objects of the Date class do not have properties to retrieve and set. Rather, they have methods that we use to access the various components of a date in human-readable terms (i.e., in more convenient units). For example, to determine the month of a particular Date object, we use: myMonth = myDate.getMonth( ); We cannot use: myMonth = myDate.month; // There's no such property! We have to use methods. Many Date methods contain the letters "UTC," which is an abbreviation for Coordinated Universal Time. For most purposes, UTC time is directly synonymous with the more colloquial Greenwich Mean Time, or GMT -- the time as measured on the Greenwich meridian. UTC is simply a newer standard that is less ambiguous than GMT, which has had several meanings over history. The UTC methods allow us to work with times directly in Coordinated Universal Time without converting between time zones. The equivalent non-UTC methods all generate values based on local, adjusted time zones. UsageAll dates and times are determined according to the settings on the operating system on which the Flash movie is running (not the web server) and include regional offsets. Times and dates, therefore, are only as accurate as the user's system. Note that the Date( ) constructor may also be used as a global function to generate a string expressing the current time in the same format as would be returned by myDate.toString( ). In Flash 5 ActionScript, it is not possible to convert a string into a Date object, as is possible in JavaScript. ExampleDates can be added and subtracted to come up with cumulative times or elapsed times. Suppose our friend Graham decides to go traveling for a little less than a year. While he's gone, we want to keep track of how many days he's been away and how many days we have to wait for him to return. The following code takes care of our countdown: // Assign the current time to now var now = new Date( ); // Graham leaves September 7, 2000 (remember, months start at 0 // so September is 8, not 9) var departs = new Date(2000,8,7); // Graham comes back August 15, 2001 var returns = new Date(2001,7,15); // Convert the times to milliseconds for easy comparison. // Then check how many milliseconds have elapsed between the two times. var gone = now.getTime() - departs.getTime( ); // Divide the difference between departure date and now by the number // of milliseconds in a day. This tells us how many days we've been waiting. var numDaysGone = Math.floor(gone/86400000); // Use the same technique to determine how many days we have left to wait var left = returns.getTime() - now.getTime( ); var numDaysLeft = Math.floor(left/86400000); // Display our days in text fields goneOutput = numDaysGone; leftOutput = numDaysLeft; When adding a day to, or subtracting a day from, an existing date, we normally assign the number of milliseconds in a day (86400000) to a variable for convenient use. The following code adds one day to the current date: oneDay = 86400000; now = new Date( ); tomorrow = new Date(now.getTime( ) + oneDay); // We could also add one day to the date in now like this now.setTime(now.getTime( ) + oneDay); To apply custom formatting to a date, we must manually map the return values of getDate( ), getDay( ), getHours( ), and so on to custom strings as shown in the following example: // Takes any Date object and returns a string of the format: // Saturday December 16 function formatDate(theDate) { var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; var dateString = days[theDate.getDay( )] + " " + months[theDate.getMonth( )] + " " + theDate.getDate( ); return dateString; } now = new Date( ); trace("Today is " + formatDate(now)); The next example shows how to convert the 24-hour clock return value of getHours( ) to a 12-hour clock with AM and PM: // Takes any Date object and returns a string of the format: // "2:04PM" function formatTime(theDate) { var hour = theDate.getHours( ); var minute = theDate.getMinutes( ) > 9 ? theDate.getMinutes() : "0" + theDate.getMinutes( ); if (hour > 12) { var timeString = (hour - 12) + ":" + minute + "PM"; } else { var timeString = hour + ":" + minute + "AM"; } return timeString; } now = new Date( ); trace("The time is " + formatTime(now)); For an example using the Date class to create an analog-style clock, see Section 13.9.1, "Building a Clock with Clips" in Chapter 13, "Movie Clips". Note that programming time-based behavior such as a 10-second pause in a movie is often accomplished more easily with the global getTimer( ) function. See Also
AvailabilityFlash 5 Synopsisdate.getDate() ReturnsAn integer from 1 to 31, representing the day of the month for date.
AvailabilityFlash 5 Synopsisdate.getDay() ReturnsAn integer from 0 0 (Sunday) to 6 (Saturday), representing the day of the week for date. ExampleThe following code loads a .swf file specific to the current day of the week into the movie clip welcomeHeader (the seven .swf files are named in the series sun.swf, mon.swf, and so on): now = new Date( ); today = now.getDay( ); days = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"]; welcomeHeader.loadMovie(days[today] + ".swf");
AvailabilityFlash 5 Synopsisdate.getFullYear() ReturnsA four-digit integer representing the year for date, for example 1999 or 2000.
AvailabilityFlash 5 Synopsisdate.getHours() ReturnsAn integer from 0 (midnight) to 23 (11 p.m.) representing the hour of the day for date. A.M. and P.M. notation are not supported but can be constructed manually as shown in the Date class examples.
AvailabilityFlash 5 Synopsisdate.getMilliseconds() ReturnsAn integer from 0 to 999 representing the milliseconds of date. Note that it does not represent the milliseconds from 1970 (see getTime( )), but rather the fractional remainder of the seconds indicated by the specified Date object. See AlsoDate.getTime( )
AvailabilityFlash 5 Synopsisdate.getMinutes() ReturnsAn integer from 0 to 59 representing the minutes of the hour of date.
AvailabilityFlash 5 Synopsisdate.getMonth() ReturnsAn integer from 0 (January) to 11 (December), not 1 to 12, representing the month of the year of date. UsageBe careful not to assume that 1 is January! The return value of getMonth( ) starts at 0, not 1. ExampleHere we convert the number returned by getMonth( ) to a human-readable abbreviation: var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec"]; myDateObj = new Date( ); trace ("The month is " + months[myDateObj.getMonth( )]);
AvailabilityFlash 5 Synopsisdate.getSeconds() ReturnsAn integer from 0 to 59 representing the seconds of the minute of date.
AvailabilityFlash 5 Synopsisdate.getTime() ReturnsAn integer expressing the number of milliseconds between the time of date and midnight, January 1, 1970. Positive if after January 1, 1970; negative if before. DescriptionInternally, all dates are represented as a single number -- the number of milliseconds between the time of the date and midnight, January 1, 1970. The getTime( ) method gives us access to that number of milliseconds so that we may use it to construct other dates or to compare the elapsed time between two dates. ExampleSuppose we place the following code on the 10th frame of a movie: time1 = new Date( ); Then we place the following code on the 20th frame of a movie: time2 = new Date( ); With the following code, we can determine the amount of time that elapsed, in milliseconds, between the 10th and 20th frames of our movie: elapsedTime = time2.getTime() - time1.getTime( ); Note that Flash's global getTimer( ) function also gives us access to elapsed time in a movie. See AlsoDate.setTime( ), getTimer( )
AvailabilityFlash 5 Synopsisdate.getTimezoneOffset() ReturnsAn integer representing the current number of minutes between the local time zone and the actual UTC (Greenwich meridian) time. Positive if local time is behind UTC; negative if local time is ahead of UTC. Includes adjustments for local daylight saving time depending on the day of the year. ExampleWhen invoked in Eastern Daylight Time (EDT) during daylight savings, the following code returns the value 240 (240 minutes is 4 hours): myDate = new Date( ); trace(myDate.getTimezoneOffset( )); // Displays: 240 However, when invoked in EDT, during non-daylight savings times of year, the same code returns 300 (300 minutes is 5 hours), which is the real offset between Eastern Standard Time (EST) and UTC.
AvailabilityFlash 5 Synopsisdate.getUTCDate() ReturnsAn integer from 1 to 31, representing the day of the month for date, where date is treated as a UTC time.
AvailabilityFlash 5 Synopsisdate.getUTCDay() ReturnsAn integer from 0 (Sunday) to 6 (Saturday), representing the day of the week for date, where date is treated as a UTC time.
AvailabilityFlash 5 Synopsisdate.getUTCFullYear() ReturnsA four-digit integer representing the year for date, where date is treated as a UTC time, for example 1999 or 2000.
AvailabilityFlash 5 Synopsisdate.getUTCHours() ReturnsAn integer from 0 (midnight) to 23 (11 p.m.) representing the hour of the day for date, where date is treated as a UTC time.
AvailabilityFlash 5 Synopsisdate.getUTCMilliseconds() ReturnsAn integer from 0 to 999 representing the milliseconds of date, where date is treated as a UTC time.
AvailabilityFlash 5 Synopsisdate.getUTCMinutes() ReturnsAn integer from 0 to 59 representing the minutes of the hour of date, where date is treated as a UTC time.
AvailabilityFlash 5 Synopsisdate.getUTCMonth() ReturnsAn integer from 0 (January) to 11 (December), not 1 to 12, representing the month of the year of date, where date is treated as a UTC time. UsageBe careful not to assume that 1 is January! The return value of getUTCMonth( ) starts at 0, not 1.
AvailabilityFlash 5 Synopsisdate.getUTCSeconds() ReturnsAn integer from 0 to 59 representing the seconds of the minute of date, where date is treated as a UTC time.
AvailabilityFlash 5 Synopsisdate.getYear() ReturnsThe value of date.getFullYear( ) -1900. For example, getYear( ) of 1999 is 99, getYear( ) of 2001 is 101, and getYear( ) of 1800 is -100. This function is most useful for dates in the 20th century.
AvailabilityFlash 5 Synopsisdate.setDate(day) Arguments
ReturnsAn integer representing the number of milliseconds between the new date and midnight, January 1, 1970. See AlsoDate.getDate( )
AvailabilityFlash 5 Synopsisdate.setFullYear(year, month, day) Arguments
ReturnsAn integer representing the number of milliseconds between the new date and midnight, January 1, 1970. See AlsoDate.setYear( ), Date.getFullYear( )
AvailabilityFlash 5 Synopsisdate.setHours(hour) Arguments
ReturnsAn integer representing the number of milliseconds between the new date and midnight, January 1, 1970. See AlsoDate.getHours( )
AvailabilityFlash 5 Synopsisdate.setMilliseconds(ms) Arguments
ReturnsAn integer representing the number of milliseconds between the new date and midnight, January 1, 1970. See AlsoDate.getMilliseconds( ), Date.setTime( )
AvailabilityFlash 5 Synopsisdate.setMinutes(minute) Arguments
ReturnsAn integer representing the number of milliseconds between the new date and midnight, January 1, 1970. See AlsoDate.getMinutes( )
AvailabilityFlash 5 Synopsisdate.setMonth(month) Arguments
ReturnsAn integer representing the number of milliseconds between the new date and midnight, January 1, 1970. UsageBe careful not to assume that 1 is January! Months start at 0, not 1. See AlsoDate.getMonth( )
AvailabilityFlash 5 Synopsisdate.setSeconds(second) Arguments
ReturnsAn integer representing the number of milliseconds between the new date and midnight, January 1, 1970. See AlsoDate.getSeconds( )
AvailabilityFlash 5 SynopsisDate.setTime(milliseconds) Arguments
ReturnsThe value of milliseconds. DescriptionInternally, all dates are represented as the number of milliseconds between the time of the date and midnight, January 1, 1970. The setTime( ) method specifies a new date using the internal millisecond representation. Setting a date using milliseconds from 1970 is often handy when we're determining differences between multiple dates and times using getTime( ). ExampleUsing setTime( ) in concert with getTime( ) we can adjust the time of an existing date by adding or subtracting milliseconds. For example, here we add one hour to a date: now = new Date( ); now.setTime(now.getTime( ) + 3600000); And here we add one day: now = new Date( ); now.setTime(now.getTime( ) + 86400000); To improve the readability of our code, we create variables representing the number of milliseconds in an hour and milliseconds in a day: oneDay = 86400000; oneHour = 3600000; now = new Date( ); // Subtract one day and three hours. now.setTime(now.getTime( ) - oneDay - (3 * oneHour)); See AlsoDate.getTime( ), Date.setMilliseconds( ), Date.UTC( ), getTimer( )
AvailabilityFlash 5 Synopsisdate.setUTCDate(day) Arguments
ReturnsAn integer representing the number of milliseconds between the new date and midnight, January 1, 1970 in UTC time.
AvailabilityFlash 5 Synopsisdate.setUTCFullYear(year) Arguments
ReturnsAn integer representing the number of milliseconds between the new date and midnight, January 1, 1970 in UTC time.
AvailabilityFlash 5 Synopsisdate.setUTCHours(hour) Arguments
ReturnsAn integer representing the number of milliseconds between the new date and midnight, January 1, 1970 in UTC time.
AvailabilityFlash 5 Synopsisdate.setUTCMilliseconds(ms) Arguments
ReturnsAn integer representing the number of milliseconds between the new date and midnight, January 1, 1970 in UTC time.
AvailabilityFlash 5 Synopsisdate.setUTCMinutes(minute) Arguments
ReturnsAn integer representing the number of milliseconds between the new date and midnight, January 1, 1970 in UTC time.
AvailabilityFlash 5 Synopsisdate.setUTCMonth(month) Arguments
ReturnsAn integer representing the number of milliseconds between the new date and midnight, January 1, 1970 in UTC time. UsageBe careful not to assume that 1 is January! Months start at 0, not 1.
AvailabilityFlash 5 Synopsisdate.setUTCSeconds(second) Arguments
ReturnsAn integer representing the number of milliseconds between the new date and midnight, January 1, 1970 in UTC time.
AvailabilityFlash 5 Synopsisdate.setYear(year, month, day) Arguments
ReturnsAn integer representing the number of milliseconds between the new date and midnight, January 1, 1970. DescriptionsetYear( ) is identical to setFullYear( ) except that it interprets one- and two-digit years as being relative to 1900 whereas setFullYear( ) interprets them as being relative to 0 A.D. See AlsoDate.getYear( ), Date.setFullYear( )
AvailabilityFlash 5 Synopsisdate.toString() ReturnsA string giving the current time and date of date in human-readable format, including the UTC (GMT) offset. To compose customized representations of the date, use the methods for retrieving the day, hours, minutes, and so on, and map those values onto your own strings, as shown earlier in the example under Date class. Exampletrace (myDate.toString( )); // Displays a date in the format: // Wed Sep 15 12:11:33 GMT-0400 1999
AvailabilityFlash 5 SynopsisDate.UTC(year, month, day, hours, minutes, seconds, ms) Arguments
ReturnsThe number of milliseconds between the specified date and midnight, January 1, 1970. DescriptionThe Date.UTC( ) method takes the same arguments as the Date( ) constructor, but instead of returning an object for the specified date, Date.UTC( ) returns a number indicating the date in the internal milliseconds-from-1970 format. The returned number is typically used to construct a new Date object in UTC or to assign a UTC time to an existing Date object via the setTime( ) method. ExampleThe following code shows how to measure the milliseconds elapsed between midnight 1970 and midnight 2000 in UTC time: trace(Date.UTC(2000, 0) + " milliseconds passed between 1970 and 2000."); // Displays: "946684800000 milliseconds passed between 1970 and 2000." Here we use those elapsed milliseconds to construct a UTC-time-based Date object: nowUTC = new Date(Date.UTC(2000, 0)); If that code were invoked in EST (Eastern Standard Time), which is 5 hours behind UTC, nowUTC would represent the local time 7p.m. on December 31, 1999. When we check the hour using the non-UTC method getHours( ), we get the local hour, 19 (7p.m. in a 24-hour clock): trace(nowUTC.getHours( )); // Displays: 19 But when we check the hour using the UTC method getUTCHours( ), we get the correct UTC hour, (midnight in a 24-hour clock): trace(nowUTC.getUTCHours( )); // Displays: 0 See AlsoDate( ), Date.setTime( ), the Date class
AvailabilityFlash 5 Synopsisdate.valueOf() ReturnsAn integer expressing the number of milliseconds between the time of the Date object and midnight, January 1, 1970. Positive if after January 1, 1970; negative if before. DescriptionIn practice, Date.valueOf( ) is equivalent to Date.getTime( ). See AlsoDate.toString( )
AvailabilitySynopsisduplicateMovieClip(target, newName, depth) Arguments
DescriptionThe duplicateMovieClip( ) function is one way to create a new movie clip during movie playback (the other is attachMovie( )). duplicateMovieClip( ) creates an identical copy of target and places the copy in target's clip stack on layer depth. The duplicated clip begins playing at frame 1 no matter what the frame of target is when duplication occurs. A duplicated clip inherits any transformations (rotation, scale, etc.) that had been applied to target but does not inherit the timeline variables of target. The global function duplicateMovieClip( ) is also available as a movie clip method, though when used in that form, the target argument is not used. Example// Copies the ball clip and names the copy ball2 duplicateMovieClip(ball, "ball2", 0); // Moves the new ball2 clip over so we can see it ball2._x += 100; See AlsoMovieClip.duplicateMovieClip( ), removeMovieClip( ); Section 13.3.2.2, "Creating instances with duplicateMovieClip( )", Section 13.4.2.2, "How clips generated via duplicateMovieClip( ) are added to the stack", and Section 13.8.3.1, "Method versus global function overlap issues" in Chapter 13, "Movie Clips"
AvailabilityFlash 5 Synopsisescape(string) Arguments
ReturnsAn (almost) URL-encoded version of string. DescriptionThe escape( ) function creates a new encoded string based on a supplied string. The new string contains a hexadecimal escape sequence in place of any character in the supplied string that is not a digit or a basic, unaccented Latin letter between A and Z or a and z. The replacement hexadecimal escape sequences take the format %xx, where xx is the hexadecimal value of the character's code point in the Latin 1 character set. Shift-JIS double-byte characters are converted to two hexadecimal escape sequences of the form %xx%xx. The escape( ) function effectively URL-encodes a string, except that space characters are converted to %20, not +. escape( ) is sometimes used when a Flash movie sends information to server applications or writes cookies in a browser. To decode an encoded string, we use the global unescape( ) function. Examplevar phoneNumber = "(222) 515-1212" escape(phoneNumber); // yields %28222%29%20515%2D1212 See Alsounescape( ); Appendix B, "Latin 1 Character Repertoire and Keycodes"
AvailabilityFlash 4 and later Synopsiseval(stringExpression) Arguments
ReturnsThe value of the variable represented by stringExpression or a reference to the object, movie clip, or function represented by stringExpression. If stringExpression does not represent a variable or a movie clip, undefined is returned. DescriptionThe eval( ) function provides a means of constructing a dynamic reference to an identifier based on a string of text. eval( ) converts a string to a variable, movie clip, object property, or other identifier and then evaluates that identifier. For example, here we use the return value of eval( ) to set the value of a variable: name1 = "Kathy"; count = 1; currentName = eval("name" + count); // Sets currentName to "Kathy" And here we control a dynamically-named movie clip, star1: eval("star" + count)._x += 100; // Move star1 right 100 pixels But we may also use an eval( ) invocation in place of an identifier that is the lefthand operand of an assignment expression, as in: eval("name" + count) = "Simone"; // Sets name1 to "Simone" Note that, unlike its JavaScript cousin, eval( ) in ActionScript does not allow for the compiling and execution of arbitrary blocks of code in a string. Full support of eval( ) would require an ActionScript compiler in the Player, which would cause too great an increase in the Player size. UsageAs of Flash 5, eval( ) is rarely needed for dynamic variable access. When managing multiple pieces of data, use arrays and objects instead. ExampleThe eval( ) function is often used to convert the MovieClip._droptarget string property to a movie clip object reference. In the following example, suppose we have a series of cartoon face clips. When the user drops a food clip onto one of the faces, we retrieve the path to the face in question using _droptarget, then we use eval( ) to retrieve an object reference to that face. Finally, we send the face to a frame showing the mouth full of food: // Convert _droptarget string to a reference theFace = eval(food._droptarget); // Control appropriate face clip using converted reference theFace.gotoAndStop("full"); See AlsoSee Section 4.6.10, "Executing Code in a String with eval" in Chapter 4, "Primitive Datatypes"
AvailabilityFlash 4 and later Synopsis_focusrect AccessRead/write DescriptionWhen the mouse hovers over a button in Flash, the content of the button's Over state is displayed. Buttons can also gain keyboard focus when the user presses the Tab key. When a button has keyboard focus, Flash places a yellow rectangle over that button, which is not always aesthetically desirable. You can turn off the yellow highlight rectangle using the _focusrect global property, like so: _focusrect = false; When _focusrect is set to false, Flash displays the Over state of keyboard-focused buttons. When _focusrect is set to true (its default), Flash displays the yellow rectangle. UsageThough _focusrect is used in a Boolean sense, it actually stores a number, not a Boolean. Although there's rarely a reason to do so, if we examine the value of _focusrect, it returns either 1 (indicating true) or (indicating false).
AvailabilityFlash 3 and later (enhanced in Flash 5 to include trapallkeys) Synopsisfscommand(command, arguments) Arguments
DescriptionWith the fscommand( ) function, a Flash movie can communicate with the standalone Player or with the Player's host application -- the environment in which the Flash Player is running (e.g., a web browser or Macromedia Director). The fscommand( ) function is typically used in one of three ways:
When used with the standalone Player, fscommand( ) takes one of the built-in sets of command /argument pairs, as shown in Table 20-5. Table 20-5. command/argument Pairs in Standalone Player
When used in a browser, the execution of an fscommand( ) function in a movie causes the invocation of a special JavaScript function (Netscape) or VBScript function (Internet Explorer) on the page that contains the movie. The name of this special function takes the general form movieID_DoFSCommand where movieID is the name specified in the movie's OBJECT ID attribute (Internet Explorer) or EMBED NAME attribute (Netscape) from the host HTML document. When movieID_DoFSCommand( ) is invoked, the values of the fscommand( ) 's command and arguments parameters are passed to the movieID_DoFSCommand( ) function as arguments. If no movieID_DoFSCommand( ) function exists in the host page, fscommand( ) fails silently. Note that in order for fscommand( ) to work with Netscape, the swLiveConnect attribute of the movie's EMBED tag must be set to "true". For example: <EMBED NAME="testmovie" SRC="myMovie.swf" WIDTH="100%" HEIGHT="100%" swLiveConnect="true" PLUGINSPAGE="http://www.macromedia.com/go/flashplayer/" </EMBED> UsageIt is not possible to communicate with a browser via fscommand( ) under the following system configurations:
Note that fscommand( ) does not always provide the best means of communicating with a Director movie from Flash. The preferred director communication device is a getURL( ) function with either the event: or lingo: protocol. For details, see the getURL( ) function or the following Macromedia tech notes:
ExampleTo quit a standalone Projector, use: fscommand("quit"); To create a standalone Projector that runs fullscreen, use: fscommand("fullscreen", "true"); To create a standalone Projector that runs fullscreen but maintains the original movie's size, use: fscommand("fullscreen", "true"); fscommand("allowscale", "false"); For information on launching a movie in a fullscreen web browser window, see http://www.moock.org/webdesign/flash/launchwindow/fullscreen. To launch Notepad on most Windows systems, use: fscommand("exec", "C:/WINDOWS/NOTEPAD.EXE"); The following code shows an HTML page with the JavaScript and VBScript needed to respond to a simple fscommand( ) from a movie. Notice that the VBScript function simply calls the JavaScript function; this allows us to handle both Internet Explorer and Netscape with a single JavaScript function: <HTML> <HEAD> <TITLE>fscommand demo</TITLE> <SCRIPT LANGUAGE="JavaScript"> <!-- function testmovie_DoFSCommand(command, args) { alert("Here's the Flash message " + command + ", " + args); } //--> </SCRIPT> <SCRIPT LANGUAGE="VBScript"> <!-- Sub testmovie_FSCommand(ByVal command, ByVal args) call testmovie_DoFSCommand(command, args) end sub //--> </SCRIPT> </HEAD> <BODY BGCOLOR="#FFFFFF"> <OBJECT ID="testmovie" CLASSID="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" WIDTH="100%" HEIGHT="100%" CODEBASE="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab"> <PARAM NAME="MOVIE" VALUE="flash-to-javascript.swf"> <EMBED NAME="testmovie" SRC="flash-to-javascript.swf" WIDTH="100%" HEIGHT="100%" swLiveConnect="true" PLUGINSPAGE="http://www.macromedia.com/go/flashplayer/" </EMBED> </OBJECT> </BODY> </HTML> To invoke the preceding testmovie_DoFSCommand( ) JavaScript function from the flash-to-javascript.swf movie, we'd use: fscommand("hello", "world"); See AlsoFor more information on fscommand( ) and controlling Flash with JavaScript, see:
AvailabilityFlash 4; deprecated in Flash 5 SynopsisgetProperty(movieClip, property) Arguments
ReturnsThe value of movieClip's property. DescriptionThe getProperty( ) function retrieves the value of one of a movie clip's built-in properties. Though getProperty( ) was the only way to access object properties in Flash 4, the . and [] operators are the preferred property-access tools in Flash 5 and later. ExampleEach of the following getProperty( ) invocations retrieve the values of the _x property of a movie clip named ball on the main movie timeline: getProperty(ball, _x); // Relative movie clip reference getProperty(_root.ball, _x); // Absolute movie clip reference getProperty("ball", _x); // Relative path in string getProperty("_root.ball", _x); // Dot path in string getProperty("/ball", _x); // Slash path in string The following code shows similar property access using the dot and [ ] operators: ball._x; _root.ball._x; ball["_x"]; _root["ball"]["_x"]; See AlsosetProperty( ) ; Section 13.1, "The "Objectness" of Movie Clips" in Chapter 13, "Movie Clips"
AvailabilityFlash 4 and later SynopsisgetTimer() ReturnsThe number of milliseconds that have passed since the movie started playing. DescriptionThe getTimer( ) function indicates how long a movie has been playing, in milliseconds. We can use multiple getTimer( ) checks to govern the timed execution of a block of code or to add time-based features to a movie, such as a countdown in a video game. For example, when attached to a movie clip that contains a text field named counterOutput, the following code counts down from 60 to 0: onClipEvent (load) { // Record the current time var startTime = getTimer( ); // Set the number of seconds to count down var countAmount = 60; // Initialize a variable to keep track of how much time has passed var elapsed = 0; } onClipEvent (enterFrame) { // Check how much time has passed elapsed = getTimer( ) - startTime; // If the time passed is less than the length of our countdown... if (elapsed < countAmount * 1000) { // ...set the text field to show the amount of time left counterOutput = countAmount - Math.floor(elapsed / 1000); } else { // ...otherwise, our countdown is done, so tell the user counterOutput = "Time's UP!"; } } To determine the number of full seconds that have passed in a movie (rather than milliseconds), divide the return of getTimer( ) by 1000 and trim off the decimal portion with either Math.floor( ), Math.round( ), or Math.ceil( ). For example: numSeconds = Math.floor(getTimer( )/1000); ExampleThe following code loops between two frames until a movie is more than 10 seconds old and then plays the movie: now = getTimer( ); if (now > 10000) { play( ); } else { gotoAndPlay(_currentframe - 1); } See AlsoDate( ), the Date class
AvailabilityFlash 2 and Flash 3; enhanced in Flash 4 to include method parameter; Flash 5 SynopsisgetURL (URL) getURL (URL, window) getURL (URL, window, method) Arguments
DescriptionThe getURL( ) function is used to:
To load a document into the current window or frame, simply specify the URL of the document without supplying a window or method argument. Naturally, Flash supports absolute URLs (those that contain a protocol such as "http:" plus a server name or hardware device) and relative URLs (those that are relative to the current location): getURL("http://www.moock.org/"); // Absolute URL to web page getURL("file:///C|/WINDOWS/Desktop/index.html"); // Absolute URL to local file getURL("/whatever/index.html"); // Relative URL, http protocol //is assumed To load a document into a named window or frame, supply the window or frame name as the window argument. For example: getURL("http://www.moock.org/", "contentFrame"); // Load into named frame getURL("http://www.moock.org/", "remoteWin"); // Load into named window To replace the frameset that contains the current movie, use "_ parent" as the value of the window argument. For example: getURL("http://www.moock.org/", "_parent"); To replace all framesets in a web page with a loaded document, use "_top" as the value of the window argument. For example: getURL("http://www.moock.org/", "_top"); To open a loaded document in a new, anonymous browser window, use "_blank" as the value of the window argument. For example: getURL("http://www.moock.org/", "_blank"); Note that launching a new window with "_blank" does not give us any control over the appearance of the new window (size, toolbar configuration, location, etc.). To launch customized windows with getURL( ), we must invoke a JavaScript function on the movie's host page. JavaScript window-launching techniques are described at http://www.moock.org/webdesign/flash. The getURL( ) function may also be used to send variables to a remote server application or script. To send the current movie clip's timeline variables to an external script, specify the name of the script as the URL argument, and use either "GET" or "POST" as the value of the method argument. For example: getURL("http://www.someserver.com/cgi-bin/search.pl", "resultsFrame", "GET"); When invoked as a movie clip method, getURL( ) sends the timeline variables of that clip, as in: // Sends myClip's variables to search.pl myClip.getURL("http://www.server.com/cgi-bin/search.pl", "resultsFrame", "GET"); The results of the script execution will appear in the window or frame specified in the getURL( ) 's window argument (which is required when variables are submitted). To load the results of a script execution into the current frame or window, use "_self" as the window argument value, as in: getURL("http://www.someserver.com/cgi-bin/search.pl", "_self", "GET"); When the method argument is "GET", the current movie clip timeline variables are sent as a query string attached to the script URL in an HTTP GET request. Query strings are composed of variable name/value pairs, separated by ampersands (&). For example: http://www.someserver.com/cgi-bin/search.pl?term=javascript&scope=entiresite When the method argument is "POST", the current movie clip timeline variables are sent to the script as a separate block of data after the HTTP POST-request header (exactly like a regular HTML form that uses the POST method). Note that "POST" is not available in the standalone Flash Player. Because most web servers restrict the length of URLs to between 255 and 1024 characters, use "POST" instead of "GET" to transfer larger amounts of data. Note that any returned information sent by a script invoked by getURL( ) is displayed as regular web content in the browser, not in Flash. To accept the results of a script execution into Flash, use loadVariables( ). The getURL( ) function can also be used with protocols other than "http:" as shown in Table 20-6. Table 20-6. Supported Protocols for getURL
As Table 20-6 shows, if the Flash asset is imported into a Macromedia Director file, getURL( ) can be used to trigger Lingo events or execute a Lingo command. (Lingo is Director's scripting language, akin to ActionScript). For example, you can add a frame event of this form: getURL ("event: eventName params"); which will cause the Lingo event handler named on eventName to be called in Director. Here is a getURL( ) statement that generates an event named "myEvent" and passes it the string "A". Note that the " character is escaped using the sequence \": getURL ("event: myEvent \"A\""); // Send an event to Director Here is the Lingo sprite event handler that should be attached to the Flash sprite asset in Director in order to receive the event. Note that a Director sprite is roughly equivalent to a Flash movie clip instance; the Lingo keyword put is akin to ActionScript's trace( ) command, and && is Lingo's string concatenation operator: on myEvent msg put "The message received from Flash was " && msg end You can also trigger Lingo to be executed from a Flash sprite within Director using the "lingo:" keyword, such as: getURL ("lingo: beep"); // Tell Director to play a beep sound Note that Director 8.0 cannot import Flash 5 .swf files, but an updated Flash asset Xtra is expected to be available by the time you read this. Finally, getURL( ) can also be used to execute JavaScript code. Here we invoke a simple JavaScript alert using getURL( ): getURL ("javascript: alert('hello world');"); Note that execution of JavaScript code from a URL does not work in Internet Explorer 4.5 for Macintosh. ExampleHere's the code for a standard button that links to a web page: on (release) { getURL("http://www.macromedia.com/"); } BugsInternet Explorer 4.5 (IE 4.5) and older versions on Macintosh do not support the "POST" method of a getURL( ) call. To service those browsers, use "GET" instead of "POST" (subject to the length limitations cited earlier). In most browsers, getURL( ) relative links are resolved relative to the HTML file that contains the .swf file. In IE 4.5 and older versions on Macintosh, relative links are resolved relative to the location of the .swf file, not the HTML file, which causes problems when the two are in different directories. To avoid the problem, either place the .swf and the .html file in the same directory or use absolute URLs when invoking getURL( ), such as: getURL ("http://www.someserver.com/") See AlsoloadVariables( ), MovieClip.getURL( ), movieClip.loadVariables( ); Section 18.5.7, "< A> (Anchor or Hypertext Link)" in Chapter 18, "On-Screen Text Fields"
AvailabilityFlash 5 SynopsisgetVersion() ReturnsA string containing version and platform information for the Flash Player hosting the current movie. DescriptionThe getVersion( ) function tells us the platform and Flash Player version being used to view a movie. It can be used to conditionally execute different code for specific versions of the Flash Player or on certain operating systems. The string returned by getVersion( ) takes the form: platform majorVersion,minorVersion,buildNumber,patch Where platform is a code indicating the platform ("WIN", "MAC", or "UNIX"), followed by the major version number, the minor version number, and the build (a.k.a. revision) number. The last item, patch, is typically 0. For example: WIN 5,0,30,0 // Version 5.0, Build 30 (5.0r30) on Windows MAC 5,0,41,0 // Version 5.0, Build 41 (5.0r41) on Macintosh UNIX 4,0,12,0 // Version 4.0, Build 12 (4.0r12) on Unix Despite the Macromedia documentation's claim to the contrary, getVersion( ) does work in the Flash authoring tool's Test Movie mode. It reports the version number of the Player embedded in the authoring tool (which is not the same as the version of the authoring tool itself). For example, the Flash 5 authoring tool embeds the 5.0 r30 version of the Player, so its getVersion( ) function reports: WIN 5,0,30,0 or MAC 5,0,30,0 Any time a major or minor version of the authoring tool is created, the buildNumber restarts at 0. However, in the typical development cycle of the Flash authoring tool, many builds of the Flash Player are produced before the final version of the authoring tool is released. The build number of the first new major version of a Player is, hence, usually greater than 0. For example, the Flash 5 Player was first officially released at Build 30. Presumably, when Flash 6 is introduced, the Flash 6 Player will return something like: WIN 6,0,xx,0 but if a movie created in Flash 6 is played back in the Flash 5 Player, getVersion( ) would still return: WIN 5,0,30,0 Typically, we're concerned with only the platform, the major version, and the build number of a Player. To extract the portion of the getVersion( ) string we're after, we may use the string manipulation tools described in Chapter 4, "Primitive Datatypes", or we may construct a custom object with each component of the getVersion( ) string assigned to a property of that object as shown in the next example. Unless we need to produce internal blocks of ActionScript code for a specific version of the Flash Player, JavaScript and VBScript provide better tools for version detection, browser sniffing, and automatic page redirection. Furthermore, you can't use getVersion( ) unless the user already has version 5.0 or later of the Player. For details on detecting the Flash Player's presence and version with JavaScript and VBScript, see http://www.moock.org/webdesign/flash/detection/moockfpi. ExampleThe following code extracts the various portions of the string returned by getVersion( ) and stores them as the properties of an object for easy access: // Split up the getVersion( ) string into usable pieces var version = getVersion( ); var firstSpace = version.indexOf(" "); var tempString = version.substring(firstSpace + 1, version.length); var tempArray = tempString.split(","); // Assign the various parts of the getVersion( ) string to our object. // Note that we convert the version number portions to integers. var thePlayer = new Object( ); thePlayer.platform = version.substring(0,firstSpace); thePlayer.majorVersion = parseInt(tempArray[0]); thePlayer.minorVersion = parseInt(tempArray[1]); thePlayer.build = parseInt(tempArray[2]); thePlayer.patch = parseInt(tempArray[3]); // Now use our object to perform version-specific code if (thePlayer.platform == "WIN") { // Perform Windows-specific code here. } else if (thePlayer.platform == "MAC") { // Perform Mac-specific code here. } else if (thePlayer.platform == "UNIX") { // Perform Unix-specific code here. } if ((thePlayer.majorVersion == 5) && (thePlayer.build == 30)) { trace ("I recommend upgrading your player to avoid text display bugs"); } See Also$version; Appendix C, "Backward Compatibility"
AvailabilityFlash 2 and later SynopsisgotoAndPlay(frameNumber) gotoAndPlay(frameLabel) gotoAndPlay(scene, frameNumber) gotoAndPlay(scene, frameLabel) Arguments
DescriptionWhen invoked without a scene argument, gotoAndPlay( ) sends the playhead of the current timeline to the frame specified by either the frameNumber or frameLabel and then plays the timeline from that point. The "current timeline" is the movie clip or movie from which the gotoAndPlay( ) function is invoked. If two arguments are specified in the gotoAndPlay( ) function call, the first argument is assumed to be the scene. If only one argument is specified, it is treated as a frameNumber or frameLabel, and the current scene is assumed. When invoked with a scene argument, gotoAndPlay( ) moves the playhead to the frame number or label in the specified scene and then plays that scene. If a scene argument is used, the gotoAndPlay( ) function must be invoked from the _root timeline; otherwise, the operation fails silently and the playhead is not sent to the destination frame. Note that scenes are flattened into a single timeline during movie playback. That is, if scene 1's timeline contains 20 frames, and scene 2's timeline contains 10 frames, then we can send the playhead to frame 5 of scene 2 using gotoAndPlay(25);.
The global gotoAndPlay( ) function affects only the current timeline. The frames or state of other movie clips within the current timeline are not affected. To cause other movie clips to play, you must issue a separate play( ) or gotoAndPlay( ) command for each movie clip. To apply the gotoAndPlay( ) function to a clip other than the current movie clip, use the movie clip method form, myClip.gotoAndPlay( ). BugsIn Build 5.0r30 of the Flash Player, gotoAndPlay( ) did not work when used in an onClipEvent( ) handler with a string literal for frameLabel. To work around the bug, use the movie clip variation of the function using this to indicate the current clip, as in this.gotoAndPlay("myLabel"), rather than gotoAndPlay("myLabel"). Example// Go to frame 5 of the current timeline and play it gotoAndPlay(5); // Go to frame 10 of the exitSequence scene, and play it gotoAndPlay("exitSequence", 10); // Go to frame "goodbye" of the exitSequence scene, and play it gotoAndPlay("exitSequence", "goodbye"); // Caution! This plays the frame labeled "exitSequence" in the current scene. gotoAndPlay("exitSequence"); // This plays frame 1 of the exitSequence scene gotoAndPlay("exitSequence", 1); See AlsogotoAndStop( ), MovieClip.gotoAndPlay( ), play( ), stop( )
AvailabilityFlash 2 and later SynopsisgotoAndStop(frameNumber) gotoAndStop(frameLabel) gotoAndStop(scene, frameNumber) gotoAndStop(scene, frameLabel) Arguments
DescriptionWhen invoked without a scene argument, gotoAndStop( ) sends the playhead of the current timeline to the frame specified by either the frameNumber or frameLabel argument. The "current timeline" is the movie or movie clip from which the gotoAndStop( ) function is invoked. The playhead will stop at the target frame; it will not advance automatically after arriving at the target frame. If two arguments are specified in the gotoAndStop( ) function call, the first argument is assumed to be the scene. If only one argument is specified, it is treated as a frameNumber or frameLabel, and the current scene is assumed. When invoked with a scene argument, gotoAndStop( ) moves the playhead to the frame number or label in the specified scene and then halts playback. If a scene argument is used, the gotoAndStop( ) function must be invoked from the _root timeline; otherwise, the operation fails silently and the playhead is not sent to the destination frame. The global gotoAndStop( ) function affects only the current timeline. The frames or state of other movie clips within the current timeline are not affected. To move the playhead of other movie clips, you must issue a separate gotoAndStop( ) command for each movie clip. To apply the gotoAndStop( ) function to a clip besides the current movie clip, use the movie clip method of the form myClip.gotoAndStop( ). BugsIn Build 5.0r30 of the Flash 5 Player, gotoAndStop( ) did not work when used in an onClipEvent( ) handler with a string literal for frameLabel. To work around the bug, use the movie clip variation of the function using this to indicate the current clip, as in this.gotoAndStop("myLabel"), rather than gotoAndStop("myLabel"). Example// Go to frame 5 of the current timeline and stop there gotoAndStop(5); // Go to frame 20 of the introSequence scene and stop there gotoAndStop("introSequence", 20); // Go to frame "hello" of the introSequence scene, and stop there gotoAndStop("introSequence", "hello") // Caution! This goes to the frame labeled "introSequence" in the current scene gotoAndStop("introSequence") // This goes to frame 1 of the introSequence scene gotoAndStop("introSequence", 1) See Also
AvailabilityFlash 4; deprecated in Flash 5 in favor of _quality Synopsis_highquality AccessRead/write DescriptionThe _highquality global property stores an integer between 0 and 2 that dictates the rendering quality of the Flash Player as follows:
As of Flash 5, _highquality has been superseded by _quality, which may be used to set a movie's quality to "Medium", as well as "Low", "High", and "Best". See Also_quality, toggleHighQuality( )
AvailabilityFlash 5 Synopsis#include path Arguments
DescriptionThe #include directive brings script text from an external text file (preferably one with the .as extension) into the current script, placing it directly where the #include command occurs in the script. The #include operation is performed at compile time, meaning that the text included in a movie is the text that existed at the time the movie was tested, exported, or published from the authoring tool. If the external file changes after the movie is exported, the changes will not be reflected in the movie. In order for the changes to be added to the movie, the movie must be re-exported. The #include directive is used to incorporate the same block of code in multiple scripts or across Flash projects (much as you'd use an external asset library). You would do this in order to centralize your code, when maintaining code in a version-control system tool (such as CVS or Microsoft Visual Source Safe), or when using an external text editor that you prefer over the ActionScript editor. It is also handy when a programmer is working separately from, say, a graphic artist creating the Flash animations. External files lend themselves well to code repositories, such as a library of functions that are independent of the current timeline or movie clip. They tend to be less useful for code that needs to be tightly integrated with the Flash file. UsageNote that an #include directive begins with a pound sign (#), does not use parentheses, and must not end in a semicolon. Any #include statements that end in a semicolon will cause an error and will not successfully import an external script. If the file can't be found at the specified path, the directive will cause an error and no external text will be included. The text in the external file is also checked when performing a syntax check using the Check Syntax command (Ctrl-T or Command-T) in the Actions panel menu (found under the arrow button in the upper-right corner of the panel). ExampleThe following code imports an external .as file named myScript.as into the current .fla file. When using a relative path, myScript.as would have to be in the same folder as the .fla file containing the include directive: #include "myScript.as" We can construct a relative path including a subdirectory. The following assumes that myScript.as is one level down from the current .fla file in a subdirectory named includes: #include "includes/myScript.as" Use two dots to indicate the folder above the current folder. The following assumes that myScript.as is one level up from the current .fla file: #include "../myScript.as" The following assumes that myScript.as is in a subdirectory named includes adjacent to the subdirectory containing the current .fla file: #include "../includes/myScript.as" You can also specify an absolute path to any folder, such as: #include "C:/WINDOWS/Desktop/myScript.as" but absolute paths are not cross-platform and may need to be changed if you compile the .fla file on a different machine with different directories. Note the differences in the drive letter specification: #include "C:/WINDOWS/Desktop/myScript.as" // Windows #include "Mac HD:Desktop folder:working:myScript.as" // Macintosh See AlsoSee Section 16.7, "Externalizing ActionScript Code" in Chapter 16, "ActionScript Authoring Environment"
AvailabilityFlash 5 SynopsisInfinity AccessRead-only DescriptionAny number in ActionScript that exceeds the maximum allowed numeric range is represented by the numeric constant Infinity. The largest value allowed in ActionScript is represented by Number.MAX_VALUE (1.7976931348623157e+308). ExampleThe result of a calculation that exceeds the largest allowed number is Infinity. For example: Number.MAX_VALUE * 2; // Yields Infinity Infinity also results when dividing a positive number by zero: 1000 / 0; // Yields Infinity UsageInfinity is shorthand for Number.POSITIVE_INFINITY. See Also-Infinity, Number.POSITIVE_INFINITY; Section 4.3.3, "Special Values of the Number Datatype" in Chapter 4, "Primitive Datatypes"
AvailabilityFlash 5 Synopsis-Infinity AccessRead-only DescriptionAny number in ActionScript that exceeds the allowed negative numeric range is represented by the numeric constant -Infinity. The smallest negative value (the one with the largest absolute value) allowed in ActionScript is -Number.MAX_VALUE, which is equivalent to -1.7976931348623157e+308. ExampleThe result of a calculation that is smaller than (i.e., more negative than) the smallest allowed negative number is -Infinity. For example: -Number.MAX_VALUE * 2; // Yields -Infinity -Infinity also results when dividing a negative number by zero: -1000 / 0; // yields -Infinity Usage-Infinity is shorthand for Number.NEGATIVE_INFINITY. See AlsoInfinity, Number.NEGATIVE_INFINITY; Section 4.3.3, "Special Values of the Number Datatype" in Chapter 4, "Primitive Datatypes"
AvailabilityFlash 4; deprecated in Flash 5 in favor of analogous Math methods Synopsisint(number) Arguments
ReturnsThe integer portion of number. DescriptionThe int( ) function was used in Flash 4 as a brute-force means of extracting the integer portion of a number. It effectively rounds positive numbers down and rounds negative numbers up. The int( ) function works only for numbers in the range -2147483648 (-231) to 2147483647 (231-1); it produces undefined results for numbers outside this range. If number is a string composed of only numbers, int( ) converts the string to a number before operating on it. If number is the Boolean value true, int( ) returns the value 1. For all other non-numeric data (including undefined and null), int( ) returns the value 0. UsageThe int( ) function has been deprecated in favor of the more precise and standard Math.floor( ), Math.ceil( ), and Math.round( ) methods. Use parseInt( ) or Number( ) to convert non-numeric data to an integer or number. Exampleint(4.5) // Yields 4 int(-4.5) // Yields -4 int(3.999) // Yields 3 The int( ) function is useful to check if a number is a whole number by comparing the original number to the result of the int( ) function: if (int(x) != x) { trace ("Please enter a whole number for your age in years"); } See AlsoMath.ceil( ), Math.floor( ), Math.round( ), Number( ), parseFloat( ), parseInt( )
AvailabilityFlash 5 SynopsisisFinite(number) Arguments
ReturnsA Boolean value; true if the number falls between Number.MAX_VALUE and -Number.MAX_VALUE (inclusive), false if not. If number does not belong to the number datatype, number is converted to the number type before isFinite( ) executes. DescriptionThe isFinite( ) function simply checks if a number is in the legal numeric value range of ActionScript. Use isFinite( ) before executing code that requires a legitimate number to operate properly. Exampleif (!isFinite(x * y)) { // Test if the number is not finite trace ("The answer is too large to display. Try again."); } isFinite(-2342434); // Yields true isFinite(Math.PI); // Yields true isFinite(Number.MAX_VALUE * 2) // Yields false See Also-Infinity, Infinity, isNan( ), Number.MAX_VALUE, Number.MIN_VALUE; Section 4.3.3, "Special Values of the Number Datatype" in Chapter 4, "Primitive Datatypes"
AvailabilityFlash 5 SynopsisisNaN(value) Arguments
ReturnsA Boolean value: true if value is the special numeric value NaN; otherwise, false. DescriptionTo test whether or not a value is equal to the special numeric value NaN, we must use the isNaN( ) function because NaN does not test equal to itself in an ordinary equality test. For example, the expression: NaN == NaN; yields the value false. The isNaN( ) function is often used to check whether a mathematical error (such as zero divided by itself) has occurred in a phrase of code or whether converting a value to a legitimate number has failed. Because isNaN( ) returns true when the expression is not a valid numeric expression, you'll often use the logical NOT operator (!) along with isNaN( ) (something that is not not a number is a number). Note that 0/0 yields NaN, but all positive numbers divided by yield Infinity, and all negative numbers divided by yield -Infinity. Example// Set a value var x = "test123"; // Check if x is a legitimate number before using it is in a math expression. // This is a handy technique for user input in text fields, which always a string. if (!isNaN(parseFloat(x))) { var y = parseFloat(x) * 2; } See AlsoisFinite( ), NaN; Section 4.3.3, "Special Values of the Number Datatype" in Chapter 4, "Primitive Datatypes"
AvailabilityFlash 5 SynopsisKey.propertyKey.methodName() PropertiesTable 20-7 lists the properties of the Key object. Table 20-7. Key Object Keycode Properties
Methods
DescriptionThe Key object is used to determine which keys are currently depressed and which key was last depressed. We can use it to build interfaces controlled by the keyboard, such as a game with a spaceship moved via the arrow keys. Because not all keyboards are identical, keyboard-controlled interfaces can sometimes be tricky to create. By choosing our scripting tools correctly, however, we can ensure that all users have the same experience. There are two general approaches to detecting keyboard commands:
The so-called Windows virtual keycode (or simply, keycode) returned by getCode( ) and required by isDown( ) is a number representing the physical keys on the keyboard, not the symbols on those keys. By using the keycode, we can identify keys even when a movie is running on different operating systems or when two keyboards use different languages or have different symbol layouts. On most keyboards the keycodes of the keys A to Z are the same as the code points (65-90) for the equivalent uppercase Latin 1 letters. The keycodes of the keys to 9 are, likewise, the same as the Latin 1 values for those numbers (48-57). The key codes of other keys do not match Latin 1 code points. However, many of the non-letter and non-number keycodes are available as properties of Key. For example, we don't have to remember that the up arrow uses keycode 38, we simply use the Key.UP property. The following code checks whether the up arrow key is currently depressed: if (Key.isDown(Key.UP)) { trace("The up arrow is being pressed"); } When working with a keycode that is not a letter or a number and is not available as a property of Key -- such as those of the function keys (F1, F2, etc.) -- it's safest to create a quick test movie to check the keycode of the desired key, as follows: trace(Key.getCode( )); The keycodes are listed in Appendix B, "Latin 1 Character Repertoire and Keycodes". See AlsoSection 10.11.5, "keyUp" and Section 10.11.4, "keyDown" in Chapter 10, "Events and Event Handlers", and Appendix B, "Latin 1 Character Repertoire and Keycodes"
AvailabilityFlash 5 SynopsisKey.getAscii() ReturnsAn integer representing the ASCII value of the last key pressed. DescriptionThe getAscii( ) method returns the ASCII value of the last key that was pressed. Since not all keys have an ASCII value, getAscii( ) is normally used for detecting letters and numbers from the Latin 1 character set (Western European languages). Unlike getCode( ), getAscii( ) distinguishes between upper- and lowercase letters. But unlike getCode( ), it cannot differentiate between two keys with the same ASCII value, such as the 8 key on the main keyboard and the 8 key on the numeric keypad. To detect the pressing of specific keys relative to their physical location on a keyboard rather than their ASCII value (such as would be desirable when using four keys in a diamond pattern to control game play), use getCode( ). ExampleThe following example demonstrates keystroke detection for a simple hangman word game. It uses a keyDown event handler to identify the pressing of a key and adds that key to a list of user guesses: onClipEvent (keyDown) { var lastKey = Key.getAscii( ); guessNum++; userGuesses[guessNum] = String.fromCharCode(lastKey); } See AlsoKey.getCode( ); Appendix B, "Latin 1 Character Repertoire and Keycodes", and Section 10.11.4, "keyDown" in Chapter 10, "Events and Event Handlers"
AvailabilityFlash 5 SynopsisKey.getCode() ReturnsAn integer representing the keycode of the last key pressed. DescriptionThe getCode( ) method returns the keycode of the last key that was pressed, which is an arbitrary number representing the physical location of a key on the keyboard. On non-Windows operating systems, the native keycode system is translated automatically by Flash to the Windows equivalent, so getCode( ) provides a cross-platform means of referring to specific keys. The getCode( ) method can also be used to differentiate between two keys with the same ASCII value. For example, it can differentiate between the 8 key on the main keyboard and the 8 key on the numeric keypad, whereas getAscii( ) cannot. However, getCode( ) cannot differentiate between upper- and lowercase letters (for example, A and a use the same keycode because they are produced using the same key). Many common keycode values are available as properties of the Key object (e.g., Key.UP, Key.BACKSPACE). To determine the keycode of a particular key, see Appendix B, "Latin 1 Character Repertoire and Keycodes" or construct a keycode tester as follows:
ExampleUnlike isDown( ), getCode( ) is useful for creating interfaces where an individual key press has a single, direct result. For example, the user may be able to skip a movie's intro by pressing the spacebar. When the spacebar is depressed, we send the playhead to the main interface of the movie (on the main timeline) as follows: // Code on intro clip onClipEvent (keyDown) { if (Key.getCode( ) == Key.SPACE) { _root.gotoAndStop("mainInterface"); } } See AlsoKey.getAscii( ), Key.isDown( ); Appendix B, "Latin 1 Character Repertoire and Keycodes", and Section 10.11.4, "keyDown" in Chapter 10, "Events and Event Handlers"
AvailabilityFlash 5 SynopsisKey.isDown(keycode) Arguments
ReturnsA Boolean indicating whether the key specified by keycode is pressed (true) or not pressed (false). DescriptionThe isDown( ) method tells us whether the key specified by keycode is currently being pressed. It offers arbitrary, immediate access to the state of the keyboard and is best used with systems that require constant key-based input or that detect the pressing of simultaneous keys. One important advantage of isDown( ) over getCode( ) and getAscii( ) is its ability to detect the simultaneous pressing of multiple keys. By checking for both Key.UP and Key.RIGHT, for example, we may determine that a spaceship in a game should be moved diagonally. Depending on the placement of the specific keys being tested, the maximum number of keys that can be simultaneously detected may be as low as three. ExampleThe isDown( ) method is normally used to create systems that undergo a constant update with each passing frame. In the following code, we rotate and thrust a spaceship on any frame where the appropriate arrow keys are being pressed. Note that if you need to detect two keys simultaneously, you should use separate if statements. In this example, the state of the right arrow key is ignored if the left arrow key is also being depressed. But regardless, the state of the up arrow key is always checked in a separate if statement. A working version of this spaceship example is available from the online Code Depot: // Code on a spaceship clip onClipEvent (enterFrame) { if (Key.isDown(Key.LEFT)) { // Left arrow _rotation -= 10; } else if (Key.isDown(Key.RIGHT)) { // Right arrow _rotation += 10; } if (Key.isDown(Key.UP)) { // Up arrow thrust += 10; } } See AlsoKey.getCode( ); Section 10.11.4, "keyDown" in Chapter 10, "Events and Event Handlers"
AvailabilityFlash 5 SynopsisKey.isToggled(keycode) Arguments
ReturnsA Boolean indicating whether the key specified by keycode is on (true) or off (false). DescriptionThe isToggled( ) method detects the state of the special Caps Lock, Num Lock, or Scroll Lock keys. Unlike other keys, these keys have an "on" state and an "off" state indicating whether or not the feature they represent is active. The return of isToggled( ) tells us if the key's feature is in effect or not. (Though isToggled( ) actually works for any keycode, its return value is useful only for special keys that support a toggle feature. To detect the state of other keys, use isDown( ), getCode( ), or getAscii( ).)
AvailabilityFlash 3 and later Synopsis_level0 _level1 _level2 ... _leveln AccessRead-only DescriptionMultiple .swf files may be loaded into the Flash Player for simultaneous display. Each loaded .swf resides on its own level in the document level stack. (A .swf file on a higher level number will obscure lower levels if they occupy the same portion of the Stage.) The _leveln property stores a reference to the main timeline of a .swf loaded into a document level in the Player. Each document level is represented by a numbered property, such as _level0, _level1, _level2, and so on. The original document loaded into any Flash Player is considered _level0. ExampleA _leveln reference is normally used to control movies on other levels of the document stack. For example, here we play the movie on level 2: _level2.play( ); We can also use _leveln in combination with movie clip references to control clips contained by a movie on any level in the document stack. For example: _level1.orderForm.titleBar.play( ); A _leveln reference may also be used as the value of the target argument of several functions, including loadMovie( ), unloadMovie( ), loadVariables( ) and print( ). If the level does not yet exist, you should specify the level reference within quotes. If used without quotes, a nonexistent level is considered undefined and may cause the command to operate on the current timeline instead of the new, undefined level. For example, when executed from the main timeline of _level0, the following will replace the movie in _level0 if _level1 has not yet been defined: loadMovie("myMovie.swf", _level1); The following is a safer approach if you can't guarantee that the level already exists: loadMovie("myMovie.swf", "_level1"); // Works even if _level1 doesn't exist Of course, from other levels, you may wish to refer to the original level, using _level0, such as: startDrag(_level0, true); See AlsoloadMovie( ), unloadMovie( ), -root; Section 13.3.4, "Importing External Movies" and Section 13.4, "Movie and Instance Stacking Order" in Chapter 13, "Movie Clips"
AvailabilityFlash 4 and later. The loadMovie( ) function in Flash 5 corresponds to the Flash 4 Load Movie with a target path. SynopsisloadMovie(URL, target) loadMovie(URL, target, method) Arguments
DescriptionThe loadMovie( ) function imports the .swf file located at URL into the Flash Player. If target is a reference to an existing movie clip or a string indicating the path to a movie clip, the loaded .swf file is placed into the specified clip (causing the eviction of any previous content). To load a movie into the current movie clip, use the empty string as the target parameter, as in: loadMovie("myMovie.swf", "") If target is a reference to an existing document level (such as _level2) or a string indicating the path to a document level (such as "_level2"), then the .swf is placed into the specified document level. Loading a movie into _level0 clears the Player of all content and places the new .swf file into _level0. It is possible to send variables along with a loadMovie( ) invocation, in which case URL is normally the location of a script that returns a .swf file based on the variables sent. To send variables with a loadMovie( ) call, we include the method argument (set to either "GET" or "POST"). "GET" sends the current movie clip timeline variables as a query string attached to the script URL. "POST" sends the current movie clip timeline variables after the HTTP POST-request header. The "POST" method is not available in the standalone Flash Player. Because most web servers restrict the length of URLs to between 255 and 1024 characters, use "POST" instead of "GET" to transfer larger amounts of data. Over a web server, loadMovie( ) invocations that use the "GET" method can pass variables to a loaded movie without the help of an intervening script. Here, we load the external movie myMovie.swf into level 1 of the Player document stack, passing it the variables from the current timeline: loadMovie("myMovie.swf", "_level1", "GET"); Variables passed to the loaded movie are defined on that movie's main timeline. This technique works only when the loadMovie( ) request is handled by a web server. Attempts to use the "GET" method with loadMovie( ) using local files will cause an "Error opening URL" error. UsageBe careful when using movie clip and level references as the target argument of loadMovie( ). If a loadMovie( ) 's target argument yields undefined, the loadMovie( ) function uses the current timeline as its target. Similarly, target references that yield the empty string cause loadMovie( ) to operate on the current timeline. In particular, this causes problems for loading movies onto new, unoccupied levels. Consider the following code: loadMovie("myMovie.swf", _level1); If no _level1 object exists prior to the execution of that statement, that code will load myMovie.swf into the timeline that contains the loadMovie( ) statement, not _level1! To avoid the problem, you can use loadMovieNum( ) instead. Alternatively, you can use a string for the target parameter to loadMovie( ), as in: loadMovie("myMovie.swf", "_level1"); In that case, the level will be created if it doesn't already exist (only _level0 exists by default in all movies). For more information, see Section 13.8.3.1, "Method versus global function overlap issues" in Chapter 13, "Movie Clips". ExampleloadMovie("myMovie.swf", "_level1"); // Place myMovie.swf on level 1 loadMovie("myMovie.swf", "_level0"); // Place myMovie.swf on level 0 loadMovie("myMovie.swf", "myClip"); // Place myMovie.swf into myClip // Replace the contents of the Player with // coolmovie.swf, using an absolute path loadMovie("http://www.yourflashsite.com/coolmovie.swf", "_level0"); // Load a movie into level 1 from the Windows desktop. Note the // file:/// protocol and the forward slashes. loadMovie("file:///C|/WINDOWS/Desktop/animation.swf", "_level1"); See AlsoloadMovieNum( ), MovieClip.loadMovie( ), unloadMovie( ); Section 13.3.4, "Importing External Movies" in Chapter 13, "Movie Clips"
AvailabilityFlash 3; enhanced in Flash 4 to include the method parameter; available in Flash 5. The loadMovieNum( ) function corresponds with Flash 3's Load Movie, which accepted only level numbers. SynopsisloadMovieNum(URL, level) loadMovieNum(URL, level, method) Arguments
DescriptionThe loadMovieNum( ) function is nearly identical to loadMovie( ) except that it requires the target level of the load operation to be specified as a number rather than as a string. This means that loadMovieNum( ) can load movies only into document levels, not host clips. If the specified level doesn't exist, it will be created. If the specified level does exist, its occupant is replaced by the new .swf file. It is valid to load a movie into _level2 even if _level1 hasn't been created. The loadMovieNum( ) function can be used when we wish to dynamically assign the level of a loaded movie, as in: var x = 3; loadMovieNum("myMovie.swf", x); which could also be achieved via a string concatenation expression with the regular loadMovie( ) function: loadMovie("myMovie.swf", "_level" + x); See AlsoloadMovie( ), MovieClip.loadMovie( )
AvailabilityFlash 4 and later SynopsisloadVariables(URL, target) loadVariables(URL, target, method) Arguments
DescriptionNormally, we define variables inside our movies using ActionScript. However, using loadVariables( ), we may also import variables into a movie from a text file or a server-side application such as a Perl script. Variables loaded via loadVariables( ) are scoped to the movie clip or level specified by target and are always of the string datatype. To attach loaded variables to the current timeline, use the empty string as the value of the target argument. For example: loadVariables("myVars.txt", ""); // Loads the variables from myVars.txt onto // the current timeline Whether the variables to be loaded reside in a text file or are composed by a script, they must be formatted according to the rules of URL encoding, as follows:
For example, the following code shows the contents of a text file to be imported into Flash via loadVariables( ). The imported variables are name and address, which have the values "stephen" and "65 nowhere st!", respectively: name=stephen&address=65+nowhere+st%21 A text file for use with loadVariables( ) is simply a regular text file containing URL-encoded variables, as shown previously. To load variables from an external text file, we specify the path of the file as the URL argument in our loadVariables( ) function invocation. For example: // Load the variables from myVariables.txt into the main movie timeline loadVariables("myVariables.txt", "_root"); loadVariables( ) may also be used with a script or server application that outputs URL-encoded variables. When a script sends data to a Flash movie in response to a loadVariables( ) function, the script should set the MIME type of the data as: "application/x-www-urlform-encoded". Here's a typical MIME-setting statement from a Perl script: print "Content-type: application/x-www-urlform-encoded\n\n"; Though the name loadVariables( ) suggests only a single direction of variable transmission, it may also be used to send variables to a server-side script. To send all the variables defined on the current timeline to a script, we set the method argument of a loadVariables( ) function invocation to either "GET" or "POST". Variables are sent in URL-encoded format. If method is set to "GET", the variables are sent as a query string of the script URL. If method is set to "POST", the variables are sent after the HTTP POST-request header. The "POST" method is not available in the standalone Flash Player. Because most web servers restrict the length of URLs to between 255 and 1024 characters, use "POST" instead of "GET" to transfer larger amounts of data. For security reasons, loadVariables( ) works only with hosts in the domain from which the movie was downloaded. The rules that govern loadVariables( ) usage are listed in Table 20-8. These security measures affect the Flash Player browser plugins and ActiveX controls only; variables may be loaded from any domain in the standalone Player. Table 20-8. Domain-Based loadVariables( ) Security Restrictions
Domain restriction is an intentional security feature of Flash, but it can be circumvented with either a proxy script running on siteX that acts as a go-between for Flash and siteY, or a DNS alias on siteX that points to siteY. For more information, see:
UsageThe results of multiple loadVariable( ) calls to the same script URL may be cached on some browsers to the point that new data is never loaded from the server. To avoid this problem, append a dummy variable to each loadVariables( ) call so that the URL is unique. For example, here we generate a unique URL by appending the time in milliseconds: loadVariables("http://www.mysite.com/cgi-bin/myScript.pl?cacheKiller=" + getTimer( ), serverResponse); BugsThe POST method is not supported by Internet Explorer 4.5 on Macintosh. This problem was fixed in Version 5 of the browser. See AlsoloadVariablesNum( ) , MovieClip.loadVariables( ); Chapter 17, "Flash Forms"
AvailabilityFlash 5. Use the Load Variables Action in Flash 4 to place variables on a document level. SynopsisloadVariablesNum(URL, level) loadVariablesNum(URL, level, method) Arguments
DescriptionThe loadVariablesNum( ) function is nearly identical to loadVariables( ) except that it requires the target level to be specified as a number rather than as a string. This means that loadVariablesNum( ) can attach variables to document levels only, not movie clips. The target level can be specified dynamically, as in: var myLevel = 2; loadVariablesNum("myVars.txt", myLevel); A similar effect could be achieved using string concatenation with the regular loadVariables( ) function: loadVariables("myVars.txt", "_level" + myLevel); See AlsoloadVariables( )
AvailabilityFlash 5 SynopsisMath.propertyName Math.methodName() Properties
Methods
DescriptionThe Math object provides access to built-in mathematical functions (accessed through methods) and constant values (accessed through properties). These functions and constants are used to perform potentially complex calculations with relative ease. Note that the properties and methods of the Math object may be used in movies exported to the Flash 4 format, in which case Flash will approximate the calculations. The resulting values are reasonable approximations but not necessarily identical to the native Flash 5 functions. The Flash 4 values are sufficiently accurate for "close-enough" applications such as graphics display but are not accurate enough for critical financial or engineering calculations. Note that the trigonometric functions require angles to be measured in radians whereas Flash's MovieClip._rotation property is measured in degrees. There are 2 radians in a circle (1 radian is approximately 57.3 degrees). To convert from radians to degrees, use the formula: degrees = (radians / Math.PI) * 180; To convert from degrees to radians, use the formula: radians = (degrees / 180) * Math.PI; See AlsoMath.atan2( ), Math.cos( ); Section 4.1, "The Number Type" in Chapter 4, "Primitive Datatypes"
AvailabilityFlash 5; may be used when exporting Flash 4 movies SynopsisMath.abs(x) Arguments
ReturnsThe absolute value of x (a positive number of magnitude x). DescriptionThe abs( ) method calculates the distance between x and (also known as the absolute value of x). It leaves positive numbers unchanged and converts negative numbers into positive numbers of the same magnitude. It is useful for calculating the difference between two numbers without regard to which is larger than the other. For example, it is useful when calculating the distance between two points because distances are always positive. ExampleMath.abs(-5); // Returns 5 // Calculate the difference between two numbers function diff (num1, num2) { return Math.abs(num1-num2); } diff(-5, 5); // Returns 10
AvailabilityFlash 5; may be used when exporting Flash 4 movies SynopsisMath.acos(x) Arguments
ReturnsThe angle, in radians, whose cosine is x . If x is not in the range -1.0 to 1.0, returns NaN. DescriptionThe arc cosine function (sometimes written as cos-1) is the inverse of the cosine function. It returns the angle whose cosine has the specified value, in radians. The return value is in the range to (i.e., to 3.14159...). Exampletrace (Math.acos(1.0)); // Displays: 0 trace (Math.acos(0.0)); // Displays: 1.5707... (i.e., pi/2) See AlsoMath.asin( ), Math.atan( ), Math.cos( )
AvailabilityFlash 5; may be used when exporting Flash 4 movies SynopsisMath.asin(x) Arguments
ReturnsThe angle, in radians, whose sine is x . If x is not in the range -1.0 to 1.0, returns NaN. DescriptionThe arc sine function (sometimes written as sin-1) is the inverse of the sine function. It returns the angle whose sine has the specified value, in radians. The return value is in the range -/2 to /2 radians. Exampletrace (Math.asin(1.0)); // Displays: 1.5707... (i.e., pi/2) trace (Math.asin(0.0)); // Displays: 0 See AlsoMath.acos, Math.atan, Math.sin
AvailabilityFlash 5; may be used when exporting Flash 4 movies SynopsisMath.atan(x) Arguments
ReturnsThe angle, in radians, whose tangent is x . DescriptionThe arc tan function (sometimes written as tan-1) is the inverse of the tangent function. It returns the angle whose tangent has the specified value, in radians. The return value is in the range -/2 to /2. Exampletrace (Math.atan(1.0)); // Displays: 0.78539... trace (Math.atan(0.0)); // Displays: 0 trace (Math.atan(-Infinity)); // Displays: -1.5707... (i.e., -pi/2) See AlsoMath.acos( ), Math.asin( ), Math.tan( )
AvailabilityFlash 5; may be used when exporting Flash 4 movies SynopsisMath.atan2(y, x) Arguments
ReturnsThe angle, in radians, of the point (x, y) from the center of a circle, measured counterclockwise from the circle's positive horizontal axis (i.e., the X-axis). Ranges from to -. (Negative values indicate angles below the X-axis). DescriptionThe atan2() method, like atan( ), performs an arc tangent calculation but uses x- and y-coordinates, rather than their ratio, as arguments. That is, calculating an arc tangent with atan2( ) as: Math.atan2(9, 3); // Yields 1.24904577239825 is equivalent to calculating the arc tangent with atan( ), using the ratio of 9/3 (or 3), as follows: Math.atan(3); // Same thing UsageNote that the y -coordinate is passed as the first argument to atan2( ), whereas the x-coordinate is passed as the second argument. This is intentional and required. It mirrors the structure of tangent, which is the ratio of the side opposite an angle (y) divided by the side adjacent to the angle (x). ExampleThe atan2( ) method can be used to make a movie clip point toward a moving target. The following example, available at the online Code Depot, shows code that rotates the current clip toward the mouse pointer. It can be used to orient an enemy spaceship toward a player's spaceship: // Rotate movie clip toward mouse onClipEvent (load) { // Convert radians to degrees. There are 2*pi radians per 360 degrees. function radiansToDegrees(radians) { return (radians/Math.PI) * 180; } } onClipEvent (enterFrame) { // Create a point object that stores the x- and y- coordinates of // this clip relative to its parent's registration point point = {x:_x, y:_y}; // Convert our local (parent) coordinates to global (Stage) coordinates _parent.localToGlobal(point); // Measure the distance between the registration // point of this clip and the mouse deltaX = _root._xmouse - point.x; deltaY = _root._ymouse - point.y; // Calculate the angle of the line from the registration point // of this clip to the mouse rotationRadian = Math.atan2(deltaY, deltaX); // Convert the radian version of the angle to degrees rotationAngle = radiansToDegrees(rotationRadian); // See earlier function // Update the rotation of this clip to point to the mouse this._rotation = rotationAngle; }
AvailabilityFlash 5; may be used when exporting Flash 4 movies SynopsisMath.ceil(x) Arguments
ReturnsThe next integer greater than or equal to x. DescriptionThe ceil( ) (i.e., ceiling) method converts a floating-point number to the first integer greater than or equal to x. ExampleMath.ceil(1.00001); // Returns 2 Math.ceil(5.5); // Returns 6 Math.ceil(-5.5); // Returns -5 See AlsoMath.floor( ), Math.round( )
AvailabilityFlash 5; may be used when exporting Flash 4 movies SynopsisMath.cos(theta) Arguments
ReturnsThe cosine of theta (the result is in the range -1.0 to 1.0). DescriptionThe cos( ) function returns the trigonometric cosine of an angle. In a right triangle, the cosine of an angle is the result of dividing the length of the side adjacent to the angle by the triangle's hypotenuse. UsageNote that cos( ) expects angles to be provided in radians, not degrees. Exampletrace (cos(0)); // Displays: 1.0 trace (cos(Math.PI)); // Displays: -1.0 The cos( ) function can be used along with sin( ) to calculate a point on a circle, which we use in the following example to move a movie clip in a circular path. Given the radius of a circle, r, and an angle, , measured counterclockwise from the positive horizontal axis, a point's location is (r*cos, r*sin): // CODE ON FRAME 1 var radius = 100; // Radius of circle path var centerX = 275; // Horizontal center of circle path var centerY = 200; // Vertical center of circle path var rotAngleDeg = 0; // Angle of object in degrees, measured // counterclockwise from the horizon (x-axis) var rotAngRad; // Radian version of rotAngleDeg // Convert degrees to radians. There are 2*pi radians per 360 degrees. function degreesToRadians(degrees) { return (degrees/180) * Math.PI; } // CODE ON FRAME 2 // Increase the rotation angle by 5 degrees rotAngleDeg += 5; // Place the object. Note that Flash inverts the Y-axis of Cartesian coordinates // so we decrement y to obtain our new location rotAngRad= degreesToRadians(rotAngleDeg); ball._x = centerX + Math.cos(rotAngRad) * radius; ball._y = centerY - Math.sin(rotAngRad) * radius; // CODE ON FRAME 3 // Go back to frame 2 where we move the ball again gotoAndPlay(2); See AlsoMath.acos( ), Math.sin( ), Math.tan( )
AvailabilityFlash 5; may be used when exporting Flash 4 movies SynopsisMath.E DescriptionThe E property stores an approximation of the natural logarithmic base (roughly 2.71828), which in mathematics is represented by the symbol e. It is a transcendental number like , used in mathematical equations involving growth or change. Don't confuse it with the E that is used for exponential notation as described in Section 4.3.2, "Floating-Point Literals" in Chapter 4, "Primitive Datatypes". The two are unrelated. See AlsoMath.log( ), Math.LN10( ), Math.LN2( )
AvailabilityFlash 5; may be used when exporting Flash 4 movies SynopsisMath.exp(x) Arguments
ReturnsMath.E to the power x .
AvailabilityFlash 5; may be used when exporting Flash 4 movies SynopsisMath.floor(x) Arguments
ReturnsThe closest integer less than or equal to x. DescriptionThe floor method converts a floating-point number to the first integer less than or equal to x . ExampleMath.floor(1.99999); // Returns 1 Math.floor(5.5); // Returns 5 Math.floor(-5.5); // Returns -6 function minutesToHHMM (minutes) { var hours = Math.floor(minutes/60); minutes -= hours * 60; minutes = minutes < 10 ? "0" + minutes : minutes; return hours + ":" + minutes; } See AlsoMath.ceil( ), Math.round( )
AvailabilityFlash 5; may be used when exporting Flash 4 movies SynopsisMath.LN10 DescriptionThe LN10 property represents the natural logarithm of 10 (the base-e logarithm of 10), a constant equaling approximately 2.30259.
AvailabilityFlash 5; may be used when exporting Flash 4 movies SynopsisMath.LN2 DescriptionThe LN2 property represents the natural logarithm of 2 (the base-e logarithm of 2), a constant equaling approximately 0.69315
AvailabilityFlash 5; may be used when exporting Flash 4 movies SynopsisMath.log(x) Arguments
ReturnsThe natural logarithm of x . DescriptionThe log( ) method calculates the natural logarithm (i.e., the base-e logarithm) of a number. See the following example to calculate the base-10 logarithm. Exampletrace (Math.log(Math.E)); // Displays: 1 // Compute the base-10 logarithm of a number function log10 (x) { return (Math.log(x) / Math.log(10)); }
AvailabilityFlash 5; may be used when exporting Flash 4 movies SynopsisMath.LOG10E DescriptionThe LOG10E property represents the common logarithm of e (the base-10 logarithm of e), a constant equaling approximately 0.43429.
AvailabilityFlash 5; may be used when exporting Flash 4 movies SynopsisMath.LOG2E DescriptionThe LOG2E property represents the base-2 logarithm of e (log2e), a constant equaling approximately 1.44270. BugsIn Flash 5r30, LOG2E erroneously returns the value of LN2 (0.69315).
AvailabilityFlash 5; may be used when exporting Flash 4 movies SynopsisMath.max(x, y) Arguments
ReturnsThe larger of x and y. ExampleMath.max(5, 1); // Returns 5 Math.max(-6, -5); // Returns -5 This example constrains a value to the specified range: function constrainToRange (checkVal, minVal, maxVal) { return Math.min(Math.max(checkVal, minVal), maxVal); } // Constrain the slider to the stage area mySlider._x = constainToRange (mySlider._x, 0, 550); This example returns the maximum value in an array: function maxInArray (checkArray) { maxVal = -Number.MAX_VALUE; // Initialize maxVal to a very small number for (var i = 0; i < checkArray.length; i++) { maxVal = Math.max(checkArray[i], maxVal); } return maxVal; } trace(maxInArray([2,3,66,4,342,-90,0])); // Displays: 342 See AlsoMath.min( )
AvailabilityFlash 5; may be used when exporting Flash 4 movies SynopsisMath.min(x, y) Arguments
ReturnsThe smaller of x and y. ExampleMath.min(5, 1); // Returns 1 Math.min(-6, -5); // Returns -6 Reader Exercise: Modify the example under Math.max( ) to return the minimum value in an array rather than the maximum. See AlsoMath.max( )
AvailabilityFlash 5; may be used when exporting Flash 4 movies SynopsisMath.PI DescriptionThe PI property represents the constant , the ratio of the circumference of a circle to its diameter. ExampleMath.PI is most famously used in calculating the area of a circle: function circleArea (radius) { // PI times the radius squared could also be // written as Math.PI * Math.pow(radius, 2) return Math.PI * (radius * radius); }
AvailabilityFlash 5; may be used when exporting Flash 4 movies SynopsisMath.pow(base, exponent) Arguments
ReturnsThe base raised to the power exponent. DescriptionThe pow( ) method can be used to raise any number to any power. If exponent is negative, pow( ) returns 1 / (baseabs(exponent)). If exponent is a fraction, pow( ) can be used to take, say, the square root or cube root of a number (in which case it returns the positive root, although, mathematically, there may also be a negative root). ExampleMath.pow(5, 2); // Returns 25 (5 squared) Math.pow(5, 3); // Returns 125 (5 cubed) Math.pow(5, -2); // Returns 0.04 (1 divided by 25) Math.pow(8, 1/3); // Returns 2 (cube root of 8) Math.pow(9, 1/2); // Returns 3 (square root of 9) Math.pow(10, 6); // Returns 1000000 (can also be written as 1e6) BugsBuild 30 of the Flash 5 Player did not correctly calculate Math.pow( ) for negative values of base. For example, Math.pow(-2, 2) was calculated as NaN whereas it should be 4. See AlsoMath.exp( ), Math.sqrt( ), Math.SQRT2, Math.SQRT1_2
AvailabilityFlash 5; may be used when exporting Flash 4 movies SynopsisMath.random() ReturnsA floating-point number greater than or equal to 0.0 and less than 1.0. DescriptionThe random( ) method provides a way to produce random numbers, which can be used to choose randomly between actions in a script. The random( ) method generates a random value between 0 and .99999... inclusive, which we can scale according to our needs. For example, to obtain a random number between 0 and 5, we use: Math.floor(Math.random( ) * 6) And to obtain a random number between 1 and 6, we use: Math.floor(Math.random( ) * 6) + 1 This custom function returns an integer number in a specified range rather than a floating-point number in the range 0 to 1: // Returns a number in the range minVal to maxVal, inclusive function myRandom (minVal, maxVal) { return minVal + Math.floor(Math.random( ) * (maxVal + 1 - minVal)); } // Invoke the function dieRoll = myRandom(1, 6); // Emulates a six-sided die trace(dieRoll); // Note that to simulate two dice, you can use this: twoDice = myRandom(2, 12); // The minimum value is 2, not 1 // To return the die values separately, use an array function rollTwoDice ( ) { return [myRandom(1, 6), myRandom(1, 6)]; } Due to a bug in Build 30 of the Flash 5 Player, this approach is prone to an extremely rare, but potentially important inaccuracy. In Build 30, random( ) generates values in the range 0.0 to 1.0, inclusive. When we multiply the return of random( ) by an integer, n, we produce values in the range 0.0 to n. In our example, we multiplied Math.random( ) by 6, so that the returned value ranges from 0.0 to 6.0. By invoking floor( ) on the adjusted value, we produce integers in the range to n (0 to 6 in our example). This leads to an inaccurate distribution of random numbers -- the chance of producing n is much smaller than the chance of producing any other number in the series. The following version of the myRandom( ) function avoids the problem by simply discarding the value 1.0 if it happens to be chosen by Math.random( ): // Returns an integer in the range minVal to maxVal, inclusive function myRandom (minVal, maxVal) { do { r = Math.random( ); // Keep picking a number until it is not 1. } while (r == 1); return minVal + Math.floor(r * (maxVal + 1 - minVal)); } // Invoke the function dieRoll = myRandom(1, 6); // Emulates a six-sided die safely in Build 30 // of the Flash 5 Player UsageMath.random( ) replaces the deprecated Flash 4 random function. ExampleMath.random( ) is often used to cause the playhead to jump to a random frame in the timeline. The following code invokes the myRandom( ) function from the preceding example and then sends the playhead to the randomly chosen frame: // Invoke the function; pick a random number between 10 and 20 var destinationFrame = myRandom(10, 20); // Now send the playhead to that frame gotoAndStop(destinationFrame);
AvailabilityFlash 5; may be used when exporting Flash 4 movies SynopsisMath.round(x) Arguments
ReturnsThe integer mathematically closest to x (or x itself, if x is an integer). If the fractional component of x is exactly 0.5 (x is equidistant from the two closest integers), round( ) returns the first integer greater than x. DescriptionThe round( ) method performs traditional rounding; it converts a floating-point number to the nearest integer. Positive numbers with a fractional portion less than 0.5 and negative numbers with a fractional portion greater than 0.5 are rounded down. Positive numbers with a fractional portion greater than or equal to 0.5 and negative numbers with a fractional portion less than or equal to 0.5 are rounded up. ExampleMath.round(1.4); // Returns 1 Math.round(1.5); // Returns 2 Math.round(1.6); // Returns 2 Math.round(-5.4); // Returns -5 Math.round(-5.5); // Returns -5 Math.round(-5.6); // Returns -6 See Alsoint( ), Math.ceil( ), Math.floor( )
AvailabilityFlash 5; may be used when exporting Flash 4 movies SynopsisMath.sin(theta) Arguments
ReturnsThe sine of theta (the result is in the range -1.0 to 1.0). DescriptionThe sin( ) method returns the trigonometric sine of an angle. In a right triangle, the sine of an angle is the result of dividing the length of the side opposite the angle by the triangle's hypotenuse. UsageNote that sin( ) expects angles to be provided in radians, not degrees. Exampletrace (Math.sin(0)); // Displays: 0 trace (Math.sin(Math.PI/2)); // Displays: 1.0 The sin( ) function can be used along with cos( ) to calculate a point on a circle. See the example under Math.cos( ). See AlsoMath.asin( ), Math.cos( ), Math.tan( )
AvailabilityFlash 5; may be used when exporting Flash 4 movies SynopsisMath.sqrt(x) Arguments
ReturnsThe square root of x, or NaN if x is less than 0. DescriptionThe sqrt( ) method returns the positive root of its operand (even though there may also be a mathematically valid negative root). It is equivalent to: Math.pow(x, 0.5) ExampleMath.sqrt(4); // Returns 2, although -2 is also a valid root Math.sqrt(36); // Returns 6, although -6 is also a valid root Math.sqrt(-20); // Returns NaN See AlsoMath.pow( ), Math.SQRT2, Math.SQRT1_2
AvailabilityFlash 5; may be used when exporting Flash 4 movies SynopsisMath.SQRT1_2 DescriptionThe SQRT1_2 property is a constant approximating the value 1/Math.SQRT2 (the reciprocal of the square root of 2), equaling approximately 0.70711. See AlsoMath.SQRT2
AvailabilityFlash 5; may be used when exporting Flash 4 movies SynopsisMath.SQRT2 DescriptionThe SQRT2 property is a constant approximating the square root of 2, an irrational number, equaling approximately 1.41421. See AlsoMath.SQRT1_2
AvailabilityFlash 5; may be used when exporting Flash 4 movies SynopsisMath.tan(theta) Arguments
ReturnsThe tangent of theta (the result is in the range -Infinity to Infinity). DescriptionThe tan( ) method returns the trigonometric tangent of an angle. In a right triangle, the tangent of an angle is the result of dividing the length of the side opposite the angle by the length of the side adjacent to the angle. This is also the same as the ratio Math.sin(theta)/Math.cos(theta), so as cos(theta) approaches zero, tan(theta) approaches Infinity. Therefore, tan(theta) is not calculable for the values -/2, /2, -3/2, 3/2, etc. Exampletrace (Math.tan(0)); // Displays: 0 trace (Math.tan(Math.PI/4)); // Displays: 1 See AlsoMath.atan( ), Math.cos( ), Math.sin( )
AvailabilityFlash 4 and later SynopsistextField.maxscroll ReturnsA positive integer representing the line number of the last legal top line of a text field. DescriptionThe maxscroll property tells us the largest allowed scroll value for a text field. It represents the number of the last line in a text field that may be used as the top line in its viewable region. The maxscroll property can be used with the scroll property to manage a scrolling-text field. See Alsoscroll; Section 18.4.2, "The maxscroll Property" in Chapter 18, "On-Screen Text Fields"
AvailabilityFlash 5 SynopsisMouse.methodName Methods
DescriptionThe Mouse object has only two methods and no properties. We use Mouse.hide( ) to conceal the system mouse pointer, usually in order to replace it with a customized mouse pointer as shown later. It may also be desirable to hide the mouse pointer in fullscreen, keyboard-controlled movies or for touch-screen kiosks. Note that the Mouse object does not tell us the location of the mouse pointer. That information is stored in the _xmouse and _ ymouse properties of each movie clip object. Use _root._xmouse and _root._ ymouse to determine the mouse pointer's location on the main Stage. See AlsoMovieClip._xmouse, MovieClip._ ymouse
AvailabilityFlash 5 SynopsisMouse.hide() DescriptionThe hide( ) method causes the normal mouse pointer (usually an arrow) to disappear when the mouse is over any part of the Player. The normal system pointer reappears when the mouse passes outside the Flash Player's active stage area. UsageNote that in Flash 5, even after Mouse.hide( ) has been invoked, the normal system text I-beam cursor will appear when the mouse hovers over a text field. ExampleThe hide( ) method is used to conceal the default system mouse pointer, typically in order to replace it with a custom pointer. In Flash, a custom pointer is nothing more than a movie clip that follows the mouse. Using the mouseMove event, we can cause a movie clip to follow the mouse by updating the clip's _x and _ y properties with each passing frame. The following code demonstrates the technique: // Code on the clip that acts as the custom pointer onClipEvent (load) { Mouse.hide( ); } onClipEvent (mouseMove) { _x = _root._xmouse; _y = _root._ymouse; updateAfterEvent( ); } It may also be desirable to hide the custom pointer when the mouse is inactive, say, because the pointer has left the Flash Player's active stage area, in which case the system pointer appears and there are two pointers on screen. The following code shows how to adapt the previous code to hide the cursor after 5 seconds of inactivity: onClipEvent (load) { Mouse.hide( ); } onClipEvent (enterFrame) { if (getTimer( ) - lastMove > 5000) { _visible = false; } else { _visible = true; } } onClipEvent (mouseMove) { _x = _root._xmouse; _y = _root._ymouse; lastMove = getTimer( ); updateAfterEvent( ); } To change a custom pointer to a custom "hand" icon when the mouse hovers over a button, use the button's rollOver event to set the custom pointer clip to a frame containing the custom hand, and use the rollOut event to set the custom pointer back to the default, as follows: on (rollOver) { _root.customPointer.gotoAndStop("hand"); } on (rollOut) { _root.customPointer.gotoAndStop("default"); } In all cases, remember to place the custom pointer on the top layer of your movie so it appears above all other content. Alternatively, use duplicateMovieClip( ) or attachMovie( ) to dynamically generate the custom pointer clip and assign it a very high depth. See Also
AvailabilityFlash 5 SynopsisMouse.show() DescriptionThe show( ) method causes the default system mouse pointer to reappear after Mouse.hide( ) has been invoked. It can be used to provide a normal pointer at necessary times in a movie, such as when the user is expected to fill in a form. This is one way to handle the unfortunate appearance of the text I-beam when the system pointer is hidden. See AlsoMouse.hide( )
AvailabilityFlash 3 and later ConstructorNone. Movie clip symbols are created manually in the Flash authoring tool. Movie clip instances can be created with attachMovie( ) and duplicateMovieClip(). PropertiesMovie clip properties provide descriptions of, and control over, various physical features of movie clips and main movies. Properties are accessed using the dot operator, as with any object. See Section 13.1, "The "Objectness" of Movie Clips" in Chapter 13, "Movie Clips", for details on using movie clip properties. Two property-related issues to note:
Table 20-9 lists the movie clip properties. Note that all built-in movie clip properties begin with an underscore. This make them easy to distinguish from custom properties that you can add to your movie clip and which by convention should not begin with an underscore. In the Access column of Table 20-9, R/W indicates that a property's value may be both retrieved and set (i.e., read/write), and RO indicates that it can be retrieved but not set (i.e., read-only). Some read-only properties can sometimes be set indirectly through the authoring tool or via some related function (e.g., gotoAndStop( ) sets the _currentframe property), but only read/write properties can be set directly via ActionScript. The Type column describes the datatype of each property's value. The Property Description column gives a quick summary of the property's purpose, but the full descriptions that follow later provide important details. With the exception of the _name and _parent properties, the properties in Table 20-9 apply to both movie clip instances and the main movie (i.e., _root). However, a property's value may differ markedly depending on whether it is checked from a movie clip instance or the main movie and may also differ depending on where the clip is attached. For example, a movie clip's _x property differs depending on whether it is attached to the main timeline or as a child of a parent clip. Furthermore, all properties of the current timeline may be accessed without an explicit reference to it, as in _alpha versus myClip._alpha. Table 20-9. Movie Clip Property Summary
*Applies to movie clip instances; does not apply to the main timeline. MethodsMovie clip methods may be invoked on any movie clip instance and, in most cases, on any main movie timeline. Many of the movie clip methods provide the same functionality as analogous global functions but simply use the convenient MovieClip.method( ) dot syntax format. Those that do not correspond to a global function may be applied to the current clip without an explicit reference to it, as in attachMovie( ) versus myClip.attachMovie( ). Table 20-10 lists the movie clip methods. Table 20-10. Movie Clip Method Summary
*Applies to movie clip instances; does not apply to the main timeline. EventsMovie clip instances support event handlers, which respond automatically to a predefined set of events (e.g., mouse or keyboard interaction or movie playback). The supported movie clip event handlers are listed in Table 20-11. See Chapter 10, "Events and Event Handlers", for details on each. Table 20-11. Movie Clip Event Handler Summary
DescriptionMovieClip is not actually a class in ActionScript but rather a unique ActionScript datatype used to represent information about, and allow control of, movies and movie clips. For most purposes, we treat movie clips and movies as objects; we may create and access movie clip properties, and we may create and invoke movie clip methods. Because MovieClip is not a true class, we do not use a constructor to create new MovieClip instances. Instead, we create movie clip symbols in the authoring tool and place instances on the Stage manually. Some methods, however, allow us to copy existing clips (duplicateMovieClip( )), or add new clips to the Stage programmatically (attachMovie( )). Not all MovieClip objects are equal; some MovieClip methods and properties apply only to movie clip instances, not to main movies (a main movie is the _root timeline of a .swf document). In our consideration of the MovieClip properties and methods, we'll note cases in which functionality is limited to one type of MovieClip object. Note that we use the word MovieClip to refer to the "class" of the objects, and the word movieclip (lowercase) to refer to the ActionScript datatype; we use movie clip, clip, or instance to refer to a particular movie clip, and we use movie to refer to the main movie of a .swf file. In the synopsis for each detailed property and method entry, the abbreviation mc stands in for the name of a clip or main movie. For many properties and methods, mc is optional -- if omitted, the current timeline is used. Throughout this MovieClip section, when talking about coordinates, we need to refer to the location of movie clips. We measure the position of a clip in reference to one representative point, its so-called registration point , as marked by a crosshair in the clip's Library symbol. When a clip resides on the main Stage, we describe its location relative to the top-left corner of the Stage, which corresponds to the point (0,0). When a clip resides within another clip, we describe its location relative to the registration point of the parent clip, which again corresponds to the point (0,0). The point (0,0) in both cases is the origin point (or simply origin) of the coordinate space being used to plot the location of the clip. We'll see how the localToGlobal( ) and globalToLocal( ) methods can convert between these two coordinate spaces.
We'll often use the coordinate-related properties and methods to move a clip, determine where a clip is, or determine whether it intersects another object or point. The last technique is referred to as collision detection because it is often used to determine whether to change the direction in which a clip is animating, as if it bounced off another object (see the MovieClip.hitTest( ) method). Note that ActionScript doesn't have a native datatype to represent a point (i.e., an x- and y- coordinate). See MovieClip.globalToLocal( ) for an explanation of how to create a point object from a generic object. See AlsoFor a full consideration of the MovieClip class, see Chapter 13, "Movie Clips"
AvailabilityFlash 4 and later Synopsismc._alpha AccessRead/write DescriptionThe floating-point _alpha property specifies the opacity (or conversely the transparency) of mc as a percentage -- 0 is completely transparent whereas 100 is completely opaque. Setting the _alpha of mc affects the visual transparency of all clips nested inside mc but does not affect their _alpha properties. That is, if we have a clip, square, that contains another clip, circle, and we set square._alpha to 50, then circle will be 50% transparent on-screen but will have an _alpha of 100. UsageNote that setting the _alpha of a movie clip affects the aa property of the object returned by Color.getTransform( ). Exampleball._alpha = 60; // Make ball partially transparent ball._alpha = 0; // Make ball invisible The following clip event handler makes a clip more transparent as the mouse moves down on the screen: onClipEvent(enterFrame) { _alpha = 100 - (_root._ymouse / 400) * 100; } See AlsoThe Color Class; MovieClip._visible
AvailabilityFlash 5 Synopsismc.attachMovie(symbolIdentifier, newName, depth) Arguments
DescriptionThe attachMovie( ) method creates a new instance called newName based on the exported movie clip symbol specified by symbolIdentifier. If mc is the main movie, the new instance is placed in the top-left corner of the Stage. If mc is a movie clip instance, the new instance is placed on mc's registration point. In either case, the new instance is placed above mc in a stack of programmatically-generated clips. See AlsoduplicateMovieClip( ), MovieClip.duplicateMovieClip( ); Section 13.3.2.3, "Creating instances with attachMovie( )" and Section 13.4.2.1, "How clips generated via attachMovie( ) are added to the stack" in Chapter 13, "Movie Clips"
AvailabilityFlash 4 and later Synopsismc._currentframe AccessRead-only DescriptionThe integer _currentframe property represents the frame number at which the playhead of mc currently resides. Note that the first frame is 1, not 0; therefore, _currentframe ranges from 1 to mc._totalframes. Example// Send a playhead back two frames from its current location gotoAndStop(_currentframe - 2); See AlsoMovieClip.gotoAndPlay( ), MovieClip.gotoAndStop( )
AvailabilityFlash 4 and later Synopsismc._droptarget AccessRead-only DescriptionIf mc is being dragged, _droptarget stores a string indicating the path to the clip over which mc hovers (if any). If mc is not hovering over a clip, _droptarget stores undefined. If mc was previously dragged and then dropped on a clip, _droptarget stores a string indicating the path to the clip upon which mc was dropped. The path is provided in slash notation. A movie clip is considered to be "over" another clip if the registration point of the dragged clip overlaps any portion of the target clip. ExampleThe _droptarget property is convenient for creating drag-and-drop interfaces. The following example demonstrates how to create a simple shopping-basket interface using _droptarget (when an item clip is dropped onto the basket clip, the item is allowed to stay in the basket; otherwise, the item is returned to its original location): // CODE ON FRAME ONE OF item var origX = _x; var origY = _y; function drag( ) { this.startDrag( ); } function drop( ) { stopDrag( ); if (_droptarget != "/basket") { _x = origX; _y = origY; } } // CODE ON A BUTTON IN item on (press) { drag( ); } on (release) { drop( ); } Note that _droptarget stores a string, not a clip reference. To convert a _droptarget string to a movie clip reference, use the technique shown in the example for eval( ). See AlsoMovieClip.startDrag( ), MovieClip.stopDrag( )
AvailabilityMethod form introduced in Flash 5 (global form introduced in Flash 4) Synopsismc.duplicateMovieClip(newName, depth) Arguments
DescriptionThe MovieClip.duplicateMovieClip( ) method is an alternative to the global duplicateMovieClip( ) function. When invoked as a MovieClip method, duplicateMovieClip( ) takes no target parameter -- it duplicates mc. The method syntax is less prone to user error than its global function counterpart. For usage instructions, see the global duplicateMovieClip( ) function. See AlsoMovieClip.attachMovie( ), duplicateMovieClip( )
AvailabilityFlash 4 and later Synopsismc._framesloaded AccessRead-only DescriptionThe integer _framesloaded property indicates how many frames of mc have been loaded into the Player (from to mc._totalframes). It is normally used to create preloaders that pause playback until a sufficient number of frames have downloaded. For a movie clip, the _framesloaded property always equals _totalframes (because clips are loaded in their entirety before playing) unless the instance is in the process of loading an external .swf file due to a loadMovie( ) invocation. The _framesloaded property is, therefore, useful only with main movies or external .swf files loading into instances or levels. Preloader code is traditionally placed directly on the main timeline of the movie being preloaded. A simple approach is to loop between frames 1 and 2 until the movie has loaded, at which point we go to the movie's start frame. For example: // CODE ON FRAME 1 if (_framesloaded > 0 && _framesloaded == _totalframes) { gotoAndPlay("beginMovie"); } // CODE ON FRAME 2 gotoAndPlay(1); In Flash 5 and later, we may alternatively use the enterFrame movie clip event handler to build a more portable preloader. In the movie we wish to preload, at the frame where we want preloading to start, we invoke the stop( ) function. Then we place a movie clip with the following code on that movie's timeline: onClipEvent (enterFrame) { loaded = _parent._framesloaded; if (loaded > 0 && loaded == _parent._totalframes && loading != "done") { _parent.gotoAndPlay("beginMovie"); loading = "done"; } } In the preceding example, the clip tracks its parent's load progress and starts its parent playing when loading is finished. By using a movie clip as a preloader, we circumvent the need for a loop on the preloading movie's timeline. A movie clip preloader could even be turned into a Smart Clip, providing easier workflow for less experienced developers. Notice that in our preloader examples, we checked whether _framesloaded > 0 in addition to whether _framesloaded == _totalframes. This is necessary because when a movie is unloaded from a clip, that clip has a _totalframes of 0. Hence, if _framesloaded is (as it might be on a very slow connection), the comparison _framesloaded == _totalframes can return true even when no frames have yet loaded. Our check prevents the movie from skipping ahead before the appropriate content has loaded. This precaution is not necessary with main movie preloaders for .swf files loaded onto levels, because their _totalframes property is never zero. ExamplePreloaders often include a horizontal loading bar and a text field indicating the percentage of a movie that has downloaded. Loading bars are implemented as clips sized with either the _width property or the _xscale property. However, note that a clip scales about its registration point (proportionately on the right and left sides of the clip's registration point). Therefore, to size a clip from one side only, we must place all of the clip's content on one side of the registration point in the clip's symbol. The following example shows how to add a loading bar and a status text field to our earlier clip handler code: // A Portable Preloader with a Status Bar onClipEvent (enterFrame) { // Measure how many frames have loaded loaded = _parent._framesloaded; // If all the frames have finished loading... if (loaded > 0 && loaded == _parent._totalframes && loading != "done") { // ...play the movie and make a note that we're done loading _parent.gotoAndPlay("beginMovie"); loading = "done"; } // Determine the percentage of bytes that have loaded percentDone = Math.floor((_parent.getBytesLoaded( ) / _parent.getBytesTotal( )) * 100); // Display the percentage of loaded bytes in the text field loadStatus loadStatus = percentDone + "% complete"; // Set the size of our loadBar clip loadBar._xscale = percentDone; } Use the Bandwidth Profiler in Test Movie mode to simulate movie download for preloader testing. See AlsoMovieClip.getBytesLoaded( ), MovieClip._totalframes; Section 10.10.4, "data" in Chapter 10, "Events and Event Handlers", and Section 19.1.4, "The Bandwidth Profiler" in Chapter 19, "Debugging"
AvailabilityFlash 5 Synopsismc.getBounds(targetCoordinateSpace) Arguments
ReturnsAn object whose properties -- xMin, xMax, yMin, yMax -- describe the bounding box of the space occupied by mc. These four properties of the object respectfully specify the leftmost, rightmost, topmost, and bottommost pixel coordinates of mc. DescriptionThe getBounds( ) method returns an anonymous object with properties that define the rectangular area occupied by mc (i.e., mc 's bounding box). To retrieve the values stored in the returned object, we must access that object's properties as shown in the next example. The dimensions of the bounding box of a clip may be measured relative to any other clip or movie. Using the targetCoordinateSpace argument, we may pose the question, "If mc resided on targetCoordinateSpace's canvas, what area would it occupy?" The answer will be different depending on whether targetCoordinateSpace is a main movie or a clip instance; the origin point of the main movie's coordinate space is the top-left corner of the Stage, but the origin point of an instance's coordinate space is its registration point as marked in the clip's Library symbol (shown as a crosshair). The getBounds( ) method can be used to perform basic collision detection between a movie or clip and some other point (though MovieClip.hitTest( ) serves this purpose better). It might also be used to identify a rectangular region in which to place a clip added to a movie with MovieClip.attachMovie( ). Examplevar clipBounds = this.getBounds( ); var leftX = clipBounds.xMin; var rightX = clipBounds.xMax; var topY = clipBounds.yMin; var bottomY = clipBounds.yMax; See AlsoMovieClip.hitTest( )
AvailabilityFlash 5 Synopsismc.getBytesLoaded() ReturnsAn integer representing the number of bytes of mc that have finished downloading to the Player. (Divide by 1024 to convert to kilobytes.) DescriptionThe getBytesLoaded( ) method tells us the number of bytes of a movie that have downloaded into the Flash Player. However, getBytesLoaded( ) measures bytes in whole-frame chunks only. So if a movie's first frame is 200 bytes in size and its second frame is 3000 bytes in size, getBytesLoaded( ) will return 200 and 3200 but never any increment in between. Until all of a given frame has downloaded, the return value of getBytesLoaded( ) does not change. The getBytesLoaded( ) method may, therefore, be thought of as a "bytes version" of the _framesloaded property. Note that internal movie clips are always entirely loaded before they are displayed, so the return value of getBytesLoaded( ) on an internal movie clip will always be the same as getBytesTotal( ) (unless the movie clip is currently loading an external .swf file in response to loadMovie( )). Therefore, getBytesLoaded( ) is effective only when used with a main movie or an external .swf file being loaded into an instance or level. Like _framesloaded , getBytesLoaded( ) is normally used to build preloaders. It can be used in concert with getBytesTotal( ) to create a more accurate progress bar than is possible with _framesloaded and _totalframes (because the byte size of each frame may not be equal -- a movie with 10 frames is not 30% loaded when three frames are loaded if the frames differ widely in size). Example// CODE ON FRAME 1 if (_framesloaded > 0 && _framesloaded == _totalframes) { gotoAndPlay("beginMovie"); } else { // Show the load progress in text fields. Divide by 1024 to convert to KB. loadProgressOutput = this.getBytesLoaded( )/1024; loadTotalOutput = this.getBytesTotal( )/1024; } // CODE ON FRAME 2 gotoAndPlay(1); See AlsoMovieClip._framesloaded, MovieClip.getBytesTotal( )
AvailabilityFlash 5 Synopsismc.getBytesTotal() ReturnsAn integer representing the size of mc, in bytes. Divide by 1024 to convert to kilobytes. DescriptionThe getBytesTotal( ) method tells us the size, in bytes, of a clip instance or the main movie. When invoked on the main movie, getBytesTotal( ) reports the size of the entire .swf. It is normally used in concert with getBytesLoaded( ) to produce preloaders for main movies and .swf files loaded into instances or levels. See AlsoMovieClip.getBytesLoaded( ), MovieClip._totalframes
AvailabilityMethod form introduced in Flash 5 (global form supported by Flash 2, enhanced in Flash 4 to include the method argument) Synopsismc.getURL(URL, window, method) Arguments
DescriptionThe MovieClip.getURL( ) method is an alternative to the global getURL( ) function. Its method form is useful only when variables are being sent, in which case getURL( ) sends the variables from mc, which does not have to be the current timeline. See AlsoFor general usage instructions, see the global getURL( ) function.
AvailabilityFlash 5 Synopsismc.globalToLocal(point) Arguments
DescriptionThe globalToLocal( ) method converts the x and y properties of point from coordinates on the main Stage to coordinates in the coordinate space of mc. Note that globalToLocal( ) does not return a new object, it merely modifies the existing x and y values of point. To use globalToLocal( ), we must first create an object with x and y properties. For example: var myPoint = new Object( ); myPoint.x = 10; myPoint.y = 20; The x and y properties of our object are positions on the horizontal and vertical axes of the main Stage, relative to its top-left corner. For example, an x of 10 is 10 pixels to the right of the Stage's left edge, and a y of 20 is 20 pixels below the Stage's top border. With our object created and our x and y properties set, we then pass the object to the globalToLocal( ) method, as in: myClip.globalToLocal(myPoint); When globalToLocal( ) is executed, the values of myPoint's x and y properties are transformed to represent a point in the space of myClip, measured from myClip's registration point. By examining the new values of our myPoint object's properties, we answer the question, "Where does the point (x, y) of the main Stage appear in myClip ?" For example: xInClip = myPoint.x; yInClip = myPoint.y; ExampleThe following example calculates the offset from the upper-left corner of the main Stage to the registration point of the current clip: pt = new Object( ); // Create generic object to hold our point pt.x = 0; // Left border of main Stage pt.y = 0; // Top border of main Stage this.globalToLocal(pt); // Convert pt to local coordinates trace("From the current clip, the top-left corner of the main Stage is at "); trace("x: " + pt.x + "y: " + pt.y); See AlsoMovieClip.localToGlobal( )
AvailabilityMethod form introduced in Flash 5 (global form supported by Flash 2 and later) Synopsismc.gotoAndPlay(frameNumber) mc.gotoAndPlay(frameLabel) Arguments
DescriptionThe MovieClip.gotoAndPlay( ) method is an alternative to the global gotoAndPlay( ) function. Use the method form to control remote movie clips or movies, specified by mc. For general usage instructions, see the global gotoAndPlay( ) function. Example// Send the part1 clip to the label intro, then play part1 part1.gotoAndPlay("intro");
AvailabilityMethod form introduced in Flash 5 (global form supported by Flash 2 and later) Synopsismc.gotoAndStop(frameNumber) mc.gotoAndStop(frameLabel) Arguments
DescriptionThe MovieClip.gotoAndStop( ) method is an alternative to the global gotoAndStop( ) function. Use the method form to control remote movie clips or main movies specified by mc. For general usage instructions, see the global gotoAndStop( ) function. Example// Send the mainMenu clip to frame 6 and stop the playhead there mainMenu.gotoAndStop(6);
AvailabilityFlash 4; enhanced in Flash 5 Synopsismc._height AccessRead-only in Flash 4; read/write in Flash 5 DescriptionThe floating-point _height property is a non-negative number specifying the height of mc, in pixels. If mc has no content, _height is 0. The _height property measures the content of a clip as the distance between the highest occupied pixel and the lowest occupied pixel, even if there is empty space between those pixels. An occupied pixel is a pixel that contains a shape, graphic, button, movie clip, or other content element. Changes made to a clip's height in the authoring tool or via _ yscale are reflected by _height. We may set the value of _height in order to vertically resize a movie clip. Attempts to set _height to a negative value are ignored. Setting a clip's _height to does not make it invisible; rather, the clip becomes a one-pixel horizontal line. The _height of the main movie (either _root._height or _leveln._height) is not the Stage height as specified under Modify Movie Dimensions in the authoring tool but rather the height of the contents of the main movie. There is no explicit Stage height property; if required, we must provide the Stage height manually as a variable. For example, if a movie's Stage has a height of 400, we could add the following variable: _root.stageHeight = 400; To make that value available on the timeline of any clip, use: Object.prototype.stageHeight = 400; UsageNote that when we set the height of a movie clip, lines are scaled proportionally, losing their original point size as set in the Stroke panel. However, the point size of lines set to Hairline in the Stroke panel is not scaled when a movie clip is resized. That is, use hairlines to prevent your strokes from appearing fat or distorted when a clip is scaled. Exampleball._height = 20; // Set the height of ball to 20 pixels ball._height /= 2; // Reduce the height of ball by a factor of 2 See AlsoMovieClip._width, MovieClip._yscale
AvailabilityFlash 5 Synopsismc.hitTest(x, y, shapeFlag) mc.hitTest(target) Arguments
ReturnsA Boolean indicating the result of the collision-detection test. The result is true under any of the following circumstances:
The result is false under any of the following circumstances:
DescriptionThe hitTest( ) method is used to determine whether a movie clip or specific point intersects with (i.e., "hits") mc. When checking to see if a point intersects mc, we provide hitTest( ) with the x and y coordinates of the point to check (relative to the main Stage). We may also provide the optional shapeFlag argument, which indicates whether the collision test should use the actual pixels of mc, or just mc 's bounding box (the smallest rectangle that can encompass every occupied pixel of mc). Checking the actual pixels of mc allows us to determine whether the point (x, y) is an occupied pixel inside the contour of mc, not merely whether it is any point inside mc 's bounding box. When we're checking to see if a movie clip intersects mc, we provide hitTest( ) with the target argument specifying the clip to check. Collision detection between target and mc always uses the bounding boxes of the clips; hitTest( ) does not support pixel-perfect clip-versus-clip detection. Manual pixel-perfect collision-detection routines can be difficult to create and processor-intensive to run. In many situations -- for example, a simple spaceship game -- it's common practice to detect against a bounding circle rather than exact pixels. UsageNote that collision is always tested relative to the location of mc on the main Stage of the Player. Therefore, when hitTest( ) is used with a single point, the arguments x and y should always describe a point using Stage coordinates. See MovieClip.localToGlobal( ) for information on converting clip coordinates to Stage coordinates. In clip-versus-clip detection, the coordinates of clips on different timelines are automatically converted to global (i.e., Stage) coordinates. ExampleThis example shows how to manually detect the intersection of two circles without using hitTest( ): // Check the distance between two circular clips on both axes var deltaX = clip1._x - clip2._x; // Horizontal distance var deltaY = clip1._y - clip2._y; // Vertical distance // Store the radius of each circle in a convenient property var radius1 = clip1._width / 2; var radius2 = clip2._width / 2; // If the distance between the circles' centers squared is less // than or equal to the total length of the two radii squared, // an intersection occurs. if ((deltaX * deltaX) + (deltaY * deltaY) <= (radius1 + radius2) * (radius1 + radius2)) { trace("intersecting"); } else { trace("not intersecting"); } Here we check whether paddle intersects ball using hitTest( ): if (paddle.hitTest("ball")) { trace("The paddle hit the ball."); } Here we check whether the mouse pointer is over an occupied pixel within tractor's contour. Notice that the coordinates of the pointer are given in relation to _root (the main Stage). Gaps in a movie clip are detectable when shapeFlag is true; for example, if the tractor uses empty space to represent its windows, then hitTest( ) will return false when the pointer is over a window: if (tractor.hitTest(_root._xmouse, _root._ymouse, true)) { trace("You're pointing to the tractor."); } See Also
AvailabilityMethod form introduced in Flash 5 (global form supported by Flash 4) Synopsismc.loadMovie(URL) mc.loadMovie(URL, method) Arguments
DescriptionThe MovieClip.loadMovie( ) method is an alternative to the global loadMovie( ) function. When invoked as a MovieClip( ) method, loadMovie( ) takes no target parameter; it loads the .swf at URL into mc. The method syntax is less prone to user error than its global function counterpart. For usage instructions, see the global loadMovie( ) function. See AlsoloadMovie( ); Section 13.8.3.1, "Method versus global function overlap issues" in Chapter 13, "Movie Clips"
AvailabilityMethod form introduced in Flash 5 (global form supported by Flash 4 and later) Synopsismc.loadVariables(URL) mc.loadVariables(URL, method) Arguments
DescriptionThe MovieClip.loadVariables( ) method is an alternative to the global loadVariables( ) function. When invoked as a MovieClip method, loadVariables( ) takes no target parameter; it loads the variables at URL into mc. The method syntax is less prone to user error than its global function counterpart. For usage instructions, see the global loadVariables( ) function. See AlsoloadVariables( ); Section 13.8.3.1, "Method versus global function overlap issues" in Chapter 13, "Movie Clips"
AvailabilityFlash 5 Synopsismc.localToGlobal(point) Arguments
DescriptionThe localToGlobal( ) method converts the x and y properties of point from coordinates given in mc 's coordinate space to coordinates on the main Stage of the Player. Note that localToGlobal( ) does not return a new object, it merely modifies the existing x and y values of point. To use localToGlobal( ), we must first create a so-called point or coordinates object with x and y properties. To do so, we'll simply create a generic object from the Object class, and add x and y properties to it: myPoint = new Object( ); myPoint.x = 10; myPoint.y = 20; The x and y properties of our object are positions on the horizontal and vertical axes of mc, relative to mc 's registration point (shown as a crosshair in mc 's Library symbol). For example, an x of 10 is 10 pixels to the right of mc 's registration point, and a y of 20 is 20 pixels below mc 's registration point. With our object created and our x and y properties set, we then pass the object to the localToGlobal( ) method, as in: myClip.localToGlobal(myPoint); When localToGlobal( ) is executed, the values of myPoint's x and y properties are transformed to represent the corresponding point on the main Stage, measured from the Stage's upper-left corner. By examining the new values of our myPoint object's properties, we answer the question "Where does the point (x, y) of the movie clip appear on the main Stage?" For example: mainX = myPoint.x; mainY = myPoint.y; ExampleThe following example determines the location of a clip's registration point relative to the main Stage: pt = new Object( ); pt.x = 0; // Horizontal registration point of clip pt.y = 0; // Vertical registration point of clip this.localToGlobal(pt); // Convert pt to main Stage coordinates trace("On the main Stage, the registration point of the current clip is at: "); trace("x: " + pt.x + "y: " + pt.y); The localToGlobal( ) method can be used to convert a point to Stage coordinates for use with the hitTest( ) method, which expects points to be supplied in the Stage's coordinate space. It can also be used to compare points in two different movie clips using a common coordinate space. See AlsoMovieClip.globalToLocal( ), MovieClip.hitTest( )
AvailabilityFlash 4 and later Synopsismc._name AccessRead/write DescriptionThe _name property specifies the instance name of a movie clip instance as a string. Because it initially reflects the instance name set in the Instance panel during authoring, the _name property doesn't apply to main movies (the main movie is most easily referred to by the global property _root). ExampleWe can use _name to determine whether or not to perform some manipulation of a given clip, as we did when generating a series of star movie clips in Example 10-2. The _name property may also be used to reassign the identifier of a clip. For example: // Change ball to circle ball._name = "circle"; // Now control the former ball as circle circle._x = 500; See AlsoMovieClip._target, targetPath( ); Section 13.3.3, "Instance Names" in Chapter 13, "Movie Clips"
AvailabilityMethod form introduced in Flash 5 (global form supported by Flash 2 and later) Synopsismc.nextFrame() DescriptionThe MovieClip.nextFrame( ) method is an alternative to the global nextFrame( ) function. Use the method form to control remote movie clips or main movies specified by mc. For general usage instructions, see the global nextFrame( ) function. Example// Advance slideshow one frame and stop the playhead slideshow.nextFrame( ); See AlsoMovieClip.prevFrame( ), nextFrame( )
AvailabilityFlash 4 and later Synopsismc._parent AccessRead-only DescriptionThe _ parent property stores a reference to the clip object upon whose timeline mc resides. Main movies don't support the _ parent property because they are at the top level (conveniently referred to as _root). References to _root._ parent return undefined. The _parent property gives us the powerful ability to manipulate clips in relation to the current clip. BugsThough it is possible in Flash 5 to reassign the _ parent property to another clip, doing so has little purpose -- only the reference is changed, not the physical structure of the clips. This unintentional behavior will likely be changed in the future. ExampleIf mc resides on the main timeline of a movie, we can play the main timeline from mc using: _parent.play( ); We may also set the parent timeline's properties, as in: _parent._alpha = 50; The _ parent property may also be used in succession; that is, we may access the _ parent of a _ parent, as follows: _parent._parent.play( ); // Play the clip two clips above the current clip See Also_root; Section 13.5.3, "Referring to Nested Instances" in Chapter 13, "Movie Clips"
AvailabilityMethod form introduced in Flash 5 (global form supported by Flash 2 and later) Synopsismc.play() DescriptionThe MovieClip.play( ) method is an alternative to the global play( ) function. Use the method form to control remote movie clips or main movies specified by mc. For general usage instructions, see the global play( ) function. Example// Begin playing clip intro intro.play( ); See AlsoMovieClip.stop( ), play( )
AvailabilityMethod form introduced in Flash 5 (global form supported by Flash 2 and later) Synopsismc.prevFrame() DescriptionThe MovieClip.prevFrame( ) method is an alternative to the global prevFrame( ) function. Use the method form to control remote movie clips or main movies specified by mc. For general usage instructions, see the global prevFrame( ) function. Example// Rewind slideshow one frame and stop it slideshow.prevFrame( ); See AlsoMovieClip.nextFrame( ), prevFrame( )
AvailabilityMethod form introduced in Flash 5 (global form supported by Flash 4 and later) Synopsismc.removeMovieClip() DescriptionThe MovieClip.removeMovieClip( ) method is an alternative to the global removeMovieClip( ) function. When invoked as a MovieClip method, removeMovieClip( ) takes no target parameter; it removes mc. The method syntax is less prone to user error than its global function counterpart. For usage instructions, see the global removeMovieClip( ) function. See AlsoduplicateMovieClip( ), MovieClip.attachMovie( ), MovieClip.duplicateMovieClip( ); Section 13.8.3.1, "Method versus global function overlap issues" in Chapter 13, "Movie Clips"
AvailabilityFlash 4 and later Synopsismc._rotation AccessRead/write DescriptionThe floating-point _rotation property specifies the number of degrees mc is rotated from its original orientation (if mc is a clip, the original orientation is that of its symbol in the Library). Both authoring tool and programmatic adjustments are reflected in _rotation. Numbers in the range to 180.0 rotate the clip clockwise. Numbers in the range to -180.0 rotate the clip counter-clockwise. The same effect is achieved when rotating a clip n degrees or n-360 degrees (where n is positive). For example, there is no difference between rotating a clip +299.4 degrees or -60.6 degrees. Likewise, when n is negative, there is no difference between n degrees and n+360 degrees. For example, rotating a clip -90 degrees is the same as rotating it +270 degrees. When _rotation is set to anything outside the range of -180 to 180, the value is brought into the proper range according to the following calculation: x = newRotation % 360; if (x > 180) { x -= 360; } else if (x < -180) { x += 360; } _rotation = x; BugsIn the Flash 4 Player, setting the _rotation of a clip reduces the scale of that clip by a fractional amount. Over many _rotation settings, a clip will actually shrink noticeably. To account for this bug, set the _xscale and _ yscale of the clip to 100 whenever setting the _rotation. ExamplePlacing the following code on a clip causes the clip to rotate 5 degrees clockwise each time a frame is rendered: onClipEvent (enterFrame) { _rotation += 5; }
AvailabilityMethod form introduced in Flash 5 (global form supported by Flash 4 and later) Synopsismc.startDrag() mc.startDrag(lockCenter) mc.startDrag(lockCenter, left, top, right, bottom) Arguments
DescriptionThe MovieClip.startDrag( ) method is an alternative to the global startDrag( ) function. When invoked as a MovieClip method, startDrag( ) takes no target parameter; it drags mc. The method syntax is less prone to user error than its global function counterpart. For usage instructions, see the global startDrag( ) function. BugsNote that the correct order of the constraining rectangular coordinates is left, top, right, bottom but that the Flash 5 ActionScript Dictionary lists them in the wrong order under MovieClip.startDrag( ). Example// Button code to drag and drop the current clip or movie on (press) { this.startDrag(true); } on (release) { stopDrag( ); } See AlsoMovieClip.stopDrag( ), startDrag( ), stopDrag( ); Section 13.8.3.1, "Method versus global function overlap issues" in Chapter 13, "Movie Clips"
AvailabilityMethod form introduced in Flash 5 (global form supported by Flash 2 and later) Synopsismc.stop() DescriptionThe MovieClip.stop( ) method is an alternative to the global stop( ) function. Use the method form to control remote movie clips or main movies specified by mc. For general usage instructions, see the global stop( ) function. Example// Halt the playback of spinner spinner.stop( ); See AlsoMovieClip.play( ), stop( )
AvailabilityMethod form introduced in Flash 5 (global form supported by Flash 4 and later) Synopsismc.stopDrag() DescriptionThe MovieClip.stopDrag( ) method is an alternative to the global stopDrag( ) function. However, there is no need to use the method form; stopDrag( ) cancels any drag operation in progress, whether invoked through a movie clip or as a global function. See AlsoMovieClip.startDrag( ), stopDrag( )
AvailabilityFlash 5 Synopsismc.swapDepths(target) mc.swapDepths(depth) Arguments
DescriptionAll movie clip instances in a .swf document reside in a stack that governs the visual layering of instances in the Player. The stack is structured like a deck of cards; clips in higher positions in the stack appear in front of clips in lower positions. The position of an instance in the stack is initialized when the clip is created (either in the Flash authoring tool or via attachMovie( ) or duplicateMovieClip( ) ). Using swapDepths( ), we can change the position of an instance in the stack. The swapDepths( ) method takes two forms. When used with a target argument, swapDepths( ) trades the stack position of mc and target, provided that mc and target share the same parent clip (reside on the same timeline). When used with a depth argument, swapDepths( ) places mc in a new position in mc's parent stack. If that position is occupied, the previous occupant is moved to mc's old position. Note that swapDepths( ) cannot be used to move a clip outside of the stack maintained by its parent. For information on how movies and movie clips are stacked in the Player, see Section 13.4, "Movie and Instance Stacking Order" in Chapter 13, "Movie Clips". BugsNote that swapping a duplicated or attached instance with a manually created instance via the depth argument can cause redraw problems in the Flash 5 Player. Treat the depth argument with prudence, and always test depth-swapping code extensively. See AlsoSection 13.4, "Movie and Instance Stacking Order" in Chapter 13, "Movie Clips"
AvailabilityFlash 4 and later Synopsismc._target AccessRead-only DescriptionThe _target property represents the path to mc in a Flash 4-style slash notation string. For example, if a clip, ball, resides on the main movie timeline, ball's _target property is "/ball". A clip, stripe, inside ball would have a _target of "/ball/stripe". To retrieve a string giving the path to a clip in dot notation, use the targetPath( ) function. See AlsotargetPath( )
AvailabilityFlash 4 and later Synopsismc._totalframes AccessRead-only DescriptionThe integer _totalframes property represents the number of frames in mc's timeline, where mc is a movie clip or main movie. A new clip or main movie always has a _totalframes of 1. But if the contents of a clip are unloaded via unloadMovie( ), _totalframes becomes 0. It may also be momentarily while the current clip is unloaded before a new clip is loaded during a loadMovie( ) operation over a slow connection. The _totalframes property is most often used along with _frameloaded to create preloaders as shown in the entry for MovieClip._framesloaded. See AlsoMovieClip._framesloaded
AvailabilityMethod form introduced in Flash 5 (global form supported by Flash 3 and later) Synopsismc.unloadMovie() The MovieClip.unloadMovie() method is an alternative to the global unloadMovie() function. When invoked as a MovieClip method, unloadMovie() takes no target parameter; it unloads mc. The method syntax is less prone to user error than its global function counterpart. For usage instructions, see the global unloadMovie( ) function. Example// Removes a loaded document from level 1 _level1.unloadMovie( ); See AlsoMovieClip.loadMovie( ), unloadMovie( ); Section 13.8.3.1, "Method versus global function overlap issues" in Chapter 13, "Movie Clips"
AvailabilityFlash 4 and later Synopsismc._url AccessRead-only DescriptionThe _url property represents the URL (Uniform Resource Locator) indicating the Internet or local disk location from which the content of mc was loaded, as a string. The _url property is always an absolute URL, never a relative one. For main movies, _url is simply the location of the current .swf file. The _url of all movie clips in a .swf file is the same as the main movie of that file unless external .swf files have been loaded into individual clips via MovieClip.loadMovie( ). The _url of a clip that hosts an externally loaded .swf file is the location of the externally loaded file. The _url property is sometimes used to create simple security systems that prevent a movie from playing when displayed in a unwanted location. ExampleThe value of _url in a movie loaded from a web site looks like this: "http://www.moock.org/gwen/meetgwen.swf" The value of _url in a movie loaded from a local PC hard drive looks like this: "file:///C|/data/flashfiles/movie.swf" Here we check whether a movie is hosted in the desired location (if not, we display a frame that contains an error): if (_url != "http://www.moock.org/gwen/meetgwen.swf") { trace ("This movie is not running from its intended location."; gotoAndStop("accessDenied"); } See AlsoMovieClip.loadMovie( )
AvailabilityFlash 5 Synopsismc.valueOf() ReturnsA string containing the full path to mc, using dot syntax. For example: "_level1.ball" "_level0" "_level0.shoppingcart.product1" DescriptionThe valueOf( ) method returns a string representing the absolute path to mc using dot syntax notation. The valueOf( ) method is automatically invoked whenever a MovieClip object is used where a string is called for. For example, trace(mc) will generate the same result as trace(mc.valueOf( )). It is, therefore, rarely necessary to invoke valueOf( ) explicitly. See AlsoObject.valueOf( ), targetPath( )
AvailabilityFlash 4 and later Synopsismc._visible AccessRead/write DescriptionThe Boolean _visible property indicates whether mc is currently shown (true) or hidden (false). We use _visible as a quick means of hiding a movie clip or movie from view. Note that hidden clips may still be controlled via ActionScript and still play, stop, receive events, and otherwise operate as normal. Hidden clips are simply not displayed on screen. The initial value of the _visible property for all movie clips is true, even for movie clips that are fully transparent or completely off stage. The _visible property changes only when deliberately modified by a script; think of it as a way to programmatically show and hide clips, not a reflection of all factors such as position and transparency that can affect a clip's visibility. Hiding a movie clip using the _visible property is preferred to setting it to fully transparent or moving it off stage because the Flash Player does not attempt to draw the graphics in movie clips with _visible set to false, thus improving rendering performance. ExampleThe following button code hides the current clip when the button is depressed and reveals it when the button is released: on (press) { this._visible = false; } on (release) { this._visible = true; } See AlsoMovieClip._alpha
AvailabilityFlash 4; enhanced in Flash 5 Synopsismc._width AccessRead-only in Flash 4; read/write in Flash 5 DescriptionThe floating-point _width property stores a non-negative number specifying the current width of mc, in pixels. If mc has no content, _width is 0. The _width property measures the content of a clip or movie as the distance between the leftmost occupied pixel and the rightmost occupied pixel, even if there is empty space between those pixels. An occupied pixel is a pixel that contains a shape, graphic, button, movie clip, or other content element. Changes made to a clip's width in the authoring tool or via _xscale are reflected by _width. We may set the value of _width in order to horizontally resize a movie clip. Attempts to set _width to a negative value are ignored. Setting a clip's _width to does not hide the clip, it turns it into a one-pixel vertical line. The _width of the main movie (either _root._width or _leveln._width) is not the Stage width as specified under Modify Movie Dimensions in the authoring tool but rather the width of the contents of the main movie. There is no explicit Stage width property; if required, we must provide the Stage width manually as a variable. For example, if a movie's Stage has a width of 550, we could add the following variable: _root.stageWidth = 550; To make that value available on the timeline of any clip, use: Object.prototype.stageWidth = 550; UsageNote that when we set the width of a movie clip, lines are scaled proportionally, losing their original point size as set in the Stroke panel. However, the point size of lines set to Hairline in the Stroke panel is not scaled when a movie clip is resized. That is, use hairlines to prevent your strokes from appearing fat or distorted when a clip is scaled. Exampleball._width = 20; // Set the width of ball to 20 pixels ball._width *= 2; // Double the width of ball See AlsoMovieClip._height, MovieClip._xscale
AvailabilityFlash 4 and later Synopsismc._x AccessRead/write DescriptionThe floating-point _x property always indicates the horizontal position of mc's registration point, but it is measured relative to one of three possible coordinate spaces:
The _x property (along with all horizontal coordinates in Flash) increases to the right and decreases to the left. Fractional _x values are approximated in Flash with antialiasing (blurring). If mc is contained by an instance that is scaled and/or rotated, the coordinate space it inhabits is also scaled and/or rotated. For example, if mc's parent is scaled by 200% and rotated 90 degrees clockwise, _x will increase in the downward direction rather than to the right, and a single unit of _x will actually be 2 pixels instead of 1. Because switching between instance and main movie coordinate spaces can be cumbersome, the MovieClip object provides the localToGlobal( ) and globalToLocal( ) methods for performing coordinate-space transformations. ExamplePlacing the following code on a clip causes it to move 5 pixels to the right with each passing frame (assuming that its coordinate space hasn't been altered by transformations to its parent): onClipEvent (enterFrame) { _x += 5; } Positioning clips via _x and _y is a fundamental task in visual ActionScript programming. The following example shows clip event handlers that cause a clip to follow the mouse at a fixed rate of speed (many other motion samples may be obtained from the online Code Depot): // Make a clip follow the mouse onClipEvent(load) { this.speed = 10; // Moves clip toward the point (leaderX, leaderY) function follow (clip, leaderX, leaderY) { // Move only if we're not at the destination if (clip._x != leaderX || clip._y != leaderY) { // Determine the distance between clip and leader var deltaX = clip._x - leaderX; var deltaY = clip._y - leaderY; var dist = Math.sqrt((deltaX * deltaX) + (deltaY * deltaY)); // Allocate speed between X and Y axes var moveX = clip.speed * (deltaX / dist); var moveY = clip.speed * (deltaY / dist); // If the clip has enough speed to overshoot the destination, // just go to the destination. Otherwise move according to // the clip's speed. if (clip.speed >= dist) { clip._x = leaderX; clip._y = leaderY; } else { clip._x -= moveX; clip._y -= moveY; } } } } onClipEvent(enterframe) { follow(this, _root._xmouse, _root._ymouse); } See AlsoMovieClip.globalToLocal( ), MovieClip.localToGlobal( ), MovieClip._y
AvailabilityFlash 5 Synopsismc._xmouse AccessRead-only DescriptionThe floating-point _xmouse property indicates the horizontal location of the mouse pointer's hotspot relative to the coordinate space of mc. If mc is a main movie, _xmouse is measured from the Stage's left edge. If mc is an instance, _xmouse is measured from the instance's registration point. To obtain a consistent _xmouse coordinate that is always measured relative to the Stage, use _root._xmouse. ExamplePlacing the following code on a clip causes it to mirror the mouse pointer's horizontal position relative to the Stage (it moves left and right in a straight line): onClipEvent (enterFrame) { _x = _root._xmouse; } See AlsoMovieClip._ ymouse
AvailabilityFlash 4 and later Synopsismc._xscale AccessRead/write DescriptionThe floating-point _xscale property specifies the width of mc relative to its original width, expressed as a percentage. If mc is an instance, its "original width" is the width of the instance's symbol in the Library. If mc is a main movie, its "original width" is the width of the movie at authoring time. When the current width of mc is the same as its original width, _xscale is 100. An _xscale of 200 doubles mc's width relative to its original width. An _xscale of 50 halves mc's width relative to its original width. The _xscale property scales a clip about its registration point (proportionately on the right and left sides of the clip's registration point). To size a clip from one side only, place all of the clip's content on one side of the registration point in the clip's symbol (this is a useful technique for creating horizontal preloader bars). When a clip's _xscale is set to a negative value, the clip is flipped horizontally as if across a vertical mirror running through its registration point (i.e., it becomes a mirror image of itself), after which the negative value is treated as a positive. To flip a clip horizontally without resizing it, set the clip's _xscale to -100. Example// Double the width of ball (the height remains unchanged) ball._xscale *= 2; // Create a mirror image of ball ball._xscale = -100; See AlsoMovieClip._ yscale
AvailabilityFlash 4 and later Synopsismc._y AccessRead/write DescriptionThe floating-point _ y property always indicates the vertical position of mc 's registration point, but it is measured relative to one of three possible coordinate spaces.
The _ y property (along with all vertical coordinates in Flash) increases downward and decreases upward -- the opposite of the Cartesian coordinate system. Fractional _ y values are approximated in Flash with antialiasing (blurring). If mc is contained by an instance that is scaled and/or rotated, the coordinate space it inhabits is also scaled and/or rotated. For example, if mc's parent is scaled by 200% and rotated 90 degrees clockwise, _ y will increase toward the left rather than downward, and a single unit of _ y will actually be 2 pixels instead of 1. Because switching between instance and main movie coordinate spaces can be cumbersome, the MovieClip object provides the localToGlobal( ) and globalToLocal( ) methods for performing coordinate-space transformations. ExamplePlacing the following code on a clip causes the clip to move down 5 pixels with each passing frame (assuming that its coordinate space hasn't been altered by transformations to its parent): onClipEvent (enterFrame) { _y += 5; } See AlsoMovieClip.globalToLocal( ), MovieClip.localToGlobal( ), MovieClip._x
AvailabilityFlash 5 Synopsismc._ymouse AccessRead-only DescriptionThe floating-point _ ymouse property indicates the vertical location of the mouse pointer's hotspot relative to the coordinate space of mc. If mc is a main movie, _ ymouse is measured from the Stage's top edge. If mc is an instance, _ ymouse is measured from the instance's registration point. To obtain a consistent _ ymouse coordinate that is always measured relative to the Stage, use _root._ ymouse. ExamplePlacing the following code on a clip causes it to mirror the mouse pointer's vertical position relative to the Stage (it moves up and down in a straight line): onClipEvent (enterFrame) { _y = _root._ymouse; } See AlsoMovieClip._xmouse
AvailabilityFlash 4 and later Synopsismc._yscale AccessRead/write DescriptionThe floating-point _ yscale property specifies the height of mc relative to its original height, expressed as a percentage. If mc is an instance, its "original height" is the height of the instance's symbol in the Library. If mc is a main movie, the "original height" is the height of the movie at authoring time. When the current height of mc is the same as its original height, _ yscale is 100. A _ yscale of 200 doubles mc's height relative to its original height. A _ yscale of 50 halves mc's height relative to its original height. The _ yscale property scales a clip about its registration point (proportionately above and below the clip's registration point). To size a clip from above or below only, place all of the clip's content above or below the registration point in the clip's symbol (this is a useful technique for creating vertical preloader bars). When a clip's _ yscale is set to a negative value, the clip is flipped vertically as if across a horizontal mirror running through its registration point (i.e., it becomes a vertical mirror image of itself), after which the negative value is treated as a positive. To flip a clip vertically without resizing it, set the clip's _ yscale to -100. Example// Double the height of ball (the width remains unchanged) ball._yscale *= 2; // Flip ball vertically ball._yscale = -100; See AlsoMovieClip._xscale
AvailabilityFlash 5 SynopsisNaN AccessRead-only DescriptionNaN is a special numeric constant used to represent invalid numeric data (NaN is an acronym for "Not-a-Number"). Numeric operations that cannot be resolved to a legitimate number yield the value NaN. For example: Math.sqrt(-1); // An imaginary number that cannot be represented 15 - "coffee cup"; // "coffee cup" cannot be converted to a number. Note that NaN is still numeric data, even though it is not a calculable number: typeof NaN; // Yields "number" UsageThe value NaN is hardly ever used directly in source code but rather serves as a way for an operation to return an error condition. Because NaN does not compare equal to itself, the only way you can detect it is with the global function isNaN( ). NaN is shorthand for Number.NaN. See AlsoisNaN( ), Number.NaN; Section 4.3.3, "Special Values of the Number Datatype" in Chapter 4, "Primitive Datatypes"
AvailabilityFlash 4 and later Synopsisnewline ReturnsA newline character. DescriptionThe constant newline represents a standard line break character (ASCII 10). It is synonymous with the escape sequence "\n" and is used to force a line break in a block of text (usually for display in a text field variable). UsageThough newline was a function in Flash 4, it became a constant in Flash 5 and has a syntax that resembles a property or variable. Note that parentheses are not used following newline. ExamplemyOutput = "hello" + newline + "world"; See AlsoSee Section 4.5.2.2, "Escape sequences" in Chapter 4, "Primitive Datatypes"
AvailabilityFlash 2 and later SynopsisnextFrame() DescriptionThe nextFrame( ) function moves the playhead of the current timeline ahead one frame and stops it there. The "current timeline" is the timeline from which the nextFrame( ) function is invoked. The nextFrame( ) function is synonymous with gotoAndStop(_currentFrame + 1);. If invoked on the last frame of a timeline, nextFrame( ) simply stops the playhead on that frame unless another scene follows the current scene, in which case nextFrame( ) moves the playhead to frame 1 of the next scene. See AlsogotoAndStop( ), MovieClip.nextFrame( ), nextScene( ), prevFrame( )
AvailabilityFlash 2 and later SynopsisnextScene() DescriptionThe nextScene( ) function moves the main playhead of a movie to frame 1 of the scene following the current scene and stops the main movie timeline. The "current scene" is the scene from which the nextScene( ) function is invoked. It must be invoked on a scene's main timeline in order to have an effect; that is, nextScene( ) does not work inside a movie clip or onClipEvent( ) handler. If invoked from the last scene in a movie, nextScene( ) sends the playhead to frame 1 of that scene and halts movie playback. See AlsonextFrame( ), prevScene( )
AvailabilityFlash 5 SynopsisNumber(value) Arguments
ReturnsThe result of converting value to a primitive number. DescriptionThe Number( ) function converts its argument to a primitive numeric value and returns that converted value. The results of converting various types of data to a primitive number are described in Table 3-1. It's often not necessary to use the Number( ) function; ActionScript automatically converts values to the number type when appropriate. Be sure not to confuse the global Number( ) function with the Number class constructor. The former is a function that converts a value to the number type, whereas the latter is the class used to wrap a primitive numeric datum in an object that can take properties and methods. UsageNote that the Number( ) function frequently appears in Flash 4 .fla files that have been converted to the Flash 5 format. For information on how datatypes are handled when Flash 4 files are converted to Flash 5, see Section 3.4.4, "Flash 4-to-Flash 5 Datatype Conversion" in Chapter 3, "Data and Datatypes". See AlsoThe Number class, parseFloat( ), parseInt( ); Section 3.4.2, "Explicit Type Conversion" in Chapter 3, "Data and Datatypes"
AvailabilityFlash 5 Constructornew Number(value) Arguments
Class PropertiesThe following properties are accessed directly as properties of the Number class, using Number.propertyName. To access them you do not need to instantiate a new Number object (i.e., there is no need for the constructor function). Some of these properties, such as NaN don't even require the Number.propertyName notation. You can simply use NaN as shorthand for Number.NaN (details for each property follow later).
Methods
DescriptionThe Number class has two purposes:
UsageThere is no need to create a new Number object if you simply want to access the numeric properties it defines. In fact, where applicable, it is easier to use global property equivalents (NaN, Infinity, and -Infinity). Frankly, it is rare that you'll need the Number class properties at all. On the other hand, the Number class's toString( ) method is used with an instantiated Number object. However, the interpreter takes care of creating a Number object for us whenever we invoke a method on a primitive numeric value. For example: x = 102; x.toString(16); // x is automatically converted to a Number object // for the sake of this operation. You might do this in order to, say, use toString( ) to convert between various number systems. Again, frankly, this is a fairly rare task, so you probably won't be using the Number class much. See AlsoThe Math object; Section 4.1, "The Number Type" in Chapter 4, "Primitive Datatypes"
AvailabilityFlash 5 SynopsisNumber.MAX_VALUE AccessRead-only DescriptionThe MAX_VALUE property stores the largest representable positive number in ActionScript (1.7976931348623157e+308). It is convenient when you'd like to start with a very large value, as shown in the following example. Any number greater than MAX_VALUE can't be represented by ActionScript and is therefore considered to be POSITIVE_INFINITY. ExampleHere we are looking for a minimum value in an array. We initialize the minVal variable to MAX_VALUE, knowing that any subsequent value will be less than it: var myArray = [-10, 12, 99] var minVal = Number.MAX_VALUE for (thisValue in myArray) { if (myArray[thisValue] < minVal) { minVal = myArray[thisValue]; } } trace ("The minimum value is " + minVal); See AlsoNumber.MIN_VALUE; Number.POSITIVE_INFINITY; Section 4.3.3, "Special Values of the Number Datatype" in Chapter 4, "Primitive Datatypes"
AvailabilityFlash 5 SynopsisNumber.MIN_VALUE AccessRead-only DescriptionThe MIN_VALUE property stores the smallest representable positive number in ActionScript, 5e-324 (not to be confused with -Number.MAX_VALUE, the most-negative number allowed in ActionScript). See AlsoNumber.MAX_VALUE; Section 4.3.3, "Special Values of the Number Datatype" in Chapter 4, "Primitive Datatypes"
AvailabilityFlash 5 SynopsisNumber.NaN AccessRead-only DescriptionThe NaN property stores the special "invalid number" value of the number datatype. It is used to represent the result of an illogical mathematical calculation (e.g., 0/0) or an attempted data conversion that does not yield a legitimate number. Number.NaN is normally used in its more convenient global property form, NaN. UsageThe value NaN is hardly ever used directly in source code but rather serves as a way for an operation to return an error condition. The only way you can detect NaN is with the global function isNaN( ). See AlsoisNaN( ), NaN; Section 4.3.3, "Special Values of the Number Datatype" in Chapter 4, "Primitive Datatypes"
AvailabilityFlash 5 SynopsisNumber.NEGATIVE_INFINITY AccessRead-only DescriptionThe NEGATIVE_INFINITY property stores a special numeric value used to represent values more negative than -Number.MAX_VALUE (the most-negative number representable in ActionScript). This is known as an underflow condition and is typically caused by a mathematical error. Number.NEGATIVE_INFINITY is normally used in its more convenient global property form, -Infinity. See Also-Infinity, isFinite( ), Number.MAX_VALUE; Section 4.3.3, "Special Values of the Number Datatype" in Chapter 4, "Primitive Datatypes"
AvailabilityFlash 5 SynopsisNumber.POSITIVE_INFINITY AccessRead-only DescriptionThe POSITIVE_INFINITY property stores a special numeric value used to represent values greater than Number.MAX_VALUE (the largest number representable in ActionScript). This is known as an overflow condition and is usually caused by some sort of mathematical error. Number.POSITIVE_INFINITY is normally used in its more convenient global property form, Infinity. Exampleif (score == Number.POSITIVE_INFINITY) { trace ("You've achieved the highest possible score."); } See AlsoInfinity, isFinite( ), Number.MAX_VALUE; Section 4.3.3, "Special Values of the Number Datatype" in Chapter 4, "Primitive Datatypes"
AvailabilityFlash 5 SynopsisnumberObject.toString(radix) Arguments
ReturnsThe value of numberObject converted to a string. DescriptionThe toString( ) method retrieves the value of a Number object, converts that value to a string, and returns that string. We may use the radix argument to convert numeric values between different bases (e.g., binary, octal, decimal, and hexadecimal). The letters A-Z are used to represent digits with the value 10-35, respectively, although ordinarily only A through F are used (to represent the hex digits equivalent to 10 through 15). To use Number.toString( ) with a primitive numeric value, surround the value with parentheses, as in: (204).toString(16); Examplex = new Number(255); trace(x.toString( )); // Displays: "255" (i.e., decimal) trace(x.toString(16)); // Displays: "ff" (i.e., hexadecimal) trace(x.toString(2)); // Displays: "11111111" (i.e., binary) // Convert a hex literal to decimal trace((0xFFFFFF).toString(10)); // Displays: "16777215" See AlsoNumber ( ), Object.toString( ), parseInt( ); See Section 4.3.1, "Integer Literals" in Chapter 4, "Primitive Datatypes"
AvailabilityFlash 5 Constructornew Object() Properties
Methods
DescriptionThe Object class is the base class of the ActionScript object model. Object is used for two general purposes: (a) as a constructor for creating new, generic objects, and (b) as a superclass upon which to base new classes. All classes in ActionScript, whether user-defined or built-in are descendants of the Object class. All objects of all classes therefore inherit the properties of Object (though some classes override those properties). To create a generic object of the Object class directly in our code without using a constructor, we can use an object literal just as we might use a string literal or an array literal. An object literal is a series of comma-separated property name/value pairs, enclosed in curly braces. Here's the general syntax: { property1: value1, property2: value2, property3: value3 } The names of properties in an object literal must be legal identifiers as described in Chapter 14, "Lexical Structure". The values may be any valid expression. For example: // An object literal with two numeric properties myObject = { x: 30, y: 23 }; // Set the x property value using a complex expression myOtherObject = { x: Math.floor(Math.random( ) * 50 + 1) }; Because object literals always create generic, anonymous objects, they are used only when we need object-formatted data temporarily, such as when, say, invoking Sound.setTransform( ), Color.setTransform( ), or MovieClip.localToGlobal( ). See Also
AvailabilityFlash 5 SynopsissomeObject.constructor AccessRead/write (overwriting an object's constructor property is not recommended as it alters the natural structure of class inheritance). DescriptionThe constructor property stores a reference to the constructor function that was used to create someObject. For example, the constructor property of a Date object is the Date constructor function: now = new Date( ); now.constructor == Date; // Yields true See AlsoSection 12.5.3.3, "The constructor property" in Chapter 12, "Objects and Classes"
AvailabilityFlash 5 SynopsissomeObject.__ proto__ AccessRead/write (Overwriting an object's __ proto__ property is not recommended as it alters the natural structure of class inheritance.) DescriptionThe __ proto__ property stores a reference to the automatically-assigned prototype property of someObject's constructor function, which is used to transfer properties down through a class hierarchy. An object's __ proto__ property is mostly used internally by the interpreter to look up inherited properties for an object, but we can also use it to determine the class of an object, as shown in Example 12-6 and Example 12-9. Note that __ proto__ begins and ends with two underscore characters. See AlsoSection 12.5.3.4, "The _ _ proto_ _ property" in Chapter 12, "Objects and Classes"
AvailabilityFlash 5 SynopsissomeObject.toString() ReturnsAn internally defined string that describes or otherwise represents the object. DescriptionThe toString( ) method returns a string description for someObject. By default, someObject.toString( ) returns the expression: "[object " + class + "]" where class is the internally defined name of the class to which someObject belongs. The ActionScript interpreter automatically invokes the toString( ) method whenever someObject is used in a string context. For example: x = new Object( ); trace(x); // Displays: "[object Object]" Most classes overwrite the default toString( ) method of Object in order to provide more meaningful information about each member of the class. For example, the Date.toString( ) method returns the date and time, and the Array.toString( ) method returns a comma-separated list of array elements. We may do the same when constructing our own classes. ExampleThis example shows how to provide a custom toString( ) method for the Ball class that we created in Chapter 12, "Objects and Classes": // Add a Custom toString() method // Make the Ball constructor function Ball (radius, color, xPosition, yPosition) { this.radius = radius; this.color = color; this.xPosition = xPosition; this.yPosition = yPosition; } // Assign a function literal to the Ball class prototype's toString() method Ball.prototype.toString = function ( ) { return "A ball with the radius " + this.radius; }; // Create a new ball object myBall = new Ball(6, 0x00FF00, 145, 200); // Now check myBall's string value trace(myBall); // Displays: "A ball with the radius 6" See AlsoArray.toString( ), Date.toString( ), Number.toString( ), Object.valueOf( )
AvailabilityFlash 5 SynopsissomeObject.valueOf() ReturnsThe internally defined primitive value of someObject, if a primitive value is associated with someObject. If no primitive value is associated with someObject, then someObject itself is returned. DescriptionThe valueOf( ) method returns the primitive datum associated with an object, if such an association exists. This method is mostly commonly used with objects of the Number, String, and Boolean classes, which all have associated primitive data. The MovieClip.valueOf( ) method returns a string representing the path to the clip. Note that it's rarely necessary to invoke valueOf( ) explicitly; it is automatically invoked by the interpreter whenever someObject is used where a primitive is expected. See AlsoBoolean.valueOf( ), MovieClip.valueOf( ), Number.valueOf( ), Object.toString( ), String.valueOf( )
AvailabilityFlash 5 SynopsisparseFloat(stringExpression) Arguments
ReturnsThe extracted floating-point number. Or, if extraction was unsuccessful, the special numeric value NaN. DescriptionThe parseFloat( ) function converts a string to a floating-point number (a number with a fractional portion). It works only with strings that contain a valid string representation of a floating-point number; otherwise, NaN is returned. The string must be of the following form:
Trailing characters that cannot be parsed as part of the preceding numeric form are ignored. UsageBecause user input data entered into text fields always belongs to the string datatype, we often use parseFloat( ) to extract numeric data from user-entered text. Note that parseFloat( ) can extract numbers from strings that contain both numbers and non-numeric characters, whereas Number( ) cannot. ExamplesparseFloat("14.5 apples"); // Yields 14.5 parseFloat(".123"); // Yields 0.123 var x = "15, 4, 23, 9"; parseFloat(x); // Yields 15 See AlsoisNaN( ), NaN, Number( ), parseInt( ); Section 3.4.2, "Explicit Type Conversion" in Chapter 3, "Data and Datatypes"; Section 4.2, "Integers and Floating-Point Numbers" in Chapter 4, "Primitive Datatypes"
AvailabilityFlash 5 SynopsisparseInt(stringExpression) parseInt(stringExpression, radix) Arguments
ReturnsThe extracted integer value, as a base-10 number regardless of the original radix. Or, if extraction was unsuccessful, the special numeric value NaN. DescriptionThe parseInt( ) function converts a string expression to an integer. It works only with strings that contain a valid string representation of an integer using the specified radix. The string must be of the following form:
Trailing characters that cannot be parsed as part of the preceding numeric form are ignored. The number derived from the supplied string starts with the first nonblank character in the string and ends with the character before the first character that is not a legitimate digit in the supplied radix. For example, in the base-10 system, the letter F is not a valid digit, so the following expression yields the number 2: parseInt("2F", 10); But in the base-16 system (hexadecimal), the characters A, B, C, D, E, and F are valid numerals, so the following expression yields the number 47: parseInt("2F", 16); // 2F in hexadecimal is 47 in base-10 The radix argument of parseInt( ) specifies the base of the number as it exists in the string. In other words, using the radix argument we may say to the interpreter "Treat this string as a base-16 number" or "Treat this string as a base-2 number." parseInt( ) also interprets the prefix 0x to indicate a hexadecimal (a.k.a. hex) number (as if a radix of 16 was specified) and a leading to indicate an octal number (as if a radix of 8 was specified): parseInt("0xFF"); // Parsed as hex, yields 255 parseInt("FF", 16); // Parsed as hex, yields 255 parseInt("0377"); // Parsed as octal, yields 255 = (3 * 64) + (7 * 8) + (7 * 1) parseInt("377", 8); // Parsed as octal, yields 255 An explicit radix overrides any implicit radix: parseInt ("0xFF", 10) // Parsed as decimal, yields 0 parseInt ("0x15", 10) // Parsed as decimal, yields 0 (not 15, and not 21) parseInt ("0377", 10) // Parsed as decimal, yields 377 Note that the parseInt( ) function extracts integer values only, unlike parseFloat( ) which can also extract fractional values but may be used only with base-10 numbers. ExampleWe primarily use parseInt( ) to extract integers from a string that contains both numbers and text or to remove the decimal place from a number (similar to Math.floor( )). parseInt("Wow, 20 people were there"); // Yields NaN parseInt("20 people were there"); // Yields 20 parseInt("1001", 2); // Yields 9 (1001 evaluated in binary) parseInt(1.5); // Yields 1 (the number 1.5 is converted to the string // "1.5" before the parseInt operation proceeds) See AlsoMath.floor( ), NaN, parseFloat( ); Section 3.4.2, "Explicit Type Conversion" in Chapter 3, "Data and Datatypes"; Section 4.2, "Integers and Floating-Point Numbers" in Chapter 4, "Primitive Datatypes"
AvailabilityFlash 2 and later Synopsisplay() DescriptionInvoking the play( ) function initiates the sequential display of the frames in the current main movie or movie clip. The "current" movie or movie clip is the one that bears the play( ) function invocation statement. Frames are displayed at a rate dictated by the frames per second (or FPS) setting of the entire movie, which is set under the Movie Properties (Modify Movie Frame Rate). Once started, the playback of a movie or movie clip continues until another function invocation specifically stops the playback. All movie clips loop (begin playing again at frame 1) when the playhead reaches the end of the timeline. In a browser, however, main movies loop only if the code used to embed the movie in the HTML page specifies that the movie should loop, as determined by the LOOP attribute. (If you're using the Publish command to embed your movie in an HTML page, set the LOOP attribute by selecting File Publish Settings HTML Playback Loop.) See AlsogotoAndPlay( ), MovieClip.play( ), stop( )
AvailabilityFlash 2 and later SynopsisprevFrame() DescriptionThe prevFrame( ) function moves the playhead of the current timeline back one frame and stops it there. The "current timeline" is the timeline from which the prevFrame( ) function is invoked. The prevFrame( ) function is synonymous with gotoAndStop(_currentFrame - 1);. If invoked on the first frame of a timeline, prevFrame( ) simply stops the playhead on that frame unless another scene precedes the current scene, in which case prevFrame( ) moves the playhead to the last frame of the previous scene. See AlsogotoAndStop( ), MovieClip.prevFrame( ), nextFrame( ), prevScene( )
AvailabilityFlash 2 and later SynopsisprevScene() DescriptionThe prevScene( ) function moves the main playhead of a movie to frame 1 of the scene before the current scene and stops the main movie timeline. The "current scene" is the scene from which the prevScene( ) function is invoked. It must be invoked on a scene's main timeline in order to have an effect; that is, prevScene( ) does not work inside a movie clip or onClipEvent( ) handler. If invoked from the first scene in a movie, prevScene( ) sends the playhead to frame 1 of that scene and halts movie playback. See AlsonextScene( ), prevFrame( )
AvailabilityFlash 5 Synopsisprint(target, boundingBox) Arguments
DescriptionPrinting a Flash movie using a web browser's built-in print function behaves inconsistently and often results in poor quality printouts. Using the print( ) function, we can print the contents of a movie with accuracy and quality, directly from Flash. By default, print( ) causes all of the frames of target's timeline to be sent to the printer, one frame per page, cropped according to the boundingBox argument. To designate only specific frames for printing, we assign the label #P to the desired frames. The print( ) function sends vectors directly to PostScript printers and vectors converted to bitmaps to non-PostScript printers. Because print( ) uses vectors, it cannot be used to print movies with alpha transparency or color transformations. To print movies that have color effects, use printAsBitmap( ). UsageIn Flash 4 r20 and above, the features of the various Flash 5 print( ) functions are available as a modified getURL( ) Action. For more details, see Macromedia's Flash Printing SDK, available at:
Example// Print every frame in the main movie timeline, // sizing each individually to fill the page print("_root", "bframe"); // Print every frame in the main movie timeline, // sizing each frame relative to the combined size of all frames print("_root", "bmax"); When a button with the following code is clicked, Flash prints all frames in the button's timeline, cropped to the bounding box of the frame with the label #b and sized to fill the page: on (release) { print(this, "bmovie"); } See AlsogetURL( ), printAsBitmap( ), printAsBitmapNum( ), printNum( )
AvailabilityFlash 5 SynopsisprintAsBitmap(target, boundingBox) Arguments
DescriptionThe printAsBitmap( ) function is functionally identical to print( ), except that it outputs rasterized content to the printer, not vectors. It can, therefore, successfully print movies with color transformations but produces poorer quality for vector-based artwork. UsageSee Usage notes under the print( ) function. See Alsoprint( ), printAsBitmapNum( ), printNum( )
AvailabilityFlash 5 SynopsisprintAsBitmapNum(level, boundingBox) Arguments
DescriptionThe printAsBitmapNum( ) function is nearly identical to printAsBitmap( ) except that it requires the target level of the print operation to be specified as a number rather than as a string. This means that printAsBitmapNum( ) can print only document levels, not movie clips. It is normally used when we wish to dynamically assign the level of a movie to print, as in: var x = 3; printAsBitmapNum(x, "bmax"); which could also be achieved using string concatenation with the regular printAsBitmap( ) function: printAsBitmap("_level" + x, "bmax"); UsageSee Usage notes under the print( ) function. See Alsoprint( ), printAsBitmap( ), printNum( )
AvailabilityFlash 5 SynopsisprintNum(level, boundingBox) Arguments
DescriptionThe printNum( ) function is nearly identical to print( ) except that it requires the target level of the print operation to be specified as a number rather than as a string. This means that printNum( ) can print only document levels, not movie clips. It is normally used when we wish to dynamically assign the level of a movie to print, as in: var x = 3; printNum(x, "bmax"); which could also be achieved using string concatenation with the regular print( ) function: print("_level" + x, "bmax"); UsageSee Usage notes under the print( ) function. See Alsoprint( ), printAsBitmap( ), printAsBitmapNum( )
AvailabilityFlash 5 Synopsis_quality AccessRead/write DescriptionThe _quality property stores a string that dictates the rendering quality of the Flash Player as follows:
Lower rendering quality means that fewer calculations are required to draw a frame of the movie, resulting in faster performance. The typical setting of _quality for most movies is "HIGH". ExampleHere we set the rendering quality of a movie to the best it can be (which also causes the slowest playback): _quality = "BEST"; See Also_highQuality, toggleHighQuality( )
AvailabilityFlash 4; deprecated in Flash 5 in favor of Math.random( ) Synopsisrandom(number) Arguments
ReturnsA random integer greater than or equal to 0 and less than number. DescriptionThe deprecated random( ) function was used in Flash 4 to generate random numbers. This function has been retired from the language and is available only for the sake of backward compatibility. In Flash 5 and higher, use the preferred Math.random( ) method. Note that random( ) generated integers from to number -1, whereas Math.random( ) generates floats from 0.0 to .999. See AlsoMath.random( )
AvailabilityFlash 4; enhanced in Flash 5 to apply to instances created with attachMovie( ) SynopsisremoveMovieClip(target) Arguments
DescriptionThe removeMovieClip( ) function deletes the specified movie clip from the Player, leaving no trace of the clip's contents or shell. Subsequent references to the clip or any of its variables or properties yield undefined. The removeMovieClip( ) function may be used only on movie clip instances that were originally created via duplicateMovieClip( ) or attachMovie( ). It has no effect on movie clips created in the authoring tool. See AlsoattachMovie( ), duplicateMovieClip( ), MovieClip( ).removeMovieClip( ); Section 13.6, "Removing Clip Instances and Main Movies" in Chapter 13, "Movie Clips"
AvailabilityFlash 5 (same as "/" in Flash 4 movies) Synopsis_root AccessRead-only DescriptionThe _root property stores a reference to the main timeline of the current document level. We use _root to invoke methods on the main movie or to retrieve and set the main movie's properties. For example: _root.play( ); // Play the main timeline _root._alpha = 40; // Make the whole movie partially transparent The _root property may also be used to refer to nested clips. For example: _root.myClip.play( ); _root.shapes.square._visible = false; The _root property provides access to a movie clip in absolute terms. That is, a reference that starts with _root is valid (and invariant) from anywhere in a movie. See Also_leveln; _ parent; Section 13.5.4, "Referring to Main Movies with _root and _leveln" in Chapter 13, "Movie Clips" and Section 2.5.6, "Accessing Variables on Different Timelines" in Chapter 2, "Variables"
AvailabilityFlash 4 and later Synopsistextfield.scroll ReturnsA positive integer representing the number of the topmost viewable line of a text field. DescriptionThe scroll text field property can be both retrieved and set. When we retrieve the value of a text field's scroll property, it indicates the number of the line currently displayed as the first line in the field's viewable region. When we set the value of scroll, it scrolls the text field, making the supplied line number the top line in the field's viewable region. The scroll property is normally used with maxscroll to create text-scrolling interfaces as described under Section 18.4.3, "Typical Text-Scrolling Code" in Chapter 18, "On-Screen Text Fields". UsageThough scroll is listed as a function in Flash, it is effectively used as a property of a text field variable. Notice that parentheses are not used when scroll is invoked. BugsIn Build 5.0 r30 of the Flash Player, when a text field's font is embedded, using scroll may cause some text to be displayed outside the visual region of the field. Some text may not be removed as the text in the field scrolls. To work around the problem, use a mask over the text field layer. This problem was fixed in Build 5.0 r41. Example// Sets x to the index of the top line displayed in myField var x = myField.scroll; // Scrolls the text in myField down one myField.scroll++; See Alsomaxscroll; Section 18.4.1, "The scroll Property" in Chapter 18, "On-Screen Text Fields"
AvailabilityFlash 5 SynopsisSelection.methodName() Methods
DescriptionWe use the Selection object to control user interaction with text fields and to capture portions of text fields. In actual use, the Selection object methods are preceded by the keyword Selection; they always operate on the text field with focus, of which there can be only one at any given time. The methods of a Selection object can position the insertion point and can select or retrieve a text field's content. These abilities add subtle but important behavior to user-input systems. For example, in a user-login screen, we can prompt a user to enter his name by placing the cursor in a name-entry text field. Or we can highlight an error in a form by selecting the problematic text. We can also customize the so-called Tab order of a series of text fields, as shown under Reference 20.205. Positions of the characters in a text field are referred to with zero-relative indexes where the first character is index 0, the second is index 1, and so on. Character indexing is described in detail in Section 4.6.4, "Character Indexing" in Chapter 4, "Primitive Datatypes". In Flash 5 it is not possible to cut, copy, or paste text programmatically. Further, cut, copy, and paste shortcut keys such as Ctrl-C and Ctrl-V are not functional in the Flash Player. The secondary mouse button (right-click on Windows, Ctrl-click on Macintosh) provides access to the cut, copy, and paste commands. UsageClicking a form's submit button automatically removes focus from any previously focused text field. To capture a selection before focus is lost, use the button's rollover event. For example: on (rollOver) { focusedField = Selection.getFocus(); } See Also_focusrect, Selection.setFocus( ); Chapter 18, "On-Screen Text Fields"
AvailabilityFlash 5 SynopsisSelection.getBeginIndex() ReturnsThe index of the first character in the current selection (highlighted block of text). If no text field has keyboard focus, it returns -1. If a text field has focus but no characters are selected, it returns the value of Selection.getCaretIndex( ). DescriptionThe getBeginIndex( ) method identifies the beginning of a selection. To determine the span of characters currently selected, use both getBeginIndex( ) and getEndIndex( ). ExampleThe following example creates a string representing the currently selected characters and then displays that string in the Output window: var firstChar = Selection.getBeginIndex( ); var lastChar = Selection.getEndIndex( ); var currentSelection = eval(Selection.getFocus( )).substring(firstChar, lastChar); trace(currentSelection); The following code extends the current selection by one character to the left: Selection.setSelection(Selection.getBeginIndex() - 1, Selection.getEndIndex( )); See AlsoSelection.getCaretIndex( ), Selection.getEndIndex( )
AvailabilityFlash 5 SynopsisSelection.getCaretIndex() ReturnsThe index of the insertion point in the current text field. If no text field has keyboard focus, it returns -1. If the text field with focus is empty, it returns 0. DescriptionThe getCaretIndex( ) method indicates the insertion point (i.e., the location of the cursor) in a text field. The cursor appears as an I-beam when a text field has keyboard focus. Use setSelection( ) to set the location of the insertion point. ExampleBecause getCaretIndex( ) returns -1 when no text field has focus, we may determine whether any field has focus by checking whether getCaretIndex( ) is equal to -1, as follows: if (Selection.getCaretIndex( ) == -1) { trace("No field has focus"); } See AlsoSelection.setSelection( )
AvailabilityFlash 5 SynopsisSelection.getEndIndex() ReturnsThe index of the character after the last character in the current selection (highlighted block of text). If no text field has focus, it returns -1. If a text field has focus but no characters are selected, it returns the value of Selection.getCaretIndex( ). DescriptionThe getEndIndex( ) method identifies the end of a selection. To identify the span of characters currently selected, use both getEndIndex( ) and getBeginIndex( ). ExampleThe following code extends the current selection by one character to the right: Selection.setSelection(Selection.getBeginIndex(), Selection.getEndIndex( )+ 1); See Also
AvailabilityFlash 5 SynopsisSelection.getFocus() ReturnsA string indicating the full path to the text field variable that has keyboard focus (i.e., the one in which the cursor currently resides), for example, "_level1.myTextField". If no text field has keyboard focus, it returns null. DescriptionThe getFocus( ) method identifies which text field currently has focus (if any) by returning its string path. To turn that string into a variable reference, we use eval( ). For example, in the following code we identify the number of characters in the text field with focus. We retrieve the name of the field by invoking getFocus( ), and we convert that name into a variable with eval( ) : var numChars = eval(Selection.getFocus( )).length; ExampleBecause getFocus( ) returns null when no text field is selected, we may determine whether any field has focus by checking whether getFocus( ) is equal to null, as follows: if (Selection.getFocus( ) == null) { trace("No field has focus"); } See AlsoSelection.setFocus( ), eval( ), Selection.getCaretIndex( )
AvailabilityFlash 5 SynopsisSelection.setFocus(variableName) Arguments
ReturnsA Boolean indicating whether the focus attempt succeeded (true) or failed (false). A focus attempt fails only if the variable specified by variableName is not found or if it is not a text field variable. DescriptionThe setFocus( ) method sets the keyboard focus for a text field. It places the cursor in that text field, normally in order to draw attention to the field or to allow the user to enter data. The setFocus( ) method can also provide a handy means of identifying erroneous input to a user. In an online form, for example, a user may mistype an email address. To alert the user to the error, we could set the focus to the email-address text field and ask her to fix the problem. We can also use setFocus( ) to create a custom Tab key order for the fields in a form, as shown in the example that follows. UsageNote that setting the focus of a text field automatically selects any content in that field. To set a field's focus without selecting any characters, use the following code: // First, focus myField Selection.setFocus("myField"); // Now place the insertion point at the start of myField Selection.setSelection(0, 0); // Or at the end of myField Selection.setSelection(myField.length, myField.length);
ExampleThis example shows how to assign a custom Tab order to the fields in a fill-in form. The corresponding sample .fla file may be downloaded from the online Code Depot (for more information on trapping the Tab key, see Section 10.11.4.1, "Handling special keys" in Chapter 10, "Events and Event Handlers"): // Custom Tab Order // CODE ON THE MOVIE CLIP CONTAINING THE FORM FIELDS onClipEvent (load) { // Store the path to this clip in a string. We'll use it // later when invoking Selection.setFocus( ). path = targetPath(this); // Create an array with the names of our text fields, supplied // in the desired Tab order. The first field listed is the default. tabOrder = ["field1", "field3", "field2", "field4"]; } onClipEvent (keyUp) { // If the Tab key was pressed... if (Key.getCode( ) == Key.TAB) { // ...If no field has focus... if (Selection.getFocus( ) == null) { // ...then set focus to the first field in the array of fields Selection.setFocus(path + "." + tabOrder[0]); } else { // Otherwise, locate the currently focused field in the array of fields i = 0; focused = Selection.getFocus( ); while (i < tabOrder.length) { // Extract the name of the field variable from the full path // that's returned by Selection.getFocus( ) fieldName = focused.substring(focused.lastIndexOf(".") + 1); // Check each element of tabOrder for the focused field. if (tabOrder[i] == fieldName) { // Stop when we find a match currentFocus = i; break; } i++; } // Now that we know where the focused field lies in the tabOrder array, // set the new focus to either the next field or the previous field, // depending on whether the Shift key is down. if (Key.isDown(Key.SHIFT)) { // Shift key is down, so go to the previous field, unless we're already // at the beginning, in which case go to the last field. nextFocus = currentFocus-1 == -1 ? tabOrder.length-1 : currentFocus-1; } else { // Shift key is not down, so go to the next field, // unless we're already at the end, in which case go to the first field. nextFocus = currentFocus+1 == tabOrder.length ? 0 : currentFocus+1; } // Finally, assign the new focus Selection.setFocus(path + "." + tabOrder[nextFocus]); } } } // CODE ON BUTTON ON MAIN TIMELINE on (keyPress "<Tab>") { // This placeholder code just traps the Tab key in Internet Explorer var tabCatcher = 0; } See Also
AvailabilityFlash 5 SynopsisSelection.setSelection(beginIndex, endIndex) Arguments
DescriptionThe setSelection( ) method selects (highlights) the characters from beginIndex to endIndex-1 in the text field with focus. If no field has focus, setSelection( ) has no effect. It is commonly used to highlight problematic user input. UsageThough the Selection object does not have a "setCaretIndex" method, we may use the setSelection( ) method to set the insertion point to a specific location within a text field. To do so, we specify the same beginIndex and endIndex values, as in: // Set the insertion point after the third character Selection.setSelection(3, 3); Example// Select the second and third letters // of the currently focused text field Selection.setSelection(1, 3); See AlsoSelection.getBeginIndex( ), Selection.getCaretIndex( ), Selection.getEndIndex( )
AvailabilityFlash 4 and later SynopsissetProperty(movieClip, property, value) Arguments
DescriptionThe setProperty( ) function assigns value to one of movieClip's built-in properties (the built-in properties are listed under the MovieClip class ). It cannot be used to set the value of custom (i.e., user-defined) properties. In Flash 4, setProperty( ) was the only means to assign movie clip property values; as of Flash 5, the . and [] operators are the preferred means of setting both built-in and custom movie clip properties. Example// Flash 4 syntax. Rotate the main movie by 45 degrees: setProperty("_root", _rotation, 45); // Flash 5 syntax. Also rotates the main movie by 45 degrees: _root._rotation = 45; See AlsogetProperty( ); Section 13.1, "The "Objectness" of Movie Clips" in Chapter 13, "Movie Clips"; Appendix C, "Backward Compatibility".
AvailabilityFlash 5 Constructornew Sound() new Sound(target) Arguments
Methods
DescriptionObjects of the Sound class are used to control the existing sounds in a movie or to control sounds added to a movie programmatically. Sound objects have several distinct applications. They can control:
To create a Sound object that controls all the sounds in the Player (including sounds in .swf files on document levels), use the Sound constructor without any parameters. For example: myGlobalSound = new Sound( ); To create a Sound object that controls all the sounds in a particular clip or main movie, supply a target parameter indicating the clip or movie to control. Note that this also controls sounds in clips inside target. For example: spaceshipSound = new Sound("spaceship"); // Control sounds in spaceship clip mainSound = new Sound("_root"); // Control sounds on main timeline To make an individual sound that can be started, stopped, and looped independently, create any kind of Sound object and then attach a sound to it using the attachSound( ) method. See AlsostopAllSounds( ); _soundbuftime
AvailabilityFlash 5 SynopsissoundObject.attachSound(linkageIdentifier) Arguments
DescriptionThe attachSound( ) method adds a new sound to a movie at runtime and places the new sound under soundObject's control. Once attached, the sound may be started and stopped individually by invoking start( ) and stop( ) on soundObject. In order for a sound to be attached to soundObject, the sound must be exported from the movie's Library. To export a sound, follow these steps:
Note that all exported sounds are loaded in the first frame of the movie that contains them (not when they are actually attached or played via ActionScript), which can cause long load delays if the sounds are large. You can gain better control over the loading of sounds by placing them in external .swf files and using loadMovie( ) to import them as necessary. UsageOnly one sound may be attached to a Sound object at a time. Attaching a new sound to a Sound object replaces any sound previously attached to that object. Note that attachSound( ) will not work in movies loaded into a clip or a level via loadMovie( ) unless the attached sound is available in the Library of the document to which the Sound object is scoped. Global sound objects created without a target parameter are scoped to _level0. ExampleThe following example adds a sound with the identifier phaser to the Sound object phaserSound . It then starts and stops the phaser sound: phaserSound = new Sound( ); phaserSound.attachSound("phaser"); // Start the phaser sound phaserSound.start( ); // Stop just the phaser sound phaserSound.stop("phaser"); See AlsoSound.start( ), Sound.stop( )
AvailabilityFlash 5 SynopsissoundObject.getPan() ReturnsA number indicating the last value set by setPan( ). Usually in the range -100 (left channel on, right channel off) to 100 (right channel on, left channel off). Default value is (both left and right channels in equal proportions). DescriptionBy adjusting the pan of a sound, you can create the illusion of a moving sound source. The getPan( ) method is used to determine the current distribution of the left and right channels of the sounds controlled by soundObject. Normally, getPan( ) is used in combination with setPan( ) to adjust the current pan of a sound. ExampleHere we alter the pan of a sound by 20: mySound = new Sound( ); mySound.setPan(mySound.getPan( ) - 20); See AlsoSound.getTransform( ), Sound.setPan( )
AvailabilityFlash 5 SynopsissoundObject.getTransform() ReturnsAn anonymous object whose properties contain the channel percentage values for the sounds controlled by soundObject. DescriptionThe getTransform( ) method returns an object with properties that tell us how the channels in the sounds controlled by soundObject are distributed to the left and right speakers. The properties of the returned object are ll, lr, rl, and rr, as described in the entry for the Sound.setTransform( ) method. See AlsoSound.getPan( ), Sound.setTransform( )
AvailabilityFlash 5 SynopsissoundObject.getVolume() ReturnsA number indicating the current volume as set by setVolume( ). Usually in the range (no volume) to 100 (default volume), but it can be higher. DescriptionThe getVolume( ) method is used to determine the current volume of the sounds controlled by soundObject. Normally, getVolume( ) is used in combination with setVolume( ) to adjust the current volume of a sound. ExampleHere we reduce the volume of a sound by 20: mySound = new Sound( ); mySound.setVolume(mySound.getVolume( ) - 20); See AlsoSound.setVolume( )
AvailabilityFlash 5 SynopsissoundObject.setPan(pan) Arguments
DescriptionThe setPan( ) method dictates the balance of the right and left channels of the sounds controlled by soundObject. By adjusting the pan over time, we can cause a sound to move from one speaker to the other (known as panning). To play the sounds controlled by soundObject in the left speaker only, use a pan of -100. To play the sounds controlled by soundObject in the right speaker only, use a pan of 100. To balance the two channels evenly, use a pan of 0. Note that setPan( ) affects all the sounds controlled by soundObject. If soundObject is a global sound, setPan( ) affects all the sounds in a movie. If soundObject is tied to a clip or a main timeline, setPan( ) affects all the sounds in that clip or timeline and all the clips it contains. The effects of setPan( ) can be changed only by another call to setPan( ). A setPan( ) assignment affects all future sounds controlled by soundObject, even if soundObject is deleted. ExampleThe following clip event handlers cause sounds in a movie clip to endlessly pan between the left and right speakers: onClipEvent (load) { panEffect = new Sound(this); panDirection = "right"; panIncrement = 50; } onClipEvent(enterFrame) { if (panDirection == "right") { newPan = panEffect.getPan( ) + panIncrement; if (newPan > 100) { panDirection = "left"; panEffect.setPan(panEffect.getPan( ) - panIncrement); } else { panEffect.setPan(newPan); } } else { newPan = panEffect.getPan( ) - panIncrement; if (newPan < -100) { panDirection = "right"; panEffect.setPan(panEffect.getPan( ) + panIncrement); } else { panEffect.setPan(newPan); } } } The following clip event handlers cause sounds in a clip to react to the mouse. Assuming a Stage width and height of 550 and 400, the sounds pan left and right with the mouse's horizontal movement and increase or decrease in volume with the mouse's vertical movement: onClipEvent (load) { // Create a new Sound object and attach the sound bgMusic to it mySound = new Sound(this); mySound.attachSound("bgMusic"); mySound.start(0, 999); // Play and loop the sound } onClipEvent (enterFrame) { // Measure the mouse's horizontal location, then set the pan accordingly mouseX = (_root._xmouse / 550) * 200; mySound.setPan(mouseX - 100); // Measure the mouse's vertical location, then set the volume accordingly mouseY = (_root._ymouse / 400) * 300; mySound.setVolume(300 - mouseY); } See Also
AvailabilityFlash 5 SynopsissoundObject.setTransform(transformObject) Arguments
DescriptionThe setTransform( ) method gives us precise control over how the channels in a sound are output to the left and right speakers. In principle, setTransform( ) is not unlike setPan( ), but it provides more detailed sound control over stereo sounds. A stereo sound is a combination of two distinct sounds -- the left channel and the right channel -- which are normally sent separately to the left and right speakers. However, using setTransform( ), we may dictate how much of each channel is broadcast in each speaker. We may, for example, say, "Play half of the left channel in the left speaker, none of the left channel in the right speaker, and all of the right channel in both speakers." Or we may say, "Play all of the left and right channels in the left speaker." To use setTransform( ), we must first create an object with a series of predefined properties. The properties express how to distribute the left and right channels of a stereo sound between the left and right speakers, as described in Table 20-12. Table 20-12. Properties of a transformObject
Once we have created an object with the properties described in Table 20-12, we pass that object to the setTransform( ) method of our Sound object. The values of the properties on our transformObject become the new channel output percentages for the sounds controlled by soundObject. To examine the current percentages of a particular Sound object, we use the Sound.getTransform( ) method. Example// Create a new Sound object mySound = new Sound( ); // Create a new generic object to use with setTransform( ) transformer = new Object( ); // Set the properties of the transform object transformer.ll = 0; // None of left channel in left speaker transformer.lr = 0; // None of right channel in left speaker transformer.rl = 0; // None of left channel in right speaker transformer.rr = 100; // All of right channel in right speaker // Apply the new channel distribution by passing the transform // object to the setTransform( ) method mySound.setTransform(transformer); See AlsoSound.getTransform( ), Sound.setPan( )
AvailabilityFlash 5 SynopsissoundObject.setVolume(volume) Arguments
DescriptionThe setVolume( ) method makes the sounds controlled by soundObject louder or softer. To entirely mute a sound, use a volume of 0. To make a sound louder, increase volume. Values in the range 100-200 are generally quite loud, but there is no predefined maximum. Note that setVolume( ) affects all the sounds controlled by soundObject. If soundObject is a global sound, setVolume( ) affects all the sounds in a movie. If soundObject is tied to a clip or a main timeline, setVolume( ) affects all the sounds in that clip or timeline. The effects of setVolume( ) remain in effect until overridden by another setVolume( ) call. A setVolume( ) assignment affects all future sounds controlled by soundObject, even if soundObject is deleted. ExampleThe first example simply sets the volume of a movie clip: var mySound = new Sound( ); mySound.setVolume (65); The following example shows how to make buttons that adjust a movie's volume level: // CODE ON THE MAIN MOVIE TIMELINE var globalSound = new Sound( ); var maxVolume = 200; var minVolume = 0; var volumeIncrement = 20; // CODE ON VOLUME-UP BUTTON ON MAIN TIMELINE on (release) { globalSound.setVolume(Math.min(globalSound.getVolume( ) + volumeIncrement, maxVolume)); } // CODE ON VOLUME-DOWN BUTTON ON MAIN TIMELINE on (release) { globalSound.setVolume(Math.max(globalSound.getVolume( ) - volumeIncrement, minVolume)); } See AlsoSound.getVolume( )
AvailabilityFlash 5 SynopsissoundObject.start(secondOffset, loops) Arguments
DescriptionThe start( ) method is used to play programmatically-defined sounds that were added to soundObject via attachSound( ). The start( ) method does not play all the sounds in a clip or movie; it plays only the sound most recently attached to soundObject via attachSound( ). To play only a portion of the sound attached to soundObject, use the secondOffset argument. To play the sound attached to soundObject repeatedly, use the loops argument. Example// Create a new Sound object boink = new Sound( ); // Attach a sound exported as boink to the Sound object boink.attachSound("boink"); // Play all of boink; soundOffset defaults to 0 boink.start( ); // Play only a portion of boink, starting 0.5 seconds into it; loops defaults to 1 boink.start(.5); // Play boink three times from beginning to end boink.start(0, 3); See AlsoSound.stop( )
AvailabilityFlash 5 SynopsissoundObject.stop() soundObject.stop(linkageIdentifier) Arguments
DescriptionWhen invoked without a linkageIdentifier, stop( ) silences all sounds controlled by soundObject; if soundObject is a global sound, stop( ) silences all sounds in a movie; if soundObject was created with a target parameter, stop( ) silences all sounds in target. When invoked with a linkageIdentifier, stop( ) silences only the specific sound named by linkageIdentifier. In that case, linkageIdentifier must be a sound that was attached to a Sound object via attachSound( ). However, the sound to stop need not be attached to soundObject itself. It may be attached to any Sound object that shares the same target as soundObject. Or, if soundObject was created with no target (i.e., is a global Sound object), the sound to stop may be attached to any other global Sound object. Example// Create a global Sound object mySound = new Sound( ); // Attach the sound doorbell to the object mySound.attachSound("doorbell"); // Stop all sounds in the movie mySound.stop( ); // Play doorbell mySound.start( ); // Stop just doorbell mySound.stop("doorbell"); // Create another global Sound object myOtherSound = new Sound( ); // Attach a doorknock sound to the object myOtherSound.attachSound("doorknock"); // Play doorknock myOtherSound.start( ); // Now stop the doorknock through mySound, not myOtherSound. // This works because the two Sound objects have the same target. mySound.stop("doorknock"); See AlsoSound.start( )
AvailabilityFlash 4 and later Synopsis_soundbuftime AccessRead/write DescriptionThe _soundbuftime property is an integer specifying the number of seconds of a streamed sound to preload before playing it. The default is 5 seconds. Flash synchronizes movie playback with streaming sounds to ensure that, say, a cartoon character's lips match an accompanying sound track. Animations will pause until _soundbuftime seconds of streaming sound are downloaded; therefore, a long setting can cause excessive startup times on slower connections. Because network streaming may be slow or briefly interrupted, a short _soundbuftime setting can cause sound to skip (i.e., if enough sound data wasn't buffered). The ideal setting will vary from movie to movie based on the complexity of the graphics, the quality settings of the sound, and the bandwidth of the end user's Internet connection. The default setting (5 seconds) usually works well, but experimentation may be required to find the best setting for individual cases. The streaming buffer time can be changed during playback, but it is a global property and cannot be set separately for individual sounds. Example_soundbuftime = 10; // Buffer 10 seconds of audio
AvailabilityFlash 4 and later SynopsisstartDrag(target) startDrag(target, lockCenter) startDrag(target, lockCenter, left, top, right, bottom) Arguments
DescriptionThe startDrag( ) function causes target to visually follow the mouse pointer around in the Player (known as dragging the clip). The movement of a dragging clip can be constrained to a bounding box whose coordinates are provided as arguments to the startDrag( ) function. Bounding box coordinates are given relative to the canvas on which target resides. If that canvas is the main movie Stage, then (0, 0) is the top-left corner of the Stage. If that canvas is a movie clip, then (0, 0) is the registration point of the clip's canvas. Note that Flash's coordinate system reverses the Cartesian Y-axis; y values increase toward the bottom of the screen and decrease toward the top of the screen. Negative y values are above the origin (i.e., above the X-axis). Dragging can be stopped at any time via the stopDrag( ) function. Only one movie clip or movie may be dragged at a time, so issuing a startDrag( ) function on a new target automatically cancels any drag operation already in progress. That said, when a movie or move clip is dragged, all the movie clips it contains are dragged along with it. Example// Drag ball, limiting its movement to the upper-left corner of the Stage startDrag("ball", true, 0, 0, 225, 200); See AlsoMovieclip.startDrag( ), stopDrag( )
AvailabilityFlash 2 and later Synopsisstop() DescriptionThe stop( ) function is a simple but fundamental function that halts the playback of a movie or movie clip. It is the global counterpart of the MovieClip.stop( ) method. It is commonly used to wait for the user to, say, choose from a graphical menu. See AlsoMovieClip.stop( ), play( )
AvailabilityFlash 3 and later SynopsisstopAllSounds() DescriptionThe stopAllSounds( ) function mutes all the sounds currently playing in a movie, no matter how deeply nested in movie clips. This applies to every sound in a movie, including programmatically generated Sound objects. For more precise control over stopping, starting, and setting the volume of sounds, see the Sound class. Note that stopAllSounds( ) has only a temporary effect. Any sound that starts after a stopAllSounds( ) invocation will play normally. There is no way to permanently mute a movie. See AlsoSound.setVolume( ), Sound.stop( )
AvailabilityFlash 4 and later SynopsisstopDrag() DescriptionThe startDrag( ) function causes a movie clip to follow the mouse pointer around the Stage. A stopDrag( ) operation stops a dragging movie clip from following the mouse pointer. Because only one movie clip or movie may be dragged at a time, stopDrag( ) does not require a target argument; it simply cancels any drag operation in progress. Together with startDrag( ), stopDrag( ) is used to create simple drag-and-drop interfaces in Flash, as demonstrated under "Interface Widgets" in the online Code Depot. ExampleThe following button code causes a movie clip to be dragged while the button is pressed and dropped when the button is released: on (press) { startDrag("", true); } on (release) { stopDrag( ); } See AlsoMovieClip.stopDrag( ), startDrag( ), String.toLowerCase( ) ; Section 4.6.8.1, "The toUpperCase( ) function" in Chapter 4, "Primitive Datatypes"
AvailabilityFlash 5 SynopsisString(value) Arguments
ReturnsThe result of converting value to a primitive string. DescriptionThe String( ) function converts its argument to a primitive string value and returns that converted value. The results of converting various types of data to a primitive string are described in Table 3-2. It's normally not necessary to use the String( ) function; ActionScript automatically converts values to the string type when appropriate. Be sure not to confuse the global String( ) function with the String class constructor. The former converts an expression to a string, whereas the later is a class that wraps primitive string data in an object so that properties and methods may be applied to it. UsageNote that the String( ) function sometimes appears in Flash 4 .fla files that have been converted to the Flash 5 format. For information on how datatypes are handled when Flash 4 files are converted to Flash 5, see Section 3.4.4, "Flash 4-to-Flash 5 Datatype Conversion" in Chapter 3, "Data and Datatypes". See AlsoThe String class; Section 3.4.2, "Explicit Type Conversion" in Chapter 3, "Data and Datatypes"
AvailabilityFlash 5 Constructornew String(value) Arguments
Properties
Class MethodsThe following method is invoked through the String class itself, not through an object of the String class:
MethodsThe following object methods are invoked through an instance of the String class:
DescriptionThe String class has several purposes:
UsageIn practice, the String class constructor is used primarily to convert other datatypes to strings. See the global String( ) function for more details. See AlsoSection 4.5, "The String Type" in Chapter 4, "Primitive Datatypes"
AvailabilityFlash 5 Synopsisstring.charAt(index) Arguments
ReturnsThe character in the position index within string. DescriptionThe charAt( ) method determines the character that resides at a certain position (index) in a string. Exampletrace("It is 10:34 pm".charAt(1)); // Displays: "t" (the second letter) var country = "Canada"; trace(country.charAt(0)); // Displays: "C" (the first letter) // This function removes all the spaces from a string and returns the result function stripSpaces (inString) { var outString = ""; for (i = 0; i < inString.length; i++) { if (inString.charAt(i) != " ") { outString += inString.charAt(i); } } return outString; } See AlsoString.charCodeAt( ), String.indexOf( ), String.slice( ); Section 4.6.5.2, "The charAt( ) function" in Chapter 4, "Primitive Datatypes"
AvailabilityFlash 5 Synopsisstring.charCodeAt(index) Arguments
ReturnsAn integer representing the Latin 1 or Shift-JIS code point, as shown in Appendix B, "Latin 1 Character Repertoire and Keycodes", of the character in the position index within string. Examplevar msg = "A is the first letter of the Latin alphabet."; trace(msg.charCodeAt(0)); // Displays: 65 (the code for the "A" character) trace(msg.charCodeAt(1)); // Displays: 32 (the code for the space character) See AlsoString.charAt( ), String.fromCharCode( ); Appendix B, "Latin 1 Character Repertoire and Keycodes", Section 4.6.9.2, "The charCodeAt( ) function" in Chapter 4, "Primitive Datatypes"
AvailabilityFlash 5 Synopsisstring.concat(value1, value2,...valuen) Arguments
ReturnsThe result of concatenating string with value1, value2, ...valuen . DescriptionThe concat( ) method creates a string from a series of values. It is equivalent to using the concatenation operator (+) with strings but is sometimes preferred for clarity, as the + operator can also be used to add numbers. For details on concat( ), see Chapter 4, "Primitive Datatypes". UsageNote that concat( ) does not modify string ; it returns a completely new string. Examplevar greeting = "Hello"; excitedGreeting = greeting.concat("!"); trace(greeting); // Displays: "Hello" trace(excitedGreeting); // Displays: "Hello!" var x = 4; // Initialize x as an integer trace(x + 5); // Displays: 9 trace(x.concat(5)); // Fails because x is not a string. trace(String(x).concat(5)); // Displays: "45" var x = "4"; // Initialize x as a string trace(x.concat(5)); // Displays: "45" trace(concat("foo", "fee")); // Fails because concat( ) must be invoked // as a method of a string. See AlsoThe + operator, in Chapter 5, "Operators", Section 4.6.1.1, "The concat( ) function" in Chapter 4, "Primitive Datatypes"
AvailabilityFlash 5 SynopsisString.fromCharCode(code_ point1, code_ point2,...code_ pointn) Arguments
ReturnsA string formed by concatenating the characters represented by the specified code points. DescriptionThe fromCharCode( ) class method produces a character or series of characters from character code points as described in Chapter 4, "Primitive Datatypes". Example// Makes a copyright symbol, followed by the year (2001) copyNotice = String.fromCharCode(169) + " 2001"; See AlsoString.charCodeAt( ); Appendix B, "Latin 1 Character Repertoire and Keycodes", Section 4.6.9.1, "The fromCharCode( ) function" in Chapter 4, "Primitive Datatypes"
AvailabilityFlash 5 Synopsisstring.indexOf(substring) string.indexOf(substring, startIndex) Arguments
ReturnsThe position of the first occurrence of substring in string (starting at startIndex). Returns -1 if substring is not found at or after startIndex in string. DescriptionThe indexOf( ) method is used to search for characters in strings or to check whether a string contains a certain substring. Example// Check if an email address contains an @ sign var email = "derekaol.com"; if (email.indexOf("@") == -1) { trace ("This isn't a valid email address"); } // Check if an email address has an @ sign and is from the domain aol.com var email = "derek@aol.com"; var atPos = email.indexOf("@"); if (atPos != -1 && email.indexOf("aol.com") == atPos + 1) { gotoAndStop("AOLuserOffer"); } The following code shows a generic function that checks for a keyword in a string, as you might need when grading a fill-in-the-blank quiz: // Generic function to search origStr for any occurrence // of searchStr using a case-insensitive comparison function search (origStr, searchStr) { var origStr = origStr.toLowerCase( ); var searchStr = searchStr.toLowerCase( ); return origStr.indexOf(searchStr) != -1; } var answer = "einstein"; var guess = "Dr. Albert Einstein"; // Increment score if guess contains "einstein" if (search(guess, answer)) { score++; } See AlsoString.charAt( ), String.lastIndexOf( ); Section 4.6.5.3, "The indexOf( ) function" in Chapter 4, "Primitive Datatypes"
AvailabilityFlash 5 Synopsisstring.lastIndexOf(substring) string.lastIndexOf(substring, startIndex) Arguments
ReturnsThe position of the last occurrence of substring in string prior to startIndex. Returns -1 if substring is not found prior to startIndex in string. DescriptionThe lastIndexOf( ) method is used to search for the last occurrence of a substring in a string or to check whether a string contains a certain substring. ExampleURL = "http://www.moock.org/webdesign/flash/fillthewindow.html"; // Finds the last slash character lastSlash = URL.lastIndexOf("/"); // Extracts the filename from the URL file = URL.substring(lastSlash + 1); trace(file); // Displays: fillthewindow.html See AlsoString.charAt( ), String.indexOf( ); Section 4.6.5.4, "The lastIndexOf( ) Function" in Chapter 4, "Primitive Datatypes"
AvailabilityFlash 5 Synopsisstring.length AccessRead-only DescriptionThe length property returns the number of characters in string. Note that a null character (ASCII 0) does not signal the end of a string, as it would in some languages, but neither is it counted in the string's length. For example: // Create the string "A" + null + "B" var myString = String.fromCharCode(65,0,66); trace(myString.length); // Displays: 2 (The null character is ignored) Examplevar myString = "hello"; trace (myString.length); // Displays: 5 trace ("hello".length); // Displays: 5 // Here we convert the number 1000 to a // string in order to test its length var age = 1000; // Display an error message if the number has the wrong number of digits. if (String(age).length != 2) { trace ("Please enter a two-digit number"); } See AlsoArray.length( ); Section 4.6.5.1, "The length property" in Chapter 4, "Primitive Datatypes"
AvailabilityFlash 5 Synopsisstring.slice(startIndex, endIndex) Arguments
ReturnsA substring of string, starting at startIndex and ending at endIndex-1, where both startIndex and endIndex are zero-relative. DescriptionThe slice( ) method is one of three methods that can be used to extract a substring from a string (the others being substring( ) and substr( ) ). The slice( ) method offers the option of negative start and end index values, which allows us to extract a substring by measuring back from the end of a string. UsageNote that slice( ) does not modify string ; it returns a completely new string. Examplevar fullName = "Steven Sid Mumby"; middleName = fullName.slice(7, 10); // Assigns "Sid" to middleName middleName = fullName.slice(-9, -6); // Also assigns "Sid" to middleName See AlsoString.substr( ), String.substring( ); Section 4.6.6.3, "The slice( ) function" and Section 4.6.7, "Combining String Examination with Substring Extraction" in Chapter 4, "Primitive Datatypes"
AvailabilityFlash 5 Synopsisstring.split(delimiter) Arguments
ReturnsAn array whose elements contain the substrings formed by breaking string into segments demarcated by delimiter. DescriptionThe split( ) method breaks a string into substrings, assigns those substrings to the elements of an array, and returns that array. Contiguous occurrences of delimiter without intervening characters result in empty elements. For example, the following code: owners = "terry,doug,,,jon"; ownersArray = owners.split(","); assigns the following elements to ownersArray (elements 2 and 3 contain undefined): 0: terry 1: doug 2: 3: 4: jon The split( ) method is typically used to convert a string received from a CGI script or text file into an array for further manipulation. It is also useful when parsing the parameters of an asfunction call from an HMTL text field <A> tag, which can pass only one string argument to a function. See Section 18.5.14, "Calling ActionScript Functions from HTML Links" in Chapter 18, "On-Screen Text Fields", for example code. Common delimiters include the comma and the Tab character. ExampleSuppose we store a list of names in a text file named names.txt. Each name is separated from the others by a Tab character, as implied by the whitespace shown: owners=terry doug jon On frame 1 of our movie, we load the names.txt file into our movie: this.loadVariables("names.txt"); After ensuring that names.txt has fully loaded (see Section 10.10.4, "data" in Chapter 10, "Events and Event Handlers"), we split the loaded owners variable into an array: splitString = String.fromCharCode(9); // Assign the Tab character to splitString ownersArray = owners.split(splitString); trace(ownersArray[1]); // Displays: "doug" Note that split( ) can take a long time to execute with large bodies of text. If performance is a problem, break your data into manageable portions or consider using XML instead. See the XML class. BugsIn Flash 5, using the empty string as a delimiter adds all of string to the first element of the array being generated. According to ECMA-262, an empty string delimiter should cause string to be broken at each character. Similarly, multicharacter delimiters are not recognized by Flash 5 and cause all of string to be assigned to the first element of the returned array. See AlsoArray.join( ); Section 4.6.6.4, "The split( ) function" in Chapter 4, "Primitive Datatypes"
AvailabilityFlash 5 Synopsisstring.substr(startIndex, length) Arguments
ReturnsA substring of string, starting at startIndex and including length characters. If length is omitted, the result contains characters from startIndex to the end of string. DescriptionThe substr( ) method is one of three methods that can be used to extract a substring from a string (the others being slice( ) and substring( ) ). The substr( ) method extracts a string based on the number of characters specified by length, not based on two character indexes. UsageNote that substr( ) does not modify string ; it returns a completely new string. Examplevar fullName = "Steven Sid Mumby"; middleName = fullName.substr(7, 3); // Assigns "Sid" to middleName firstName = fullName.substr(0, 6); // Assigns "Steven" to firstName lastName = fullName.substr(11); // Assigns "Mumby" to lastName // Notice the negative starting indexes... middleName = fullName.substr(-9, 3); // Assigns "Sid" to middleName firstName = fullName.substr(-16, 6); // Assigns "Steven" to firstName lastName = fullName.substr(-5); // Assigns "Mumby" to lastName See AlsoString.slice( ), String.substring( ); Section 4.6.7, "Combining String Examination with Substring Extraction" and Section 4.6.6.2, "The substr( ) function" in Chapter 4, "Primitive Datatypes"
AvailabilitySynopsisstring.substring(startIndex, endIndex) Arguments
ReturnsA substring of string, starting at startIndex and ending at endIndex-1, where both startIndex and endIndex are zero-relative. DescriptionThe substring( ) method is one of three methods that can be used to extract a substring from a string (the others being slice( ) and substr( ) ). The substring( ) function is identical to slice( ) except that it does not allow for negative startIndex and endIndex values, and it automatically reorders the two indexes if endIndex is less than startIndex. UsageNote that substring( ) does not modify string ; it returns a completely new string. Example// Extract names from a string var fullName = "Steven Sid Mumby"; middleName = fullName.substring(7, 10); // Assigns "Sid" to middleName middleName = fullName.substring(10, 7); // Assigns "Sid" to middleName // (indexes are swapped automatically) firstName = fullName.substring(0, 6); // Assigns "Steven" to firstName lastName = fullName.substring(11); // Assigns "Mumby" to lastName The following example is a reusable function to search for and replace all occurrences of a substring within a string: // A Search-and-Replace Function function replace (origStr, searchStr, replaceStr) { var tempStr = ""; var startIndex = 0; if (searchStr == "") { return origStr; } if (origStr.indexOf(searchStr) != -1) { while ((searchIndex = origStr.indexOf(searchStr, startIndex)) != -1) { tempStr += origStr.substring(startIndex, searchIndex); tempStr += replaceStr; startIndex = searchIndex + searchStr.length; } return tempStr + origStr.substring(startIndex); } else { return origStr; } } msg = "three times three is four"; trace(replace(msg, "three", "two")); // Displays: "two times two is four" See AlsoString.slice( ), String.substr( ); Section 4.6.7, "Combining String Examination with Substring Extraction" and Section 4.6.6.2, "The substr( ) function" in Chapter 4, "Primitive Datatypes"
AvailabilityFlash 5 Synopsisstring.toLowerCase() ReturnsThe lowercase equivalent of string as a new string. Characters without a lowercase equivalent are left unchanged. DescriptionThe toLowerCase( ) method creates a new, lowercase version of string ; it can be used for formatting or to facilitate case-insensitive character comparisons. The toLowerCase( ) method converts only characters in the range A-Z (it does not convert characters with diacritical marks such as accents and umlauts). UsageNote that toLowerCase( ) does not modify string ; it returns a completely new string. Example// Set msg to "this sentence has mixed caps!" msg = "ThiS SenTencE Has MixED CaPs!".toLowerCase( ); // Perform a case-insensitive comparison of two strings function caseInsensitiveCompare (stringA, stringB) { return (stringA.toLowerCase() == stringB.toLowerCase( )); } trace(caseInsensitiveCompare("Colin", "colin")); // Displays: true See AlsoString.toUpperCase( ); Section 4.6.8.2, "The toLowerCase( ) function" in Chapter 4, "Primitive Datatypes"
AvailabilityFlash 5 Synopsisstring.toUpperCase() ReturnsThe uppercase (a.k.a. ALL CAPS) equivalent of string as a new string. Characters without an uppercase equivalent are left unchanged. DescriptionThe toUpperCase( ) method creates a new, uppercase version of string ; it can be used for formatting or to facilitate case-insensitive character comparisons. The toUpperCase( ) method converts only characters in the range a-z (it does not convert characters with diacritical marks such as accents and umlauts). UsageNote that toUpperCase( ) does not modify string ; it returns a completely new string. Example"listen to me".toUpperCase( ); // Yields the string "LISTEN TO ME" var msg1 = "Your Final Score: 234"; var msg2 = msg1.toUpperCase( ); // Set msg2 to "YOUR FINAL SCORE: 234" See AlsoString.toLowerCase( ) ; Section 4.6.8.1, "The toUpperCase( ) function" in Chapter 4, "Primitive Datatypes"
AvailabilityFlash 5 SynopsistargetPath (movieClip) Arguments
ReturnsA string representing the path to movieClip in absolute terms, using dot notation (e.g., "_level0.myMovie"). DescriptionThe targetPath( ) function returns a movie clip's reference as a string that describes the absolute path to the clip (identical to the return value of MovieClip.valueOf( ) ). The targetPath( ) function is sometimes used to compose placement-sensitive code that operates on a movie clip relative to the timeline upon which the clip resides. BugsNote that the example code given for targetPath( ) in the Flash 5 ActionScript Dictionary does not represent the proper usage of targetPath( ); contrary to what the example implies, it is not a synonym for tellTarget( ). ExampleIf square is a movie clip contained by shapes, which resides on the main timeline of level 0, then inside the shapes clip, the statement: targetPath(square); would return: "_level0.shapes.square" See AlsoMovieClip._target, MovieClip.valueOf( ); Section 13.5.6.6, "The targetPath( ) function" in Chapter 13, "Movie Clips"
AvailabilityFlash 3 and Flash 4; deprecated in Flash 5 in favor of object-oriented syntax or the with statement SynopsistellTarget (target) { statements } Arguments
DescriptionIn Flash 3 and Flash 4, tellTarget( ) was the primary means of communicating between two movie clips (i.e., controlling one from the other). It was used to invoke functions such as play( ), stop( ), and gotoAndStop( ) on remote movie clips. In Flash 4, when variables were added to ActionScript, we could also use tellTarget( ) to get and set remote clip variable values. In Flash 5, these endeavors are better accomplished with the dot operator, ., and the array access operator, []. Another alternative to the tellTarget( ) function is the with statement, described in Chapter 6, "Statements". UsageThe tellTarget( ) function may be better described as a statement because it requires a substatement block. The point, however, is academic, as tellTarget( ) has been deprecated. ExampletellTarget ("ball") { gotoAndStop("redStripes"); _x += 300; } See AlsoSection 6.3.9, "The with Statement"" in Chapter 6, "Statements"; Section 13.5.7, "Whither Tell Target?" and Section 13.1, "The "Objectness" of Movie Clips" in Chapter 13, "Movie Clips"
AvailabilityFlash 2 and later; deprecated in Flash 5 in favor of _quality SynopsistoggleHighQuality() DescriptionSwitches between High quality and Low quality rendering. When set to High, the Flash Player renders lines with antialiased (smooth) edges. When set to Low, the Flash Player renders lines with aliased (jagged) edges. The toggleHighQuality( ) function does not take any arguments; it simply switches between the two possible settings -- "High" and "Low". This is problematic because it doesn't explicitly set the quality to a known setting, nor does it allow for more than two different possible quality settings. As of Flash 5, toggleHighQuality( ) has been deprecated in favor of the global _quality property, which supports Low, Medium, High, and Best rendering settings. See Also_highquality, _quality
AvailabilityFlash 4 and later Synopsistrace(value) Arguments
DescriptionThe trace( ) function is a debugging tool used only within the Test Movie mode of the Flash authoring environment. Though unassuming in nature, trace( ) is actually one of the fundamental components of ActionScript programming; it allows us to check the value of a variable or expression at any point during the playback of a movie. UsageUnfortunately trace( ) can be quite slow. Turn off tracing under File Publish Settings Flash using the Omit Trace Actions option. Exampletrace(firstName); // Output the value of firstName trace(myClip); // Output the path to myClip trace(myClip._x) // Output the x coordinate of myClip trace("hello" + " there"); // Resolve then output the expression See Also
AvailabilityFlash 5 Synopsisunescape(stringExpression) Arguments
ReturnsA new string that is a decoded version of string. DescriptionThe unescape( ) function returns a new string based on string. The new string contains equivalent Latin 1 characters for every occurrence of a two-digit hexadecimal escape sequence prefixed with % in string. The escape( ) and unescape( ) functions are used to encode and decode strings for safe transfer over a network. However, manual use of unescape( ) is rarely necessary as Flash automatically converts URL-encoded text when it is imported via loadVariables( ). Examplevar msg = "hello!"; // Set msgCoded to "hello%21" msgCoded = escape(msg); // Set msgDecoded to "hello!" var msgDecoded = unescape(msgCoded); See Alsoescape( ); Appendix B, "Latin 1 Character Repertoire and Keycodes"
AvailabilityFlash 4 and later (Flash 5's unloadMovie( ) function corresponds to Flash 4's Unload Movie with a target path) SynopsisunloadMovie(target) Arguments
DescriptionThe unloadMovie( ) function is most often used to delete movies from document levels in the Player. For example, if a movie is loaded onto level 1 in the Player, we may remove that movie from the Player as follows: unloadMovie("_level1"); The unloadMovie( ) function can also be used on movie clip instances, in which case it removes the content of the instance but not the instance itself. The instance is left on stage as an empty shell; we may load subsequent movies into that shell. Hence, a single clip can act as a container for dynamic content that is managed through successive loadMovie( ) and unloadMovie( ) executions. See AlsoloadMovie( ), MovieClip.unloadMovie( ), unloadMovieNum( ); Section 13.6, "Removing Clip Instances and Main Movies" and Section 13.8.3.1, "Method versus global function overlap issues" in Chapter 13, "Movie Clips"
AvailabilityFlash 3 and later (Flash 5's unloadMovieNum( ) function corresponds to Flash 3's unload Movie, which worked only with numbered levels) SynopsisunloadMovieNum(level) Arguments
DescriptionThe unloadMovieNum( ) function is nearly identical to unloadMovie( ) except that it requires the target level of the load operation to be specified as a number rather than as a string. This means that unloadMovieNum( ) can only remove movies on document levels, not movie clips. It is normally used when we wish to dynamically assign the level of a movie to unload, as in: var x = 3; unloadMovieNum(x); This can also be achieved using string concatenation with the regular unloadMovie( ) function: unloadMovie("_level" + x); See AlsoloadMovieNum( ), Movieclip.unloadMovie( ), unloadMovie( ); Section 13.6, "Removing Clip Instances and Main Movies" in Chapter 13, "Movie Clips"
AvailabilityFlash 5 SynopsisupdateAfterEvent() DescriptionThe user-input clip event handlers (mouseMove, mouseDown, mouseUp, keyDown, and keyUp) often occur between frame renderings in the Flash Player. To force the screen to reflect visual changes that occur during a user-input clip event handler, we invoke updateAfterEvent( ) within any of those handlers. Note, however, that updateAfterEvent( ) is not an arbitrary screen-refreshing tool; it works only within the user-input clip events. Outside of onClipEvent( ) handlers, it has no effect. ExampleThe following script attached to a movie clip causes the clip to follow the mouse pointer and refreshes the screen every time the pointer moves. Because we refresh the screen every time the pointer moves, the clip following the pointer animates very smoothly: onClipEvent (mouseMove) { _x = _root._xmouse; _y = _root._ymouse; updateAfterEvent( ); } BugsNote that the Flash 5 ActionScript Dictionary incorrectly describes the updateAfterEvent( ) function as accepting a clip event as an argument. It does not accept any arguments. See AlsoSee Section 10.14, "Refreshing the Screen with updateAfterEvent" in Chapter 10, "Events and Event Handlers"
AvailabilityFlash 4 Build 11 and later; deprecated in Flash 5 in favor of get Version Synopsis_root.$version AccessRead-only DescriptionThe $version property contains the same string as the return value of the global getVersion( ) function (operating system, followed by Player version information). The $version property was introduced midway through the life cycle of the Flash 4 Player and has been replaced by the getVersion( ) function. It is technically not a global property, but a property of the main movie timeline; from any other movie clip timeline, it must be accessed as _root.$version. See AlsogetVersion( )
AvailabilityFlash 5 Constructornew XML() new XML(source) Arguments
Properties
Methods
Event Handlers
DescriptionWe use objects of the XML class to manipulate the content of an XML (or HTML) document in an object-oriented manner and to send XML-formatted data to and from Flash. Using the methods and properties of an XML object, we may build an XML-structured document (or read an existing one) and efficiently access, change, or remove the information in that document. The source code of an XML document consists primarily of a series of elements and attributes. For example, in the following XML fragment, the elements BOOK, TITLE, AUTHOR, and PUBLISHER take the same form as well-known HTML tags, and we see that the AUTHOR element supports one attribute, SALUTATION: <BOOK> <TITLE>ActionScript: The Definitive Guide</TITLE> <AUTHOR SALUTATION="Mr.">Colin Moock</AUTHOR> <PUBLISHER>O'Reilly</PUBLISHER> </BOOK> From an object-oriented perspective, the content of an XML document can be treated as a hierarchy of objects in which each element and text block becomes an object node in a flowchart-like structure. Figure 20-1 shows our simple XML <BOOK> fragment represented conceptually as an XML object hierarchy. Figure 20-1. A sample XML node hierarchyLet's consider the structure and semantics of this sample XML object hierarchy from left to right. We start with the main XML object, shown in Figure 20-1 as DOCUMENT, which is created automatically by the XML constructor and serves as the container for our XML object hierarchy. Moving one tier to the right in the hierarchy, we come to BOOK, which is the first element in our XML source code fragment and, in this case, also the first object node under DOCUMENT. The BOOK node is the root of our XML data structure -- every well-formed XML document must have an all-encompassing root element such as BOOK that contains every other element. Branches of an XML object hierarchy are added to the tree either by parsing XML source code or invoking node-addition methods on the objects in the hierarchy. When a node is contained by another node, the contained node is said to be a child of the containing node, which is known as the parent. In our example, BOOK is the first child of DOCUMENT, and DOCUMENT is BOOK's parent. As we move to the right in Figure 20-1, we see that BOOK has seven children, including four #text nodes that do not seem to be present in our original XML document. Each occurrence of whitespace between elements in XML source code is rendered as an object in an XML object hierarchy. If we look closely, we'll find whitespace -- a carriage return and a Tab character -- between BOOK and TITLE in the preceding XML fragment. This whitespace is represented by a #text node in Figure 20-1, which also shows similar whitespace nodes after the TITLE, AUTHOR, and PUBLISHER nodes. BOOK's children are siblings of one another (i.e., they reside on the same level in the hierarchy). For example, we say that AUTHOR's next sibling is #text, and AUTHOR's previous sibling is #text. You can see how the #text nodes get in our way when we're moving from sibling to sibling in a hierarchy. We can deal with these empty whitespace nodes in one of the following ways:
Finally, we move to the last tier in the hierarchy where we find that the TITLE, AUTHOR, and PUBLISHER nodes each has a single child. Each child is a text node, corresponding to the text contained by the elements TITLE, AUTHOR, and PUBLISHER. Notice that the text contained by an element in XML source code resides in a child node of that element in the corresponding object hierarchy. To access text contained by an element, we must always refer to that element's child using either firstChild.nodeValue or childNodes[0].nodeValue, which we'll consider shortly. But what of the element attributes? Where do they appear in our XML object hierarchy? You might expect AUTHOR's SALUTATION attribute to be depicted as a child node called SALUTATION. But in practice, an attribute is not considered a child of the element that defines it, but rather a property of that element. To learn how attribute properties are accessed, see the XML.attributes entry. Let's see how to build an XML document as a hierarchy of node objects. To create a new, blank XML object, we use the XML( ) constructor: myDocument = new XML( ); We can then add nodes to our empty XML object by invoking methods such as appendChild( ), parseXML( ), and load( ) on the object. Alternatively, we may create an XML object from existing XML source in our script by invoking the XML constructor with the source argument: myDocument = new XML(source); For example: myDocument = new XML('<P>hello world!</P>'); When a source argument is supplied to the XML( ) constructor, source is parsed and converted into a new object hierarchy, which is then stored in the object returned by the constructor. (In this case, the node P is assigned as myDocument's first child and the text node with the nodeValue "hello world!" is assigned as P's first child.) Once an XML hierarchy is created and stored in an object, we may access the information in that hierarchy using the methods and properties of the XML class. For example, suppose we want to retrieve the text "hello world!" in myDocument. Thinking in object-oriented terms, we might assume that we could access the text of P as a property of myDocument, as follows: myDocument.P. In fact, that won't work; instead of referring to nodes by name, we use the XML class's built-in properties, such as firstChild and childNodes, to access nodes. For example, to access the P node, we could use: myDocument.firstChild // Accesses P myDocument.childNodes[0] // Also accesses P Because firstChild returns a reference to the first child node of the specified node in the hierarchy, myDocument.firstChild returns a reference to node P. However, we want the text "hello world!" contained by P, not node P itself. As we learned earlier, the text of an element node is stored as a child of that node. Therefore, we can reference the text node (i.e., the first descendant of P), like this: myDocument.firstChild.firstChild // Accesses the text node under P To obtain the value of a node, we use the nodeValue property. For example, we can display the value "hello world!" in the Output window using: trace(myDocument.firstChild.firstChild.nodeValue); Or, we can reassign the value of the text node under P using: myDocument.firstChild.firstChild.nodeValue = "goodbye cruel world"; To remove the P node altogether, add a new node, or move the text "hello world!" to another node, we invoke appropriate methods of the XML class. For example: // Delete P myDocument.firstChild.removeNode( ); // Make a new element named P newElement = myDocument.createElement("P"); // Add the new element to our document myDocument.appendChild(newElement); // Make a new text node to attach to P newText = myDocument.createTextNode("XML is fun"); // Attach the new text node to P myDocument.firstChild.appendChild(newText); As you can see, working with XML-structured data in an object hierarchy is a mediated endeavor. We build, destroy, and manipulate the data by invoking methods on, and accessing properties of, objects. To learn the various tools available for working with XML data, explore the properties and methods of the XML class, which are listed next. ActionScript manipulates XML data using the Document Object Model (DOM) standard published by the World Wide Web Consortium (W3C). For thorough coverage of how the DOM represents XML-structured data as an object hierarchy, consult: For details on the language-independent specifications of the core DOM, see: (pay particular attention to "Interface Node" under 1.2, Fundamental Interfaces). For details on how the DOM is implemented in ECMA-262, see:
ExampleWe've learned that the whitespace between any two elements in XML source code is represented by a text node in the corresponding XML object hierarchy. Prior to Build 41 of the Flash 5 Player, undesired whitespace nodes had to be manually stripped out of an XML object hierarchy. Stripping a particular kind of node is a common task in XML handling and serves as a good example of tree traversal (moving through every node in a hierarchy). Let's consider two different techniques for stripping whitespace nodes from a document. In the first example, we'll use a classic FIFO (First In First Out) stack to add all the nodes in a tree to an array for processing. The stripWhitespaceTraverse( ) function seeds an array of node elements with theNode, which it receives as an argument. Then it enters a loop in which it removes the first node in the array, processes that node, and adds its children (if any) to the array. When the array has no more elements, all the descendants of theNode have been processed. During processing, any node that has no children is considered potential whitespace (because text nodes never have children). Each of these nodes is checked to see if:
Any text nodes containing only characters below ASCII 32 (i.e., only whitespace) are removed: // Strip Whitespace Using a FIFO Stack // Strips any whitespace nodes descending from theNode by traversing the tree function stripWhitespaceTraverse (theNode) { // Create a list of nodes to process var nodeList = new Array( ); // Seed the list with the node passed to the function nodeList[0] = theNode; // Process descendants until there are none left to process while (nodeList.length > 0) { // Remove the first node from the list and assign it to currentNode currentNode = nodeList.shift( ); // If this node has children... if (currentNode.childNodes.length > 0) { // ...add this node's children to the list of nodes to process nodeList = nodeList.concat(currentNode.childNodes); } else { // ...otherwise, this node is the end of a branch, so check if it's a // text node. If so, check if it contains only empty whitespace. // nodeType 3 indicates a text node if (currentNode.nodeType == 3) { var i = 0; var emptyNode = true; for (i = 0; i < currentNode.nodeValue.length; i++) { // A useful character is anything over 32 (space, tab, // new line, etc. are all below). if (currentNode.nodeValue.charCodeAt(i) > 32) { emptyNode = false; break; } } } // If no useful charaters were found, delete the node if (emptyNode) { currentNode.removeNode( ); } } } } The technique shown in the preceding example is traditionally very efficient. However, in the Flash 5 Player, the Array.concat( ) method executes quite slowly. Hence, it's quicker to strip whitespace using the technique shown in the following example. Study the comments carefully: // Strip Whitespace Using Function Recursion // Strips whitespace nodes from an XML document // by passing twice through each level in the tree function stripWhitespaceDoublePass(theNode) { // Loop through all the children of theNode for (var i = 0; i < theNode.childNodes.length; i++) { // If the current node is a text node... if (theNode.childNodes[i].nodeType == 3) { // ...check for any useful characters in the node var j = 0; var emptyNode = true; for (j = 0;j < theNode.childNodes[i].nodeValue.length; j++) { // A useful character is anything over 32 (space, tab, // new line, etc. are all below) if (theNode.childNodes[i].nodeValue.charCodeAt(j) > 32) { emptyNode = false; break; } } // If no useful charaters were found, delete the node if (emptyNode) { theNode.childNodes[i].removeNode( ); } } } // Now that all the whitespace nodes have been removed from theNode, // call stripWhitespaceDoublePass() recursively on its remaining children. for (var k = 0; k < theNode.childNodes.length; k++) { stripWhitespaceDoublePass(theNode.childNodes[k]); } } See AlsoThe XMLnode class, The XMLSocket class; Section 18.5, "HTML Support" in Chapter 18, "On-Screen Text Fields"
AvailabilityFlash 5 SynopsistheNode.appendChild(childNode) Arguments
DescriptionThe appendChild( ) method adds the specified childNode to theNode as theNode's last child. We can use appendChild( ) to add a new node to an existing node, to move a node within a document, or to move a node between documents. In each of these cases, childNode must be a reference to a node object that already exists. To add a new child node to an existing node, we must first create the new child node using createElement( ), createTextNode( ), or cloneNode( ) or by parsing XML source code into an XML object. For example, in the following code, we create a new P node and a new text node. We append the text node to the P node and then append the P node and its text node child to the top node of a document: // Create a document myDoc = new XML('<P>paragraph 1</P>'); // Create a P node and a text node newP = myDoc.createElement("P"); newText = myDoc.createTextNode("paragraph 2"); // Append the text node to the P node newP.appendChild(newText); // Append the P node (including its text child) to myDoc myDoc.appendChild(newP); trace(myDoc); // Displays: "<P>paragraph 1</P><P>paragraph 2</P>" To move a node within a document, specify a childNode that is a reference to an existing node in the document. In this situation, childNode indicates the old location of the node, and theNode indicates the new parent of the node. In the process of being appended to theNode, childNode is removed from its previous parent node. For example, here we move the B node from its parent P node to the root of the document: // Create a new document myDoc = new XML('<P>paragraph 1<B>bold text</B></P>'); // Store a reference to the B node boldText = myDoc.firstChild.childNodes[1]; // Append the B node to the root of the document, while removing it from P myDoc.appendChild(boldText); trace(myDoc); // Displays: "<P>paragraph 1</P><B>bold text</B>" We also could have skipped the reference-storing step and just moved the node directly: myDoc.appendChild(myDoc.firstChild.childNodes[1]); To move a node between documents, childNode should be a reference to a node in the first (source) document and theNode should be a reference to a node in the second (target) document. For example, here we move the B node from myDoc to myOtherDoc: myDoc = new XML('<P>paragraph 1<B>bold text</B></P>'); myOtherDoc = new XML( ); myOtherDoc.appendChild(myDoc.firstChild.childNodes[1]); trace(myDoc); // Displays: "<P>paragraph 1</P>" trace(myOtherDoc); // Displays: "<B>bold text</B>" See AlsoXML.createElement( ), XML.createTextNode( ), XML.cloneNodee( ), XML.insertBefore( )
AvailabilityFlash 5 SynopsistheNode.attributes.attributeIdentifier theNode.attributes[attributeNameInQuotes] AccessRead/write DescriptionThe attributes property stores the names and values of attributes defined by theNode. For example, the ALIGN attribute of this P tag: <P ALIGN="CENTER">this is a paragraph</P> is accessed using theNode.attributes.ALIGN or theNode.attributes["ALIGN"]. If the P tag were the only tag in our XML source, we could access the ALIGN attribute as follows: // Create an XML object hierarchy myDoc = new XML('<P ALIGN="CENTER">this is a paragraph</P>'); // Access the ALIGN attribute. Displays: "CENTER" trace(myDoc.firstChild.attributes.ALIGN); // Set the ALIGN attribute myDoc.firstChild.attributes.ALIGN = "LEFT"; The attributes property is itself an object. We can add new properties to the attributes object, thereby adding new attributes to theNode, as follows: // Add a CLASS attribute to the P tag myDoc.firstChild.attributes.CLASS = "INTRO"; // firstChild now represents the XML source: // <P ALIGN="CENTER" CLASS="INTRO">this is a paragraph</P> Because attributes is not an array, it doesn't contain a length property. Instead, we can access all the attributes defined on an element using a for-in loop: var count = 0; for(var prop in theNode.attributes) { trace("attribute " + prop + " has the value " + theNode.attributes[prop]); count++; } trace ("The node has " + count + " attributes."); If the XML element represented by theNode has no attributes, attributes is an empty object with no properties and the preceding example would indicate zero attributes. See AlsoXML.nodeType
AvailabilityFlash 5 SynopsistheNode.childNodes[n] AccessRead-only DescriptionThe childNodes property is an array whose elements contain references to the immediate descendants of theNode. It is used to access nodes in an XML hierarchy. For example, if we create an object hierarchy as follows: myDoc = new XML('<STUDENT><NAME>Tim</NAME><MAJOR>BIOLOGY</MAJOR></STUDENT>'); We can then access the STUDENT node using: myDoc.childNodes[0]; We can access the NAME and MAJOR nodes (which are descendants of STUDENT) using: myDoc.childNodes[0].childNodes[0]; // NAME myDoc.childNodes[0].childNodes[1]; // MAJOR If the hierarchy below theNode changes, childNodes is automatically updated to reflect the new structure. For example, if we deleted the MAJOR node, myDoc.childNodes[0].childNodes[1] would return undefined. We often refer to nodes to manipulate information or rearrange a document's structure. For example, we might change a student's name or add a new student using: // Check the name of the student trace("The student's name is: " + myDoc.childNodes[0].childNodes[0].childNodes[0].nodeValue); // Change the name of the student myDoc.childNodes[0].childNodes[0].childNodes[0].nodeValue = "James"; // Copy the STUDENT node newStudent = myDoc.childNodes[0].cloneNode(true); // Add a new STUDENT node to the document myDoc.appendChild(newStudent); Note that as a convenience, we may also use the firstChild property to refer to childNodes[0]. The following references are identical: myDoc.childNodes[0]; myDoc.firstChild; To iterate through all the children of a node, we can use a for statement, as follows: for (var i = 0; i < theNode.childNodes.length; i++) { trace("child " + i + " is " + theNode.childNodes[i].nodeName); } However, our example traverses only the first level of theNode's hierarchy. The examples under the XML.nextSibling entry shows how to access all the nodes below theNode. If theNode has no children, theNode.childNodes.length is 0. UsageRemember that empty text nodes, representing the whitespace used to format XML source code, also show up in a childNode list. For example, in the following XML source, empty text nodes will be created by the whitespace after the BOOK start tag and the TITLE, AUTHOR, and PUBLISHER end tags: <BOOK> <TITLE>ActionScript: The Definitive Guide</TITLE> <AUTHOR SALUTATION="Mr">Colin Moock</AUTHOR> <PUBLISHER>O'reilly</PUBLISHER> </BOOK> Hence, the first child node of BOOK is an empty text node; the second child is TITLE. See AlsoXML.firstChild, XML.hasChildNodes( ), XML.lastChild, XML.nextSibling, XML.previousSibling
AvailabilityFlash 5 SynopsistheNode.cloneNode(deep) Arguments
ReturnsA duplicate of the theNode object, optionally including its subtree. DescriptionThe cloneNode( ) method creates and returns a copy of theNode, including all of theNode's attributes and values if theNode is an element node. If deep is true, the returned copy includes the entire node hierarchy descending from theNode. We often use cloneNode( ) to create a new node based on an existing template (which saves us from generating the new node structure manually). Once we've cloned a node, we normally customize it and insert it into an existing XML document using either appendChild( ) or insertBefore( ). The following example clones the first paragraph of a document to make a sibling paragraph with the same structure: // Create a new document myDoc = new XML('<P>paragraph 1</P>'); // Make a clone of the first paragraph newP = myDoc.firstChild.cloneNode(true); // Customize the clone newP.firstChild.nodeValue = "paragraph 2"; // Add the clone into the document myDoc.appendChild(newP); trace(myDoc); // Displays: "<P>paragraph 1</P><P>paragraph 2</P>" Note that the text in an element is stored in a separate child node of that element, so we must set deep to true to preserve an element's text content in a clone operation. Remember that cloneNode( ) does not insert the element it returns into the node's document -- we must do that ourselves using appendChild( ) or insertBefore( ). See AlsoXML.appendChild( ), XML.createElement( ), XML.createTextNode( ), XML.insertBefore( )
AvailabilityFlash 5 Build 41 or later SynopsisXMLdoc.contentType AccessRead/write DescriptionThe contentType property is the MIME type that is sent to a server when XML.send( ) or XML.sendAndLoad( ) is invoked. It defaults to application/x-www-urlform-encoded. The contentType property may be modified for specific XML objects, or XML.prototype.contentType may be modified to affect all XML objects. The contentType property first appeared in Build 41 of the Flash 5 Player, before which it was not possible to set MIME type. Check contentType's validity by comparing it to undefined or using the getVersion( ) function to determine the Player version and build. UsageSee important notes on setting MIME type under the XML.send( ) entry. See AlsoXML.send( ), XML.sendAndLoad( )
AvailabilityFlash 5 SynopsisXMLdoc.createElement(tagName) Arguments
ReturnsA new element node object, with no parent and no children. DescriptionThe createElement( ) method is our primary means of generating new element nodes for inclusion in an XML document object hierarchy. Note that createElement( ) does not insert the element it returns into XMLdoc -- we must do that ourselves using appendChild( ) or insertBefore( ). For example, here we create and insert a new P element into a document: myDoc = new XML( ); newP = myDoc.createElement("P"); myDoc.appendChild(newP); We can combine those steps like this: myDoc.appendChild(myDoc.createElement("P")); XMLdoc must be an instance of the XML class, not the XMLnode class. The createElement( ) method cannot be used to create text nodes; use createTextNode( ) instead. See AlsoXML.appendChild( ), XML.cloneNode( ), XML.createTextNode( ), XML.insertBefore( )
AvailabilityFlash 5 SynopsisXMLdoc.createTextNode(text) Arguments
ReturnsA new text node object, with no parent and no children. DescriptionThe createTextNode( ) method is our primary means of generating new text nodes for inclusion in an XML document object hierarchy. Note that createTextNode( ) does not insert the element it returns into XMLdoc -- we must do that ourselves using appendChild( ) or insertBefore( ). For example, here we create and insert a new P element into a document, and then we give that P element a text-node child: myDoc = new XML( ); newP = myDoc.createElement("P"); myDoc.appendChild(newP); newText = myDoc.createTextNode("This is the first paragraph"); myDoc.firstChild.appendChild(newText); trace(myDoc); // Displays: "<P>This is the first paragraph</P>" XMLdoc must be an instance of the XML class, not the XMLnode class. Text nodes are normally stored as the children of element nodes, which are created using createElement( ). See AlsoXML.appendChild( ), XML.cloneNode( ), XML.createElement( ), XML.insertBefore( )
AvailabilityFlash 5 SynopsisXMLdoc.docTypeDecl AccessRead/write DescriptionThe docTypeDecl string property specifies the DOCTYPE tag of XMLdoc, if any exists. Otherwise, docTypeDecl is undefined . XMLdoc must be the top-level node in an XML object hierarchy (i.e., an instance of the XML class, not the XMLnode class). An XML document's DOCTYPE specifies the name and location of the DTD used to validate the document. ActionScript does not perform validation of XML documents; it merely parses them. We use the DOCTYPE tag to build XML documents that may be validated externally or to identify the type of a loaded XML document. Examplevar myXML = new XML('<?xml version="1.0"?><!DOCTYPE foo SYSTEM "bar.dtd">' + '<P>a short document</P>'); trace(myXML.docTypeDecl); // Displays: "<!DOCTYPE foo SYSTEM "bar.dtd">" // Set a new DOCTYPE myXML.docTypeDecl = '<!DOCTYPE baz SYSTEM "bam.dtd">'; See AlsoXML.xmlDecl
AvailabilityFlash 5 SynopsistheNode.firstChild AccessRead-only DescriptionThe firstChild property is synonymous with childNodes[0]. It returns a reference to the first node object that descends from theNode. If theNode has no children, firstChild returns null. In this XML source fragment, the firstChild of the MESSAGE node is the text node with the nodeValue "hey": <!-- Fragment 1 --> <MESSAGE>hey</MESSAGE> Here, the firstChild of the HOTEL node is the ROOM node: <!-- Fragment 2 --> <HOTEL><ROOM><SIZE>Double</SIZE></ROOM></HOTEL> When theNode is the top of the object hierarchy (i.e., refers to the XML document object), firstChild may not always be a reference to the first useful element in the document. If a document includes an XML delcaration (<?xml version="1.0"?>) and perhaps a DOCTYPE tag, there are normally whitespace nodes before the actual root element of the XML hierarchy. However, if an XML fragment has no XML declaration and no DOCTYPE, we can start processing it with the document's firstChild node, as in: // Create a new XML fragment myDoc = new XML('<MESSAGE><USER>gray</USER><CONTENT>hi</CONTENT></MESSAGE>'); // Store the XML fragment's first node in the variable msg msg = myDoc.firstChild; // Assign the text contained by the USER tag // to a text field called userNameOutput userNameOutput = msg.firstChild.firstChild.nodeValue; It's good form, but not actually necessary, to use nodeValue to access the text contained by the USER tag. When we use a text-node object in a string context, the toString( ) method is automatically invoked on that node, and the text in the node is returned. See AlsoXML.childNodes, XML.lastChild, XML.nextSibling, XML.previousSibling
AvailabilityFlash 5 SynopsistheNode.hasChildNodes() ReturnsA Boolean: true if theNode has any children; false if it does not. DescriptionThe hasChildNodes( ) method indicates whether any node hierarchy extends from a given node. It is synonymous with the comparison expression: theNode.childNodes.length > 0 If theNode contains no subnodes, hasChildNodes( ) returns false. ExampleWe can use hasChildNodes( ) to determine whether to operate on a node during node processing. For example, here we remove the nodes below the first child of a document until the first child has no more children: while (myDoc.firstChild.hasChildNodes( )) { myDoc.firstChild.firstChild.removeNode( ); } See AlsoXML.childNodes
AvailabilityFlash 5 Build 41 or later SynopsisXMLdoc.ignoreWhite AccessRead/write DescriptionThe ignoreWhite property stores a Boolean that dictates whether to discard text nodes containing only whitespace during the parsing process. The default value is false (don't throw away whitespace nodes). This is a global setting that applies to an entire XML document, not just a specific node. That is, instances of the XMLnode class do not support ignoreWhite. ExampleTo cause a single XML document to discard whitespace nodes during parsing, use: myXML.ignoreWhite = true; To cause all XML documents to discard whitespace nodes, use: XML.prototype.ignoreWhite = true; The ignoreWhite property should be set before any attempt at parsing XML occurs (typically due to a load( ) or sendAndLoad( ) operation). See AlsoSee the examples under the XML Class entry for manual whitespace-stripping code
AvailabilityFlash 5 SynopsistheNode.insertBefore(newChild, beforeChild) Arguments
DescriptionThe insertBefore( ) method adds newChild to theNode's child list, before beforeChild . The insertBefore( ) method is similar to appendChild( ) but lets us precisely position a new node in an existing XML object hierarchy. Example// Create a document myDoc = new XML('<P>paragraph 2</P>'); // Create a P node and a text node newP = myDoc.createElement("P"); newText = myDoc.createTextNode("paragraph 1"); // Append the text node to the P node newP.appendChild(newText); // Insert the new P node (including its text child) before the existing P myDoc.insertBefore(newP, myDoc.firstChild); trace(myDoc); // Displays: "<P>paragraph 1</P><P>paragraph 2</P>" See AlsoXML.appendChild( )
AvailabilityFlash 5 SynopsistheNode.lastChild AccessRead-only DescriptionThe lastChild property is synonymous with childNodes[childNodes.length-1]. It returns a reference to the last node object that descends from theNode. If theNode has no children, lastChild returns null. In the following XML source fragment, the lastChild of the MESSAGE node is the CONTENT node: <MESSAGE><USER>gray</USER><CONTENT>hi</CONTENT></MESSAGE> Example// Create a new XML document myDoc = new XML('<MESSAGE><USER>gray</USER><CONTENT>hi</CONTENT></MESSAGE>'); // Sets msg to "hi" because myDoc's firstChild // is MESSAGE, MESSAGE's lastChild is CONTENT, and CONTENT's firstChild // is the text node with the value "hi" msg = myDoc.firstChild.lastChild.firstChild.nodeValue See AlsoXML.childNodes, XML.firstChild, XML.nextSibling, XML.previousSibling
AvailabilityFlash 5 SynopsisXMLdoc.load(URL) Arguments
DescriptionThe load( ) method imports an external XML document, parses it, converts it into an XML object hierarchy, and places that hierarchy into XMLdoc. Any previous contents of XMLdoc are replaced by the newly loaded XML content. XMLdoc must be an instance of the XML class, not the XMLnode class. UsageBefore accessing content imported with load( ), we must be sure the load and parsing operations are complete. To do so, either check the value of the XML document's loaded property, or assign the document an onLoad( ) callback handler to respond to the load completion. See the XML.loaded and XML.onLoad( ) entries for details. To determine whether the loaded data was successfully parsed, check the document's status property. XML.load( ) is subject to the domain-based security restrictions described in Table 20-8 under the global loadVariables( ) function. ExamplemyDoc = new XML( ); myDoc.load("myData.xml"); See AlsoXML.loaded, XML.onLoad( ), XML.sendAndLoad( ), XML.status
AvailabilityFlash 5 SynopsisXMLdoc.loaded AccessRead-only DescriptionThe loaded property returns a Boolean value indicating whether a previously invoked load( ) or sendAndLoad( ) operation on XMLdoc has completed. It is immediately set to false when an XML load( ) or sendAndLoad( ) operation is initiated. If the load is successful, loaded is later set to true. If no such operation has ever been executed on XMLdoc, loaded is undefined. When loaded is false, the download and parsing of XML data is still in progress, and attempts to access the object hierarchy in XMLdoc will fail. When loaded is true, XML data has finished being downloaded, parsed, and stored in XMLdoc as an object hierarchy. Note, however, that the loaded XML data may not have been parsed successfully (use XMLdoc.status to determine whether it was). XMLdoc must be an instance of the XML class, not the XMLnode class. ExampleThe following example shows a basic XML preloader that waits for the XML data to be loaded before displaying it (XML preloaders may also be built using an XML.onLoad( ) handler): // CODE ON FRAME 1 // Create a new XML document myDoc = new XML( ); // Load an external XML file into the document myDoc.load("userProfile.xml"); // CODE ON FRAME 5 // Check if the data has loaded. If so, go to the display frame. // If not, loop back to frame 4 and then play. // Loop until the data is done loading... if (myDoc.loaded) { if (myDoc.status == 0) { gotoAndStop("displayData"); } else { gotoAndStop("loadingError"); } } else { gotoAndPlay(4); } See AlsoXML.load( ), XML.onLoad( ), XML.sendAndLoad( )
AvailabilityFlash 5 SynopsistheNode.nextSibling AccessRead-only DescriptionThe nextSibling property returns the node object after theNode in the current level of the XML object hierarchy. If there is no node after theNode, nextSibling returns null. In the following XML source fragment, the CONTENT node is the nextSibling of the USER node: <MESSAGE><USER>gray</USER><CONTENT>hi</CONTENT></MESSAGE> ExampleThe nextSibling property is typically used to traverse (move through) an XML object hierarchy. For example, to view all the children of theNode in the order they appear, we may use: for (var child = theNode.firstChild; child != null; child = child.nextSibling) { trace("found node: " + child.nodeName); } By extending our loop into a function, we can recursively traverse every node in an XML object hierarchy, as follows: function showNodes (node) { trace(node.nodeName + ": " + node.nodeValue); for (var child = node.firstChild; child != null; child = child.nextSibling) { showNodes(child); } } // Invoke the function on our node or document showNodes(myDoc); Note that in both traversal examples shown, text nodes show up without a name as described under the nodeName entry. See AlsoXML.childNodes, XML.firstChild, XML.lastChild, XML.nodeName, XML.nodeValue, XML.previousSibling
AvailabilityFlash 5 SynopsistheNode.nodeName AccessRead/write DescriptionThe nodeName string property reflects the name of theNode. Since only two node types are supported by ActionScript (element nodes and text nodes), nodeName has only two possible values:
ExampleWe can use nodeName to check whether the current node is the type of element we're seeking. For example, here we extract all the content of H1 tags on the first level of an XML document (this example checks only for tags named H1, not for tags named h1 with a lowercase h): myDoc = new XML('<H1>first heading</H1><P>content</P>' + '<H1>second heading</H1><P>content</P>'); for (i = 0; i < myDoc.childNodes.length; i++) { if (myDoc.childNodes[i].nodeName == "H1") { trace(myDoc.childNodes[i].firstChild.nodeValue); } } See AlsoXML.nodeType, XML.nodeValue
AvailabilityFlash 5 SynopsistheNode.nodeType AccessRead-only DescriptionThe nodeType is an integer property that returns theNode's type. Since only two node types are supported by ActionScript -- element nodes and text nodes -- nodeName has only two possible values: 1, if the node is an element node; and 3, if the node is a text node. These values may seem arbitrary, but they are actually the appropriate values as stipulated by the DOM. For reference, the other node types in the DOM are listed in Table 20-13. Table 20-13. DOM Node Types
*Supported by Flash. Technically, ActionScript implements so-called attribute, document, and document_type nodes in addition to element and text nodes, but we don't have direct access to them as objects. For example, we may manipulate the attributes of a node through the attributes property, but we do not have direct access to attribute nodes themselves. Similarly, we have access to the DOCTYPE tag of a document through the docTypeDecl property, but we do not have direct access to document_type itself. Element nodes correspond to XML or HTML tags. For example, in the XML fragment <P>what is your favorite color?</P>, the P tag would be represented in an XML object hierarchy as an element node (nodeType 1). The text contained by a tag in XML source code -- for example, the text "what is your favorite color?" -- would be represented as a text node (nodeType 3). ExampleWe can conditionally operate on a node based on its nodeType. For example, here we remove all the empty text nodes that are children of theNode : // Loop through all children of theNode for (i = 0; i < theNode.childNodes.length; i++) { // If the current node is a text node... if (theNode.childNodes[i].nodeType == 3) { // Check for any useful characters in the node var j = 0; var emptyNode = true; for (j = 0; j < theNode.childNodes[i].nodeValue.length; j++) { // Useful character codes start above ASCII 32 if (theNode.childNodes[i].nodeValue.charCodeAt(j) > 32) { emptyNode = false; break; } } // No useful charaters were found, so delete the node theNode.childNodes[i].removeNode( ); } } See AlsoThe XML Class, XML.nodeName, XML.nodeValue
AvailabilityFlash 5 SynopsistheNode.nodeValue AccessRead/write DescriptionThe nodeValue property reflects the string value of theNode. Since only two node types (element nodes and text nodes) are supported by ActionScript, nodeValue has only two possible values:
In practice, nodeValue is normally used only with text nodes. To assign new text to an existing text node, we use nodeValue as follows: // Create a new XML document myDoc = new XML('<H1>first heading</H1><P>content</P>'); // Change the text contained by the H1 tag myDoc.firstChild.firstChild.nodeValue = "My Life Story"; Although we may explicitly retrieve the value of a text node using nodeValue, the toString( ) method implicitly returns a node's value when it is used in a string context. Therefore, this code displays the text node's text in the Output window: trace(myDoc.firstChild.firstChild); See AlsoXML.nodeName, XML.nodeType
AvailabilityFlash 5 (undocumented) SynopsisXMLdoc.onData(src); Arguments
DescriptionThe onData( ) handler executes automatically whenever raw XML source has finished loading into XMLdoc due to an earlier load( ) or sendAndLoad( ) invocation. By default, onData( ) has the following behavior:
The onData( ) handler may be assigned a custom callback function to intercept raw XML source code before ActionScript has a chance to parse it. Under certain circumstances, manipulating raw XML source manually may offer improved performance over ActionScript's built-in parsing. ExampleThe following example shows how to display raw loaded XML source while preventing it from being parsed by ActionScript: myDoc = new XML(); myDoc.onData = function (src) { trace("Here's the source: \n" + src); }; myDoc.load("book.xml"); See AlsoXML.onLoad( )
AvailabilityFlash 5 SynopsisXMLdoc.onLoad(success) Arguments
DescriptionThe onLoad( ) handler of XMLdoc is automatically executed whenever an external XML file is loaded into XMLdoc via the load( ) or sendAndLoad( ) methods. By default, the onLoad( ) handler of an XML document object is an empty function. To use onLoad( ), we assign it a callback handler (i.e., a custom-made function). For example: myDoc = new XML( ); myDoc.onLoad = handleLoad; function handleLoad (success) { // Process XML as desired here... } We rely on onLoad( ) events to tell us when it's safe to process XMLdoc. If onLoad( ) is triggered, we know that the loading and parsing of external XML data have completed, so we may safely access that loaded content. The onLoad( ) handler, hence, alleviates the need to write preloading code to wait for data to arrive after the invocation of an XML load( ) function. For example, in the following code we load an XML document, and then we wait for our custom handleLoad( ) function to be automatically executed when loading completes. If loading was successful, we process our XML content with the display( ) function. Otherwise, we show an error message by executing the display( ) function. (The displayProduct( ) and displayError( ) functions are custom functions that you've presumably written to display information to the user, but they are not shown.)Here is the code: myDoc = new XML( ); myDoc.onLoad = handleLoad; myDoc.load("productInfo.xml"); function handleLoad(success) { if (success) { output = "Product information received"; displayProduct( ); // Call custom display function } else { output = "Attempt to load XML data failed"; displayError( ); // Call custom display function } } Notice that the value of the success argument of handleLoad( ) is automatically set by the interpreter to either true or false, indicating whether or not loading completed properly. However, the success argument may appear more useful in theory than it turns out to be in practice. Most web server error messages (e.g., "404 File Not Found") come in the form of HTML documents. Since HTML can quite happily be parsed as XML data, the reception of a server error page results in the parsing of that page into the target XML document object. Because the page parses properly, the load attempt is considered "successful," and success is true, even though the actual XML file may not have been found or some other server error may have been encountered. To be positive that you have the real data you requested, test its structure or content explicitly for some identifying characteristic, such as the nodeName of a particular child. See also the XML.onData( ) event handler, which can be used to perform custom parsing. See AlsoXML.load( ), XML.onData( ), XML.sendAndLoad( )
AvailabilityFlash 5 SynopsistheNode.parentNode AccessRead-only DescriptionThe parentNode property returns a reference to the node object from which theNode descends in the XML object hierarchy. If theNode is the top of the current hierarchy, parentNode returns null. In this XML source fragment, the MESSAGE node is the parentNode of text node "hey": <MESSAGE>hey</MESSAGE> Here the parentNode of the ROOM node is the HOTEL node: <HOTEL><ROOM><SIZE>Double</SIZE></ROOM></HOTEL> See AlsoXML.childNodes, XML.firstChild, XML.lastChild, XML.previousSibling
AvailabilityFlash 5 SynopsisXMLdoc.parseXML(string) Arguments
DescriptionThe parseXML( ) method is akin to an internal load( ) function; it reads and parses the XML source contained by string, converts that XML into an object hierarchy, and then places the resulting hierarchy into XMLdoc. Any previous contents of XMLdoc are replaced by the new hierarchy. XMLdoc must be an instance of the XML class, not the XMLnode class. To include raw HTML or XML source code in a text node without parsing it, use a CDATA section as follows: <![CDATA[ source ]]> For example, the following code creates a MESSAGE element with a single child text node containing the text "<B>Welcome</B> to my site" (the <B> tag is not interpreted as an XML tag and does not become part of the XML object hierarchy): myDoc = new XML( ); myDoc.parseXML("<MESSAGE><![CDATA[<B>Welcome</B> to my site]]></MESSAGE>"); trace(myDoc); // Displays: "<MESSAGE><B>Welcome</B> to my site</MESSAGE>" ExampleWe can use parseXML( ) as a means of replacing the current object hierarchy in an XML object with a new hierarchy based on internally composed XML source code (for example, some user input). In the following example, we create a simple XML message by combining markup with input from text fields named username and content: myDoc = new XML( ); myXMLsource = "<MESSAGE><USER>" + username + "</USER><CONTENT>" + content + "</CONTENT></MESSAGE>"; myDoc.parseXML(myXMLsource); See AlsoXML.load( ), XML.status
AvailabilityFlash 5 SynopsistheNode.previousSibling AccessRead-only DescriptionThe previousSibling property returns a reference to the node object preceding theNode in the current level of the XML object hierarchy. If there is no node before theNode in the current level of the hierarchy, it returns null. In the following XML source fragment, the previousSibling of the CONTENT node is the USER node: <MESSAGE><USER>gray</USER><CONTENT>hi</CONTENT></MESSAGE> ExampleThe previousSibling property can be used to traverse an XML object hierarchy, although nextSibling is more commonly used for this purpose. To view all the children of theNode in reverse order, we may use: for (var i = theNode.lastChild; i != null; i = i.previousSibling) { trace("found node: " + i.nodeName); } See AlsoXML.childNodes, XML.firstChild, XML.lastChild, XML.nextSibling, XML.nodeName, XML.nodeValue, XML.parentNode
AvailabilityFlash 5 SynopsistheNode.removeNode() DescriptionThe removeNode( ) method deletes theNode from an XML document. All descendants (children, grandchildren, and so on) of theNode are also deleted. The childNodes property of theNode's parent is automatically updated to reflect the new structure of the remaining object hierarchy. ExampleHere we delete the second child node; the third child node takes its place: myDoc = new XML("<P>one</P><P>two</P><P>three</P>"); myDoc.childNodes[1].removeNode( ); trace(myDoc); // Displays: "<P>one</P><P>three</P>" See AlsoXML.appendChild( )
AvailabilityFlash 5 SynopsisXMLdoc.send(URL, window) Arguments
DescriptionThe send( ) method converts XMLdoc into a string of XML source code and sends that code in an HTTP request to the script or application residing at URL. The script or application is expected to process the XML in some way and optionally return a response -- normally a web page -- to the browser, which displays it in window. Note that the response is not caught by Flash but by the browser; use sendAndLoad( ) to catch the response within Flash. When XML.send( ) is invoked from the Flash Player running in a browser, XMLdoc is sent via the POST method. When XML.send( ) is invoked from the Flash Player running as a standalone application, XMLdoc is sent via the GET method. The server application receiving the posted XML string must be able to access the raw POST data of the HTTP request directly and should not attempt to parse it as normal name/value pairs. In Perl, the data in a POST request is available from STDIN, and may be extracted and stored in, say, $buffer as follows: read(STDIN,$buffer,$ENV{'CONTENT_LENGTH'}); In ASP, raw POST data may be accessed via the Request.BinaryRead method. Some applications (e.g., Cold Fusion) may not have a direct means of accessing the data in a POST request. For these situations, it may be necessary to first convert the XML object to a string using XML.toString( ) and then pass that string to the server as a variable using loadVariables( ). The default MIME content type of the XML text sent to the server is application/x-www-urlform-encoded. This type, however, is only cosmetic -- the text itself is not URL-encoded. In Build 41 and later of the Flash 5 Player, the MIME content type can be modified using the XML.contentType property. For example, to set the MIME type to application/xml, we use: myXML = new XML( ); myXML.contentType = "application/xml"; Nevertheless, setting the contentType property explicitly to application/x-www-urlform-encoded still does not cause the text sent to be URL-encoded. Note that as of Build 41 of the Flash 5 Player, when XML source is parsed and the characters &, ', ", <, and > appear in a text node, they are converted to the following entities: &, ', ", >, <. This conversion is transparent in Flash because the entities are converted back to their original characters when an XML object is converted to a string; however, the entities will show up in XML source sent to the server. ExamplemyDoc = new XML("<SEARCH_TERM>tutorials</SEARCH_TERM>"); myDoc.send("http://www.domain.com/cgi-bin/lookup.cgi", "remoteWin"); See AlsoXML.sendAndLoad( ), XML.load( ), XML.loaded, XML.onLoad( ), XML.status
AvailabilityFlash 5 SynopsisXMLdoc.sendAndLoad(URL, resultXML) Arguments
DescriptionThe sendAndLoad( ) method serializes XMLdoc into a string of XML source code and sends that code to a script or application that resides at URL. The script or application is expected to process the XML in some way and send an XML document back as a response. The response document is caught by Flash, parsed, converted into an XML object hierarchy, and placed in resultXML. Any previous contents of resultXML are replaced by the newly loaded XML content. See XML.send( ) for important information about sending XML to a server. UsageBefore accessing content imported with sendAndLoad( ), we must be sure that the load and parsing operations are complete. To do so, we either check the value of the resultXML's loaded property or we assign resultXML an onLoad( ) event handler to respond to the load completion. See the XML.loaded and XML.onLoad( ) entries for details. To determine the result of parsing the loaded data, we check the document's status property. XML.sendAndLoad( ) is subject to the domain-based security restrictions described in Table 20-8 under the global loadVariables( ) function. Example// Create an XML document myDoc = new XML("<P>hello server!</P>"); // Create an empty XML document to receive the server's response serverResponse = new XML( ); // Send myDoc to the server, and place the response in serverResponse myDoc.sendAndLoad("http://www.domain.com/cgi-bin/readData.cgi", serverResponse); // Add an onLoad handler to serverResponse that displays the response // from the server in the text field output. serverResponse.onLoad = function ( ) { output = serverResponse.toString( ); } For a good primer on sending XML to and from a server, see Macromedia's article "Integrating XML and Flash in a Web Application," at: See AlsoXML.load( ), XML.loaded, XML.onLoad( ), XML.send( ), XML.status
AvailabilityFlash 5 SynopsisXMLdoc.status AccessRead-only DescriptionThe status property returns a numeric status code indicating whether any errors were encountered when parsing XML source code. Parsing occurs when source XML is:
The status codes are shown in Table 20-14. If no errors were encountered in parsing, success is indicated by a status of 0. Errors are indicated by negative numbers. Parsing terminates once the first error is encountered, so other errors may surface even after you address previously reported errors. Table 20-14. XML Parsing Status Codes
We normally use status to determine whether it's safe to proceed with processing an externally loaded XML file. Check the loaded property to ensure that a load( ) or sendAndLoad( ) command has completed before checking the status. Note that ActionScript's XML parser does not validate documents against DTDs, it only verifies well-formedness. ExamplemyDoc = new XML("<BOOK>Colin Moock</AUTHOR></BOOK>"); trace(myDoc.status); // Displays: "-10" (missing start tag) See AlsoXML.load( ), XML.loaded, XML.onLoad( ), XML.parseXML( ), XML.sendAndLoad( )
AvailabilityFlash 5 SynopsistheNode.toString() ReturnsA string representing the source code of the XML object hierarchy starting at theNode. DescriptionThe toString( ) method converts an XML node object or an XML document object to its analogous XML source code. If theNode is a top-level XML document object, any DOCTYPE and XML declaration tags are included in the string. If the document's ignoreWhite property is false, whitespace is preserved and the document source code appears as it did when it was parsed. It's not normally necessary to invoke toString( ) explicitly; toString( ) is automatically invoked any time theNode is used in a string context. Examplevar myDoc = new XML('<?xml version="1.0"?><!DOCTYPE foo SYSTEM "bar.dtd"><BOOK> <TITLE>ActionScript: The Definitive Guide</TITLE>' + '<AUTHOR SALUTATION="Mr">Colin Moock </AUTHOR> ' + '<PUBLISHER>O\'reilly & Associates, Inc</PUBLISHER> </BOOK>'); trace(myDoc.toString( )); // Displays: <?xml version="1.0"?><!DOCTYPE foo SYSTEM "bar.dtd"> <BOOK> <TITLE>ActionScript: The Definitive Guide</TITLE><AUTHOR SALUTATION="Mr">Colin Moock </AUTHOR> <PUBLISHER>O'reilly & Associates, Inc </PUBLISHER> </BOOK> See AlsoObject.toString( ), XML.nodeValue
AvailabilityFlash 5 SynopsisXMLdoc.xmlDecl AccessRead/write DescriptionThe xmlDecl string property represents the XML declaration tag of XMLdoc, if any exists. Otherwise, xmlDecl is undefined . XMLdoc must be the top-level node in an XML object hierarchy (that is, an instance of the XML class, not the XMLnode class.) The XML declaration tag of an XML document is used to identify the version of XML being used in the document. We use the XML declaration tag to build well-formed XML documents that may be validated externally. Example// A well-formed document (but not validated against a DTD) myXML = new XML('<?xml version="1.0"?><P>this is a short document</P>'); trace(myXML.xmlDecl); // Displays: "<?xml version="1.0"?>" // Set a new XML declaration myXML.xmlDecl = '<?xml version="1.0" standalone="no"?>'; See AlsoXML.docTypeDecl
AvailabilityFlash 5 DescriptionThe XMLnode class defines the core properties and methods of nodes in an XML object hierarchy. Though XMLnode is an internal device, it may be used by programmers to extend the default functionality of XML objects. Every XML object hierarchy technically includes two kinds of object nodes:
The main container node is an instance of the XML class. For example, if we create myDoc as follows: myDoc = new XML(); then myDoc is an instance of the XML class. The XML class inherits from the XMLnode class, so main container nodes have all the properties and methods defined by XMLnode plus those defined by XML. By contrast, the children of myDoc would actually be instances of the XMLnode class, not the XML class. So, if we create myParagraph as follows: myParagraph = myDoc.createElement("P"); then myParagraph is an instance of the XMLnode class. Most of the time the internal distinction between node classes does not affect our use of XML objects. However, if we wish to add an inherited property or method to all XML objects, then we must use the XMLnode class's prototype, not the XML class's prototype (see the example that follows). Any methods or properties attached to XMLnode.prototype are inherited by all XML nodes in a movie. For reference, the properties, methods, and event handlers defined by XMLnode and XML are listed in Table 20-15. Note that while all listed items are accessible through instances of the XML class, items defined by XML are not available through instances of XMLnode. For example, the load( ) method may be invoked on an instance of the XML class, but not on an instance of the XMLnode class. For a full discussion of each item, see the appropriate XML class entry. Table 20-15. XMLnode and XML Properties, Methods, and Event Handlers
ExampleThe following code adds a custom secondChild( ) method to XMLnode.prototype (the secondChild( ) method is subsequently available from any XML node in our movie): XMLnode.prototype.secondChild = function () { return this.childNodes[1]; }; myDoc = new XML("<PRODUCT>Cell Phone</PRODUCT><PRODUCT>Game Console </PRODUCT>"); trace(myDoc.secondChild()); // Displays: "<PRODUCT>Game Console</PRODUCT>" It's also perfectly legitimate to extend the XML class via XML.prototype, but such extensions apply only to main container nodes (direct instances of the XML class). See AlsoThe XML Class; Section 12.5.4, "Superclasses and Subclasses" in Chapter 12, "Objects and Classes".
AvailabilityFlash 5 Constructornew XMLSocket() Methods
Event handlers
DescriptionThe majority of connections between Flash and a server have a very short life span. When Flash requests external data via the loadMovie( ), loadVariables( ), or XML.load( ) functions, a temporary communication channel is established. Data is sent over that channel and then the channel is terminated. This kind of short-term communication has many useful applications, but it is also limited in two important ways:
As of Flash 5, we can overcome these limitations with the XMLSocket class, which allows us to open a persistent communication link between a server application and Flash. We use XMLSocket to develop systems that require frequent server updates, such as a chat room or a networked multiplayer game. In order to connect to a remote application using XMLSocket, we must first create and store an XMLSocket object, like this: mySocket = new XMLSocket( ); Then, we invoke the connect( ) method, which asks Flash to establish a communication link with the remote application. For example: mySocket.connect("http://www.myserver.com", 8000); Once a connection is established, the XMLsocket object acts as a transmitter/receiver. We send XML-formatted data to the remote application by invoking the socket's send( ) method, and we know that we've received XML-formatted data when the socket's onXML( ) event is triggered. A server application used with an XMLSocket object must:
Server applications are typically created by server-side programmers, not Flash programmers. For an example of a simple server application that broadcasts all messages it receives to all connected clients, see the Java XMLSocket server available at the online Code Depot. An XMLSocket connection stays open until one of the following occurs:
Thankfully, the XMLSocket class also provides a way for us to monitor the status of our connection. It includes three properties -- onClose, onConnect, and onXML -- that allow us to define event handlers that will be triggered when the corresponding event occurs. Such handlers are typically known as callback handlers because they are triggered automatically by Flash in response to some event beyond the programmer's direct control. (In this sense they are very similar to ActionScript's built-in clip and button event handlers, except that the handler functions are programmer-defined.) For example, when a connection is closed by the server, the handler defined by the onClose property will be triggered.
ExampleThe following example shows the bare-bones code needed to implement a simple chat client. The client may be seen in action running at: Both the server and the client are available at the online Code Depot: // A Simple Chat Client // *** General init var incomingUpdated = false; // Track whether or not we need to scroll // to the end of incoming (the main // chat text field) var incoming = ""; // Assign the main chat text field a starting value // Attach the scroll manager movie. It forces the chat text field to // show the next (most recent) line each time a message is added. // Note that we only need the scroll manager because of a // text field scroll bug in Build r30 of the Flash 5 Player. attachMovie("processScroll", "processScroll", 0); // Attach sound to play when we receive a message var click = new Sound( ); click.attachSound("click"); // Attach sound to play when user joins or leaves var welcomeSound = new Sound( ); welcomeSound.attachSound("welcome"); // Turn off ugly yellow highlight on buttons _focusrect = 0; // *** Creates a new socket and attempts to connect to the server function connect ( ) { // Create a new XMLSocket object mySocket = new XMLSocket( ); // Assign callback functions to mySocket's handlers. mySocket.onConnect = handleConnect; mySocket.onClose = handleClose; mySocket.onXML = handleIncoming; // Attempt to connect, and assign the return of mySocket.connect() // to connectSuccess (connect() returns true if the initial stage // of connection succeeds) var connectSuccess = mySocket.connect("www.myserver.com", 1025); if (connectSuccess) { trace("initial connection succeeded"); } else { // connectSuccess was false, so we didn't establish a connection. gotoAndStop("connectionFailed"); trace("initial connection failed"); } } // *** Event handler to respond to the completion of a connection attempt function handleConnect (succeeded) { // If handleConnect()'s succeeded argument is true, the connection has been // established and we can proceed with the chat. // Otherwise, show a failure message. if (succeeded) { // Set a property noting that we have an open connection available. mySocket.connected = true; gotoAndStop("chat"); // Put the cursor in the "send message" text field Selection.setFocus("_level0.outgoing"); } else { // Connection didn't succeed so show an error message gotoAndStop("connectionFailed"); trace("connection failed"); } } // *** Event handler called when server kills the connection function handleClose ( ) { // Tell the user that the connection was lost incoming += ("The server has terminated the connection.\n"); // We updated the chat text field, so let the scroll manager know incomingUpdated = true; // Set a property noting that the connection was lost mySocket.connected = false; numClients = 0; } // *** Event handler to receive and display incoming messages function handleIncoming (messageObj) { // Display the received XML data in the Output window trace("--------new data received-----------"); trace(">>" + messageObj.toString( ) + "<<"); trace("-------- end of new data -----------"); // We're updating the chat text field, so let the scroll manager know incomingUpdated = true; lastScrollPos = incoming.scroll; // Check the time var now = new Date( ); var hours = now.getHours( ); var minutes = now.getMinutes( ); var seconds = now.getSeconds( ); // Format time for output hours = (hours < 10 ? "0" : "") + hours; minutes = (minutes < 10 ? "0" : "") + minutes; seconds = (seconds < 10 ? "0" : "") + seconds; // The server sends NUMCLIENTS any time a client connects or disconnects // If we find NUMCLIENTS in the XML object... if (messageObj.firstChild.nodeName == "NUMCLIENTS") { // ...then check if the incoming messages window is empty. If it is... if (incoming == "") { // ...then the user has just joined, so add a welcome message to the chat. incoming += ("welcome to moock comm 1.0.0, " + userID + "\n" + " connection time: " + hours + ":" + minutes + ":" + seconds + "\n" + " server: clayton\'s javaComm generic flash xmlsocket server\n\n"); } else { // Otherwise, someone has arrived or departed, so tell the user if (parseInt(messageObj.firstChild.firstChild.nodeValue) > numClients) { // Report the client arrival in the chat window incoming += (hours + ":" + minutes + ":" + seconds + " a new user has connected.\n"); } else { // Report the client departure in the chat window incoming += (hours + ":" + minutes + ":" + seconds + " a user disconnected.\n"); } } // Finally, keep track of the new number of clients // and play a welcome/departure sound numClients = parseInt(messageObj.firstChild.firstChild.nodeValue;) welcomeSound.setVolume(100); welcomeSound.start( ); } else { // No NUMCLIENTS node was found, so this is just a regular message. // Grab the user name and message from our XML object. var user = messageObj.firstChild.firstChild.nodeValue; var message = messageObj.childNodes[1].firstChild.nodeValue; // Add the message to the chat window, with a time stamp incoming += (hours + ":" + minutes + ":" + seconds + user + ">> " + message + "\n"); // Now do the new message click. // If it's been more than 30 secs since the last message, // sound a loud click. Otherwise sound a quiet click. trace("time since last message: " + (now - lastIncomingMessageTime)); if (lastIncomingMessageTime && (now - lastIncomingMessageTime) > 30000) { click.setVolume(200); } else { click.setVolume(30); } click.start( ); } // Truncate the contents of the main chat text // field if it's longer than 5000 characters if (incoming.length > 5000) { var nearestNewline = incoming.indexOf("\n", incoming.length - 5000); incoming = incoming.substring(nearestNewline, incoming.length); } // Remember when this message arrived for next time lastIncomingMessageTime = now; } // *** Sends a new XML object to the server function sendMessage( ) { // Create the message to send as an XML source fragment. // Note that the spaces before the <USER> and </MESSSAGE> tags // are required so MESSAGE and USER always have a text child node. var message = '<USER> ' + userID + '</USER><MESSAGE>' + outgoing + ' </MESSAGE>'; // Convert the message into an XML object hierarchy messageObj = new XML( ); messageObj.parseXML(message); // Check what we're sending trace("Sending: " + messageObj); // If a socket object has been created and is connected, send the XML message. // Otherwise warn the user that he needs to connect first. if (mySocket && mySocket.connected) { mySocket.send(messageObj); // Clear the "send message" text field outgoing = ""; } else { // The server must have kicked us off... incoming += "You are no longer connected. Please reconnect.\n" incomingUpdated = true; } } // *** Closes the connection to the server function quit( ) { if (mySocket.connected) { mySocket.close( ); mySocket.connected = false; numClients = 0; incoming = ""; gotoAndStop("login"); } } See Also
AvailabilityFlash 5 Synopsissocket.close() DescriptionThe close( ) method severs the communication link between socket and a server application. Once close( ) has been executed on socket, subsequent attempts to invoke send( ) on socket fail. Likewise, the server application will no longer be able to send data to Flash through socket. Note that close( ) has no effect if the socket is already closed or was never connected. Furthermore, close( ) does not trigger the onClose( ) handler of the socket object -- onClose( ) is triggered only by a server-side connection closure. See AlsoXMLSocket.connect( ), XMLSocket.onClose( )
AvailabilityFlash 5 Synopsissocket.connect(host, port) Arguments
ReturnsA Boolean indicating the initial success (true) or failure (false) of the connection attempt. DescriptionThe connect( ) method attempts to establish a connection from Flash to a server application running on host at port. If connect( ) returns true, the initial phase of the connection completed successfully and the socket's onConnect( ) handler will be invoked at a later time. From the onConnect( ) handler, we can evaluate whether the connection was fully established. Note that connection attempts can take varying amounts of time, particularly when a connection attempt fails. You should indicate to the user that a connection attempt is in progress when invoking connect( ). If connect( ) returns false, the initial connection phase did not complete successfully. In such a case, socket's onConnect( ) handler will not be invoked. It is important to check both the return value of the connect( ) method and, if connect( ) returns true, the value of the success parameter of the onConnect( ) handler. UsageFor security reasons, connect( ) is not permitted to connect to arbitrary Internet hosts. It may connect only to hosts in the domain that the movie was downloaded from. The rules for connect( ) are the same ones applied to the loadVariables( ) function. See Table 20-8 under the global loadVariables( ) function for a list of the domain matching requirements imposed by the connect( ) method. The connect( ) method returns false for connection attempts that violate security restrictions. Note that security restrictions do not apply to the standalone Player. Example// Create a new socket object mySocket = new XMLSocket( ); // Assign a callback handler function to onConnect mySocket.onConnect = handleConnect; // Attempt to connect to an application running on myserver.com at port 10000 if (mySocket.connect("myserver.com", 10000) == false) { // Jump to a frame showing some sort of error message gotoAndStop("failureDialog"); } else { // Jump to a frame where we'll wait until onConnect is triggered gotoAndPlay("connecting"); } See AlsoXMLSocket.close( ), XMLSocket.onConnect( )
AvailabilityFlash 5 Synopsissocket.onClose = closeHandler socket.closeHandler() DescriptionThe onClose property allows you to specify a callback handler to be executed automatically whenever an open connection to socket is closed by the server. Server-instigated closures usually result from a server application shutting down or deliberately "kicking off" the client. ExampleTo respond to an onClose event, we must assign our own function (i.e., our callback handler) to the onClose property of an XMLSocket object. In practice, we use this callback handler to detect an external socket disconnection. The following code assigns the function handleClose( ) to mySocket's onClose property. The handleClose( ) function simply alerts the user that a closure has occurred by updating the value of the text field status: mySocket = new XMLSocket( ); mySocket.onClose = handleClose; function handleClose ( ) { status += ("\nThe server has terminated the connection.\n"); } See AlsoXMLSocket.close( ); Section 10.6.2, "Attaching Event Handlers to Other Objects" in Chapter 10, "Events and Event Handlers"
AvailabilityFlash 5 Synopsissocket.onConnect = connectHandler socket.connectHandler(success ) Arguments
DescriptionThe onConnect property allows you to specify a callback handler to be executed automatically when a previously invoked connect( ) operation finishes. The execution of the callback handler specified by onConnect does not necessarily mean a connection has been successfully established -- the callback handler is executed whenever the connection attempt is finished, whether or not the attempt was successful. The callback handler specified by onConnect is passed a success argument that indicates if the attempt succeeded (i.e., a connection has been established). If so, success is set to true. If the attempt failed (i.e., a connection timed out, was refused, or otherwise could not be established), the success argument is set to false. Note that ActionScript does not distinguish among network timeout, unknown host, refusal, or other common connection errors. The callback handler, therefore, may not be executed for up to a minute after the connect( ) command is issued depending on the settings of the server involved in a connection attempt, the connection speed, network traffic, and so on. ExampleWe use the callback handler specified by onConnect to detect the success or failure of a connection attempt. In practice, we might use the callback handler to set a flag indicating that transmissions should begin if the connection was successful. We may also use the callback handler to execute fallback code when the connection fails, such as alerting the user to the problem's nature. To respond to an onConnect event, we must assign our own function (i.e., our callback handler) to the onConnect property of an XMLSocket object. The following code assigns the function handleConnect( ) to mySocket's onConnect property. By updating the value of the text field status, handleConnect( ) alerts the user that a connection has either succeeded or failed: mySocket = new XMLSocket( ); mySocket.onConnect = handleConnect; function handleConnect (succeeded) { if (succeeded) { status += ("Successfully connected.\n"); } else { status += ("Connection attempt failed.\n"); } } For code showing the onConnect( ) handler used in a more complete system, see the example under the XMLSocket class. See AlsoXMLSocket.connect( ); Section 10.6.2, "Attaching Event Handlers to Other Objects" in Chapter 10, "Events and Event Handlers"
AvailabilityFlash 5 (undocumented) Synopsissocket.onData(src) Arguments
DescriptionThe onData( ) handler executes automatically whenever a zero byte (ASCII null character) is transmitted to Flash over socket. By default, onData( ) simply constructs a new XML object hierarchy from src, and passes that hierarchy to socket.onXML( ). However, the onData( ) handler may be assigned a custom callback function to intercept src before ActionScript has a chance to parse it as XML. Under certain circumstances (such as real-time video games), manipulating the raw data in src manually may offer improved performance over ActionScript's built-in XML parsing. ExampleThe following code shows how to assign a custom callback function to onData( ). The callback function simply displays any data received by mySocket and prevents ActionScript from parsing the data as XML: mySocket = new XMLSocket(); mySocket.onData = function (src) { trace("Received data: \n" + src); }; See AlsoXMLSocket.onXML( )
AvailabilityFlash 5 Synopsissocket.onXML = xmlHandler socket.xmlHandler(XMLobject ) Arguments
DescriptionThe onXML property allows you to specify a callback handler to be executed when Flash receives an incoming transmission. Whenever socket receives a complete block of data (i.e., a string followed by an ASCII null character) from the server, the callback handler specified by socket.onXML is automatically invoked. A server may send data as often as it pleases, but the callback handler is executed only when the trailing null character (i.e., a zero byte) is received by socket. In Java, a zero byte is specified as '\0'. When the zero byte is received, it causes ActionScript to parse any data that has been received by socket since the last zero byte was sent (or since the initial connection if this is the first zero byte). The parsed data is converted to an XML object hierarchy which is passed as the XMLobject argument to the callback handler. If you are a Flash programmer who is responsible for the client side of a client/server application only, simply note that the callback handler specified by onXML receives any new XML data when it arrives. The new XML data is accessible through XMLobject. To access the raw data sent over a socket, override the default behavior of the socket's onData( ) handler. See XMLSocket.onData( ). ExampleTo respond to an onXML event, we must assign our own function (i.e., our callback handler) to the onXML property of an XMLSocket object. The following code assigns the function handleIncoming( ) to mySocket's onXML property. The handleIncoming( ) function accesses one of the nodes of the XML object hierarchy stored in messageObj and adds its value to the text field messages: mySocket = new XMLSocket( ); mySocket.onXML = handleIncoming; function handleIncoming (messageObj) { trace("Got some new data!"); // messageObj will contain the fragment: <MESSAGE>text</MESSAGE> var message = messageObj.firstChild.firstChild; messages += (message.nodeValue + "\n"); } For code showing the onXML handler used in a more complete system, see the example under the XMLSocket class. See AlsoXMLSocket.send, XMLSocket.onData( ); Section 10.6.2, "Attaching Event Handlers to Other Objects" in Chapter 10, "Events and Event Handlers"
AvailabilityFlash 5 Synopsissocket.send(XMLobject) Arguments
DescriptionThe send( ) method transmits a message from Flash to a server application via socket. The message to send should be an object of the XML class but may also be a string. When send( ) is invoked, XMLobject is converted to a string and sent to the remote application, followed by a zero byte (the first ASCII character, null). The remote application is not obliged to respond; however, any response sent will trigger socket's onXML( ) event handler. ExampleThe following code sends a very simple XML-formatted message to a remote application over the socket mySocket, which is a valid XMLSocket object for which a connection has already been established (note that message is an XML object, not an XMLSocket object; see the example under the XMLSocket class entry for a full-fledged XMLSocket sample application): var message = new XML('<MESSAGE>testing...testing...</MESSAGE>'); mySocket.send(message); It is also legal to send a string containing XML-formatted text without wrapping it in an XML object. For simple XML messages, this is often sufficient: mySocket.send('<MESSAGE>testing...testing...</MESSAGE>'); See AlsoCopyright © 2002 O'Reilly & Associates. All rights reserved. |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|