Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Design > Adobe Creative Suite

  • Print
  • + Share This
This chapter is from the book

Object Sampler

In the following pages, we'll look at many of the objects found in ActionScript, and provide examples of their use. Some objects (such as MovieClip, TextField, and Sound objects) are given more extensive coverage because they're likely to be the ones you'll use most often in your projects. Advanced objects, such as the XMLSocket object (which requires that you set up an XML socket server), are beyond the scope of this book (and thus are not discussed). Global objects are indicated as such in the subheads below. For all objects that don't include this indication, you must create instances.

NOTE

For additional information about any of the ActionScript objects discussed here, refer to the ActionScript Dictionary in Flash (Help > ActionScript Dictionary). Or pick up a copy of Macromedia Flash MX ActionScripting: Advanced Training from the Source, published by Macromedia Press.

Accessibility Object (Global)

This simple object has a single method, (isActive()), which returns a value of true (if a screen reader is active on the user's computer) or false (if no screen reader is active). Take a look at the following script:

if(Accessibility.isActive()){
  gotoAndStop("Accessible Version");
}else{   gotoAndStop("Standard Version");
} 

You can place this if statement on Frame 1 of your movie, so that as soon as the movie begins playing, the statement will check to see whether the user's system has an active screen reader. If an active screen reader is detected, the user will be taken to a scene that has been set up so that its content is accessible. If no active screen reader is detected, the script will take the user to a scene that contains a standard version of your site.

Array Object

You can think of an Array object as a supervariable: Whereas a regular variable can only contain a single value, an Array object can contain multiple values. You create an instance of the Array object in the following manner:

directions = new Array ("North", "East", "South", "West"); 

The above script creates an array named directions, which contains four values. Each value in an array is identified by an index number (0, 1, 2, and so on) that denotes its position in the array. In the array we just created, "North" has an index number of 0, "East" an index number of 1, and so on. To access a value that exists in an array, you would use the following syntax:

myVariable = directions[2]; 

In this script, myVariable is assigned a value of "South" because this is the value that exists at index position 2 in our directions array. There are numerous methods available to the Array object that let you manipulate the data within the array. For example, the directions array we created currently contains data in the following order:

directions[0] = "North";
directions[1] = "East";
directions[2] = "South";
directions[3] = "West"; 

Using the reverse() method as follows:

directions.reverse(); 

We can reverse the order of values to the following:

directions[0] = "West";
directions[1] = "South";
directions[2] = "East";
directions[3] = "North"; 

Or using the sort() method as follows:

directions.sort(); 

We can change the order of values so they exist alphabetically, as in the following:

directions[0] = "East";
directions[1] = "North";
directions[2] = "South";
directions[3] = "West"; 

Arrays help you logically store data in groups, making it easier to work with. For example, you could use an array to store user information, by creating four input text fields on the stage with the instance names of name, age, phoneNumber, and email, respectively, and then entering the following values:

name: Derek
age: 20;
phoneNumber: 555-1234
email: derek@derekfranklin.com 

You could then create a user array, perhaps when the user presses and releases a button, as in the following:

on(release){
user = new Array(name.text, age.text, phoneNumber.text, email.text);
} 

Then, whenever you needed to access a particular piece of data about your user, you could easily do so by using the array's name, followed by the index number of the particular piece of data you wished to use. Take a look at the following:

myMessage.text = "Hello " + user[0] + ". You seem to be " + user[1] + "
years old."; 

Assuming that myMessage is a dynamic text field, the preceding script will display "Hello Derek. You seem to be 20 years old" in that field.

Boolean Object

An instance of the Boolean object holds a value of true or false. You can create instances of the Boolean object in one of two ways:

answer = new Boolean(true); 

Or

answer = true; 

The latter is the more common method since it requires fewer keystrokes. Boolean values are frequently used in conditional statements (see Chapter 13, "Understanding ActionScript").

Button Object

Instances of Button objects are created when you place buttons on the stage. By assigning an instance name to a button, you can control it dynamically via ActionScript. For example, if you have a button instance named myButton on the stage, you can disable it at any time (so that users can no longer interact with it) by setting its enabled property to false, as in the following:

myButton.enabled = false; 

To enable that button again, you would use the following syntax:

myButton.enabled = true; 

You can also set several other Button object properties—determining, for example, whether it should be Tab enabled (that is, selectable by pressing the Tab key) or whether the hand cursor should appear when the user interacts with the instance (Figure 14.5).

Figure 14.5Figure 14.5 By setting the useHandCursor property for button instances to a value of true or false, you can control how the cursor appears when the user interacts with the button instance.


In addition to the properties and methods shown for Button objects in the Toolbox List window, they also have several properties and methods that are similar to those of the MovieClip object, as shown in Table 14.1.

Table 14.1 Properties and Methods Common to Movie Clips and Buttons

Properties

_alpha

_height

_name

_rotation

_width

_x

_Xmouse

_Xscale

_Y

_ymouse

_yscale

Methods

startDrag()

stopDrag()

swapDepths()


NOTE

For more information about Button object properties, see "MovieClip Object" later in this chapter.

Capabilities Object (Global)

The Capabilities object includes properties that provide information about the user's computer, including its current screen resolution, whether it can play sounds, its ability to play video, and more. In the following example, usersScreen would have a value of 1280 (my current horizontal screen resolution) if I viewed the movie:

usersScreen = System.capabilities.screenResolution.x; 

The information this object provides allows your movie to react accordingly. For example, if your site has a button (named videoButton) that plays a video, you can determine whether the user's computer is able to play video, and if it can't, disable the button, as in the following:

if(System.capabilities.hasVideoEncoder == false){
  videoButton.enabled = false;
} 

All of this object's properties are read only.

NOTE

For additional properties for this object, see Flash's ActionScript Dictionary.

Color Object

To manipulate a movie's color, you must create a Color object, then associate that Color object with a movie. Once you've done this, the color of the associated movie can be manipulated using the methods available to the Color object class. Take a look at the following script, which is executed when the button it's attached to is pressed and released:

on(release){
  //create a new Color object when this button is released.
  myColor = new Color(_root.myMovieClip);
  myColor.setRGB(0x33F366);
} 

Now let's examine what's happening in each line of script:

myColor = new Color(_root.myMovieClip); 

The line above creates an instance of the Color object—in essence, telling Flash to create a new color object named myColor, and associate it with the movie clip instance with the target path of _root.myMovieClip (Figure 14.6).

Figure 14.6Figure 14.6 When an instance of the Color object is created, you associate it with a particular timeline, which allows you to manipulate the color of that timeline using methods of the Color object class.


Once this object has been created and associated with a movie, we can manipulate that movie's color by addressing the name of the Color object (not the name of the movie clip instance), followed by a Color object method, which is what the next line of our script does:

myColor.setRGB (0x33F366); 

The above line of the script says, "Set the RGB value of myColor to a hex value of 33F366." This will make all graphical content within _root.myMovieClip turn green. For example, if the movie clip instance contains a graphic of the letter A, that A will turn green.

Manipulating a movie's color via a Color object is similar to selecting an instance of a movie clip in the authoring environment, and applying a tinting effect to it from the Property inspector. The difference is that the Color object lets you do it dynamically—that is, while the movie is playing.

A movie can contain as many Color object instances as you wish, each associated with a different movie.

Date Object

Date objects allow you to work with data that pertains to time, including years, months, days, hours, minutes, seconds, and even milliseconds. This feature lets you display the current time, as well as build clocks, counters, calendars, and more. Before you can use date data in your project, however, you must create an instance of the Date object. The following script creates a Date object, then uses that object to display a custom message (with an instance name of myMessage) in the dynamic text field:

on(release){
  //create a new Date object when this button is released.
  myDateObject = new Date();
  myMessage.text = "Can you believe it's already the year " +
  myDateObject.getFullYear() + "?";
} 

Now let's take a closer look at each line of this script.

myDateObject = new Date(); 

The line above creates a new Date object instance named myDateObject. You'll notice that we didn't enter any parameters within the parentheses; this means that our Date object instance will be based on the current date and time (as defined by the computer on which Flash Player is running). We'll look more at this shortly.

myMessage.text = "Can you believe it's already the year" +
myDateObject.getFullYear() + "?"; 

The above line determines the message that will be displayed in our dynamic text field. Using the getFullYear() method (which returns the four-digit year of the associated Date object instance), this will display the message "Can you believe it's already the year 2002?"

A Date object instance doesn't have to contain the current date and time. The following creates a Date object based on February 21, 1993:

myWeddingDay = new Date(1993, 1, 21); 

The three parameters in the parentheses represent the year, month, and day of the Date object instance you're creating. You'll notice that the number 1 identifies February; this is because ActionScript recognizes the first month of the year (January) as 0, and then counts upward from there (thus, February is 1, and so on).

Creating Date object instances that relate to specific dates allows you to display information about those particular dates. For example, if you wanted to let your user enter his or her birthday, so that you could display a custom message indicating what day of the week he or she was born, you could create three input text fields on the stage with instance names of year, month, and day, respectively. If the following values were entered:

year: 1966;
month: 7;
day: 27; 

The following script would be used to display the message:

on(release){
  convertMonth = month.text - 1;
  userBirthDate = new Date(year.text, convertMonth, day.text);
  if(userBirthDate.getDay() == 0){ d
    ayOfWeek = "Sunday";
  }else if(userBirthDate.getDay() == 1){
    dayOfWeek = "Monday";
  }else if(userBirthDate.getDay() == 2){
    dayOfWeek = "Tuesday";
  }else if(userBirthDate.getDay() == 3){
    dayOfWeek = "Wednesday";
  }else if(userBirthDate.getDay() == 4){
    dayOfWeek = "Thursday";
  }else if(userBirthDate.getDay() == 5){
    dayOfWeek = "Friday";
  }else if(userBirthDate.getDay() == 6){
    dayOfWeek = "Saturday";
  }
  myMessage.text = "You were born on a " + dayOfWeek + ".";
} 

Let's examine this script:

convertMonth = month.text - 1; 

If our user was born in July and entered 7 as the month in which she was born, we would need to convert that 7 to a 6 to represent July correctly in a Date object. That's what the above line accomplishes.

userBirthDate = new Date(year.text, convertMonth, day.text); 

This line creates a new Date object instance and names it userBirthDate. The current values entered into the year and day text fields, and the value of the convertMonth variable, are used to define it. Thus, userBirthDate is an object based on the date July 27, 1966.

if (userBirthDate.getDay() == 0) {
  dayOfWeek = "Sunday"; 

In this statement, the getDay() method is used to determine a numerical value (between 0 and 6) that denotes the day of the week for the specified Date object instance. Sunday is represented by 0, Monday by 1, Tuesday by 2, and so on. Thus, the if statement states, "If July 27, 1966, occurred on a Sunday (or 0), then the dayOfWeek variable is assigned a value of 'Sunday.' " The remaining else if statements in this script are used in a similar fashion to the if statement. In the end, dayOfWeek will have a string value representing the name of a particular day in the week.

myMessage.text = "You were born on a " + dayOfWeek + "."; 

The last line displays a custom message in the dynamic text field named myMessage, based on the value of dayOfWeek. In our example, since July 27, 1966, occurred on a Wednesday, myMessage displays "You were born on a Wednesday."

Key Object (Global)

The Key object allows your movie to capture and react to the user's interaction with his or her keyboard—functionality that makes it possible for the user to perform certain tasks within the movie (such as navigating to different scenes), in response to spe-cific key presses or even combinations of key presses (similar to keyboard shortcuts).

Scripts that involve the Key object are usually (though not always) executed as the result of onClipEvent(keyDown) or onClipEvent(keyUp) events. For example, if you want your project to navigate to the next frame in response to the spacebar being pressed, you would place the following script on a movie clip instance in the scene:

onClipEvent(keyDown){
  if(Key.isDown(Key.SPACE)){
    _root.nextFrame();
  }
} 

Notice that the isDown() method is looking for the spacebar being pressed by using the syntax Key.SPACE. You can use similar syntax—for example, Key.TAB, Key.SHIFT, Key.PGUP, and so on—to determine whether other "editing" keys, (Backspace, Tab, Shift, Page Up, Page Down, and so on) have been pressed. Although a limited number of keys are identified in this manner (located in the Object > Movie > Key > Constants book in the Toolbox List window), the Key object lets you get around this limitation by using ASCII key codes to identify specific keys.

For example, the spacebar has an ASCII equivalent value of 32; thus, our previous script could be rewritten as follows:

onClipEvent(keyDown){
  if(Key.isDown(32)){
    _root.nextFrame();
  }
} 

Every key on the keyboard has an ASCII equivalent, which gives you far greater flexibil-ity in designating particular keys than the syntax approach shown in the first example.

NOTE

A complete list of ASCII key codes can be found in the Flash manual, which you can access from the authoring environment by pressing F1.

LoadVars Object

The LoadVars object is used to work with variables loaded from an external source, such as a text file or Web server. For example, let's say you've created a text file containing the following text/variables:

&name=Dennis&age=28&maritalStatus=Single 

You can see that this text file contains three variables named name, age, and marital-Status. Next we'll assume that this file is saved as dennisText.txt. To load this data into the main timeline of a Flash movie when it begins playing, you would use the following syntax:

myLoadedVars = new LoadVars();
myLoadedVars.load("dennisText.txt"); 

The first line creates an instance of the LoadVars object named myLoadedVars. The second line uses the load() method to load the variables in the dennisText.txt file into the object instance. When loaded, variable values can be accessed by addressing the name of the LoadVars object instance, followed by the name of the particular variable you wish to access (Figure 14.7). For example, the following script:

message.text = "Hello " + myLoadedVars.name; 

Will display "Hello Dennis" in a text field named message.

Figure 14.7Figure 14.7 Once external variables have been loaded into a LoadVars object, their values can be accessed by addressing the name of the LoadVars object instance they were loaded into, followed by the name of the particular variable value you wish to use.


To access data output from a CGI script or Web server, point to the URL containing the dynamic page when using the load() method, for instance:

myLoadedVars.load("http://www.myDomain.com/data.asp"); 

Math Object (Global)

The Math object is the means by which you manipulate numbers with ActionScript. Let's look at some examples.

The round() method will round a number to the nearest integer. Thus, in the following example myVariable is assigned a value of 34.

myMathVariable = 34.365;
myVariable = Math.round(myMathVariable); 

The ceil() method will round a number up to the nearest integer. Thus, in the following example myVariable is assigned a value of 35.

myVariable = Math.ceil(34.365); 

The floor() method will round a number down to the nearest integer. Thus, in the following example myVariable is assigned a value of 34.

myVariable = Math.floor(34.945); 

The max() method determines which of two values is higher and returns that value. Thus, in the following example myVariable is assigned a value of 45.

mathVariable1 = 45;
mathVariable2 = 19;
myVariable = Math.max(mathVariable1, mathVariable2); 

The min() method determines which of two values is smaller and returns that value. Thus, in the following example myVariable is assigned a value of 19.

mathVariable1 = 45;
mathVariable2 = 19;
myVariable = Math.min(mathVariable1, mathVariable2); 

The Math object has additional methods, for performing trigonometry functions and more.

Mouse Object (Global)

The Mouse object's main purpose in ActionScript is to provide methods for making the mouse cursor invisible or visible. Take a look at the following script:

on(press){
  Mouse.hide();
  startDrag(_root.customCursor, true);
} 

Let's now examine each line:

on(press) { 

The above line shows that the script is attached to a button, and will be executed when the button is pressed.

Mouse.hide();

This line hides the mouse cursor.

startDrag(_root.customCursor, true); 

This last line essentially states, "Start dragging the movie clip instance named cus-tomCursor on the main timeline," and, "Yes (true), I want to lock the center of the movie clip instance to the position of the cursor." This gives your project a custom cursor when the button is pressed.

When you hide the mouse cursor from view, it is still active, just not visible onscreen.

MovieClip Object

The MovieClip object is the most important type of object in a Flash movie: Not only do movie clip instances serve as the foundation for most Flash projects, you're also able to control them in more ways than any other type of object. Since movie clip instances play such a vital role, it's important to have a thorough understanding of their properties and methods, and how you can use them to create interactivity.

We'll be looking at all movie clip instance properties in this section, but will save a thorough discussion of methods for Chapter 16, "Using ActionScript in Your Pro-jects"(see "Methods" a bit later in the chapter for more information).

Properties

Each movie/timeline has its own group of properties that can be changed dynamically while the movie is playing, and whose current values can be evaluated and used in conditional or looping statements, as well as in other areas of your scripts. As you'll see from the sample scripts, you simply use a movie's target path to access any of its properties. In this section we'll describe the various movie properties, and show you how you can manipulate them to create interactive movies. As we go along, we'll indicate (in parentheses) whether a property's value is settable and/or readable.

NOTES

As you've already learned, Flash movies can contain other movies, creating a parent/child relationship. When you change a parent timeline's properties, its children inherit those same properties. For example, if you made a parent movie transparent, the child movies it contains would become transparent as well. Keep in mind, however, that the reverse is not true: Changing the properties of a child does not affect its parent movie (Figure 14.8).

Figure 14.8Figure 14.8 Setting a parent timeline's properties affects all of its child timelines (left); however, the opposite is not true (right).


Many movie properties (except those pertaining to a timeline, such as _currentframe, _framesloaded, and _totalframes) function in the context of button instances as well.To use any of the following scripts in the context of a button instance (except those pertaining to the properties just mentioned), replace the movie clip instance's name with a button instance's name.

_alpha (can be set and read)

The _alpha property represents a movie or movie clip's transparency (expressed as a percentage).

The following script evaluates the transparency of the movie clip instance dress. If the clip is more than 50 percent transparent, the variable wearSlip is set to true before going to "DanceParty." Otherwise, you go straight to "DanceParty."

if(_root.dress._alpha > 50){
  wearSlip = true;
  gotoAndPlay("DanceParty");
}else{   gotoAndPlay("DanceParty");
} 

_currentframe (read-only)

The _currentframe property provides the current frame-number position of a timeline for a movie or movie clip.

In this script, when the on(release) mouse event occurs, the following script will send the main movie's timeline forward 20 frames from its current position:

on(release){
  _root.gotoAndStop (_root._currentframe + 20);
} 

_droptarget (read-only)

The _droptarget property represents the target path that a dragged movie is currently on top of when dragging stops (Figure 14.9); this allows you to emulate drag-and-drop behavior.

Figure 14.9Figure 14.9 In this illustration, the droptarget for movieB is movieA.


The following script lets you emulate drag-and-drop behavior. When the clip event mouseDown occurs, myMovieClip on the root timeline is dragged, with its position centered underneath the moving mouse. When the mouseUp event occurs, dragging halts and an expression is used to evaluate the movie clip's position. The movie clip directly beneath the one being dragged is always considered the droptarget. In this script, when the drag operation stops, the droptarget is identified. If it equals _root.myTarget, then myMovieClip becomes invisible; otherwise, nothing happens.

onClipEvent(mouseDown){
  startDrag(_root.myMovieClip, true);
}
onClipEvent(mouseUp){
  stopDrag();
  if(eval(_root.myMovieClip._dropTarget) == _root.myTarget) {
    _root.myMovieClip._visible = false;
  }
} 

TIP

The hitTest() method (described a little later in the chapter) offers similar functionality, but is easier to use and more flexible than the droptarget property.

_focusrect (can be set and read)

The _focusrect property value determines whether a yellow box appears around a movie clip instance, when it has been tabbed to using the Tab key (Figure 14.10). The following script turns on this functionality for the movie clip instance named myMovieClip:

myMovieClip._focusrect == true; 

Figure 14.10Figure 14.10 The focus rectangle outlines elements when the Tab key has been used to navigate between them.


NOTE

By default, this property is set to false for all movie clip instances.

_framesloaded (read-only)

The _framesloaded property represents the number of frames of a movie that have loaded. This property can be evaluated in order to prevent a timeline's playback from moving forward until a specific number of frames has been downloaded. For example, assume the following script is placed on Frame 2 of the main timeline: If more than 200 frames have been loaded when this script is executed, the timeline would jump to and begin playing Scene 2, Frame 1. Otherwise, the timeline would go to and begin playing from Frame 1 of the current scene. This causes a loop that is not broken until more than 200 frames have been loaded.

if(_framesloaded > 200){
  gotoAndPlay("Scene 2", 1);
}else{
  gotoAndPlay(1);
} 

TIP

This is the logic typically employed when creating preloading animations, which appear as the movie loads.

_height (can be set and read)

The _height property provides and sets the current height of a movie; its value is based in pixels. For an example of this type of script, see the sample script for the _width property.

_name (can be set and read)

The _name property denotes the name of a movie clip instance in the form of a string value such as "myMovieClip"—similar to the _target property (see later in this chapter) but without the full path.

This property can be useful for centralizing your code. For example, assume there are three movie clip buttons on the stage with instance names of home, products, and services, and that there are three frame labels on the timeline with similar names. Each of the movie clip buttons has an attached script, which looks like the following:

on(release){
  _root.buttonFunction(_name);
} 

Here you can see that when the button is pressed and released, it will call a function named buttonFunction() on the main timeline ,and will send that function a single parameter representing its instance name.

NOTE

We're using movie clip buttons as opposed to normal buttons here, because while button instances can be given names, the _name property in relation to regular button instances represents the name of the timeline the button instance is part of, not the instance itself. For movie clips, the _name property represents the movie clip instance's name, even if it is being used as a button, as shown in this example.

The buttonFunction() function definition can then use that value to determine how it should work:

function buttonFunction(instanceName){
  gotoAndPlay(instanceName);
  message.text = "You have navigated to the" + instanceName + " section.";
++navButtonsClicked;
} 

Here you can see that the function uses the name of the instance that is passed to it to navigate the timeline, display a message, and track the number of times a navigation button has been clicked. All buttons call this single function, but the function can react differently depending on the name of the instance that calls it, enabling you to centralize the functionality of a group of buttons.

_quality (can be set and read)

The _quality property—which can have a string value of"LOW" , "MEDIUM", "HIGH", or "BEST"—specifies the playback quality of your movie. As a global property, it pertains to all movies currently playing in the Flash Player window. The following script sets the value of the movie's quality to "MEDIUM":

_quality = "MEDIUM"; 

_rotation (can be set and read)

The _rotation property represents a movie's rotation, in degrees, relative to the movie's parent (Figure 14.11).

Figure 14.11Figure 14.11 In this graphic, movie2 is rotated 30 degrees relative to its parent (movie1); thus, the value of its rotation property is 30. If movie1 were rotated by 60 degrees, movie2 would rotate that much as well (for a total of a 90-degree rotation); however, its rotation value would still be 30 because this value is based on its rotation relative to its parent, not its absolute rotation setting.


The following script is triggered by the release mouse event. When triggered, a random numeric value between 0 and 359 is generated and assigned to the variable spin. This value is used to set the rotation value for the movie clip named myMovieClip. In addition, using a conditional statement the value of spin is evaluated: If that value is between 0 and 45 degrees, "You spun a 1, you win!" is displayed in a dynamic text field named message. Otherwise, "Try again" is displayed.

on(release) {
  spin = random(360);
  _root.myMovieClip._rotation = spin;
  if(spin >= 0 && spin < 45){
    message.text = "You spun a 1, you win!";
  }else{
    message.text = "Try again.";
  }
) 

_soundbuftime (can be set and read)

The _soundbuftime property is a numeric value that denotes the number of seconds of streaming sound that need to be downloaded by the user, before your movie can begin to play. The default setting is 5 (for 5 seconds). Because this is a global property, it pertains to all movies currently playing in the Flash Player window. This would normally be set on the first frame of your movie. The following script sets this property so that streamed audio will not begin playing until the user has downloaded 15 seconds of it.

_soundbuftime = 15; 

_target (read-only)

The _target property provides the target name and full path (in slash syntax) of a movie clip instance in the form of a string value such as "/myMovieClip".

The following script gets the target path and name of the current movie clip when the release event occurs. The script then outputs it to a dynamic text field on the main timeline named currentMovie:

on(release){
  _root.currentMovie.text = this._target;
} 

_totalframes (read-only)

The _totalframes property represents the number of frames in a movie or movie clip.

In the following script, when the release mouse event occurs, the following script will create the variable timeToPlay. This variable's value is based on the number of frames in the main movie, divided by the frame-per-second rate. Math.round() is used to remove any decimal places in the calculation. Next, the dynamic text element on the main timeline named message will display a message based on the value of timeToPlay:

on(release){
  timeToPlay = Math.round(_root._totalframes / 12);
  _root.message.text = "This movie will take " + timeToPlay + " seconds to
play.";
} 

If the movie has 240 frames, a text field will display the following:

"This movie will take 20 seconds to play."

_url (read-only)

This property represents the complete URL for a SWF that's been loaded into a Flash project. For example, if a SWF were loaded into the Flash Player window from the URL http://www.mydomain.com/secondmovie.swf, checking this property of the movie would return a string value of "http://www.mydomain.com/secondmovie.swf".

You can use this property to ensure that others don't "borrow" your work. Here's how: If you place on Frame 1 of a movie a script that checks its URL property and instructs it to take one action if it was loaded from the "correct" URL, and another if it was loaded from the "wrong" URL, you can prevent others from stealing a SWF file from their cache and using it as their own.

The following script—which is placed on Frame 1 of your movie—evaluates the URL property of the main movie. The movie will continue playing if the script detects the correct URL; however, if the script detects an incorrect URL, the movie will cease playing, and jump to (and stop at) the frame labeled Denied.

if(_root._url == "http://www.properdomain.com"){
  play();
 }else{
  gotoAndStop("Denied");
} 

_visible (can be set and read)

The _visible property—which denotes a movie's visibility—represents a Boolean value of true or false: true if visible and false if not.

The following script checks the visibility of the movie clip teacher. If it's not visible, the movie clip kids is sent to a frame labeled Recess; if it is visible, kids is sent to Desk:

if(_root.teacher._visible == false){
  _root.kids.gotoAndPlay("Recess");
}else {
  _ root.kids.gotoAndStop("Desk");
} 

_width (can be set and read)

The _width property represents the current width of a movie; its value is defined in pixels. The following script evaluates the width of the current movie, and reacts accordingly:

on(release){
  nextMeal = 50;
  if(_width + nextMeal >= 400){
    message.text = "I'm too fat.";
  }else if(_width + nextMeal <= 100){
    message.text = "I'm too skinny.";
  }else{
    message.text = "I'm just right.";
  }
} 

When executed, this script creates a variable named nextMeal, and gives it a value of 50. Using an if statement, the width of the current movie is determined, and the value of nextMeal is added to it. The combined total is then evaluated to determine whether it's greater than or equal to 400, less than or equal to 100, or somewhere in between. For our demonstration, the width of the movie was determined to be 230, which when combined with 50 equals 280. Thus, a dynamic text field named message will display the string "I'm just right."

_x (can be set and read)

The _x property of a movie represents the horizontal distance between its registration point and the registration point of its parent movie (Figure 14.12).

Figure 14.12Figure 14.12 The _x property is a relative value based on the horizontal distance movie3_x property between its registration point (marked by a plus sign [+] here) in relation to the registration point of its parent.


The following script evaluates the horizontal position of the current movie, and reacts accordingly:

on(release){
  if(_x < 200){
    message.text = "I'm on the left.";
  }else if(_x > 200) {
    message.text = "I'm on the right.";
   }else{
    message.text = "I'm stuck in the middle somewhere.";
  }
} 

For our demonstration, when this script is executed, the horizontal position of the current movie is evaluated to be exactly 200; thus, a dynamic text field named message will display the string "I'm stuck in the middle somewhere."

_xmouse (read-only)

The _xmouse property represents the current horizontal position of the mouse in relation to the registration point of a particular movie (Figure 14.13).

Figure 14.13Figure 14.13 Each movie's _xmouse value is based on the horizontal distance from the mouse to that movie's registration point (indicated by a plus sign [+] in this graphic).


The following script evaluates the current horizontal position of the mouse, in relation to the registration point of the movie clip myMovieClip, each time the mouse is moved. That value is then displayed in a dynamic text field (named message) on the main timeline:

onClipEvent(mouseMove){
  _root.message.text = _root.myMovieClip._xmouse;
} 

_xscale (can be set and read)

This property represents the percentage a movie or movie clip has been scaled horizontally from its original size, as the result of previous actions in which its _xscale property was changed. Thus, if a movie has been scaled to 50 percent of its original size, the value of its _xscale property is 50.

The following script evaluates, when the release mouse event occurs, the amount that myMovieClip has been scaled from its original size. If it's more than 100 percent, it will be reset to 100 percent; otherwise, its size is not changed:

on(release){
  if(_root.myMovieClip._xscale > 100){
    _root.myMovieClip._xscale = 100;
  }
} 

_y (can be set and read)

The _y property of a movie represents the vertical distance between its registration point and the registration point of its parent movie.

See the _x property script for an example of how this property works.

_ymouse (read-only)

The _ymouse property represents the current vertical position of the mouse in relation to the registration point of a particular movie.

See the _xmouse property script for an example of how this property works.

_yscale (can be set and read)

This property represents the percentage a movie or movie clip has been scaled vertically from its original size, as the result of previous actions in which its _yscale property was changed (Figure 14.14).

For an example of this type of script, see the _xscale script sample above.

Figure 14.14Figure 14.14 The _xscale and _yscale properties let you scale a movie's size based on percentage amounts.


NOTE

In addition to the properties discussed here,when movie clip instances are treated as buttons (see Chapter 7,"Symbols") they have several additional properties pertaining to button functionality.These allow you to enable/disable them,display the hand cursor when the mouse passes over them,and more.You can access these properties via the Toolbox List window at Objects > Movie > Movie Clip > Properties.

Methods

MovieClip object methods allow you to perform all sorts of dynamic functions while your movie plays. These include duplicating movie clip instances, making them drag-gable, masking them, and more. Since methods are much more dynamic than properties, we'll cover them in the next chapter, "Using ActionScript in Your Projects," where we'll use them in a series of mini-projects.

Number Object

An instance of the Number object holds a numerical value (for example, 3 or 94234 or 54). You can create instances of the Number object in one of two ways:

money = new Number(27); 

Or

money = 27; 

The latter is the more common way due to its simplicity.

Selection Object (Global)

The Selection object allows you to retrieve information or to set characteristics relating to selected items in your movies, most notably text fields that have focus. When the cursor is in an area of a text field, that field is said to be "in focus." You can use the Selection object to set the focus to a specific text field, to find out which text field is currently in focus, or even to programmatically select specific chunks of text in a field so that you can manipulate them in some way.

A text field must be given focus before any methods of the Selection object can be used with the field. The user can give a field focus by clicking within it, or you can manually set it using the following syntax:

Selection.setFocus(myTextField); 

Here we've set the focus as the text field named myTextField. Using the setFocus() method can be helpful if you wish to place the cursor in a particular form field, when a user enters a scene containing a form. Once a field is in focus, we can highlight a portion of it using the setSelection() method.

The following script, for example, will highlight Characters 11 through 19 in the field that currently has focus (by highlighting, we mean that black text against a white background will appear as white text against a black background) (Figure14.15):

Selection.setSelection(11, 19); 

Figure 14.15Figure 14.15 When a text field has focus, you can use the setSelection() method to select a section of text within it (causing it to appear highlighted). Once it's selected, you can change or otherwise manipulate the text.

Sound Object

Sound objects let you manipulate aspects of sound, such as volume and panning, in your movies. In addition, the Sound object provides a means of dynamically attaching sounds that exist in the library, or loading external MP3s into you movie as it plays. As with the Color object, you create a Sound object instance, associate it with a movie, and then use Sound object methods to control the sound of that movie (Figure 14.16). Take a look at the following script:

on (release) {
  _//create a new Sound object when this button is released.
  mySound = new Sound (_root.myMovieClip);
  mySound.setVolume (75);
  mySound.setPan (-50);
} 

Figure 14.16Figure 14.16 As with the Color object, when you create a Sound object instance, it's associated with a particular movie, whose sound you can control using the methods available to the Sound object.


Let's take a closer look at each line of the script.

mySound = new Sound (_root.myMovieClip); 

The line above creates a new Sound object instance (named mySound), and attaches it to a movie clip instance named myMovieClip.

NOTE

If you don't define a specific movie when creating a Sound object, it will affect all existing sounds on all timelines in the Flash Player window.

mySound.setVolume(75); 

This line lowers the overall volume of any sounds on myMovieClip's timeline to 75 percent of their originally set volume. This means that if there are several sounds playing at different volumes on the timeline, the volume of each will decrease by 25 percent, but their relative volumes will remain the same.

mySound.setPan(–100); 

The line above sets the pan (speaker balance) of the sounds on myMovieClip's time-line. A value of -100 means that the sound will only play in the left speaker; a value of 100 means that it will only play in the right speaker. A value of 0 means the sound will output equally from both speakers.

To load an external MP3 file into an instance of the Sound object, you employ the loadSound() method. The parameters for this method allow you to specify the location of the external file, and whether or not it should be treated as an event or streamed sound (see Chapter 5, "Sound," for more information). Take a look at the following example:

myLoadedSound = new Sound();
myLoadedSound.loadSound("myMP3File.mp3", true); 

The first line of this script creates a Sound object instance named myLoadedSound. The second line uses the loadSound() method to load the external MP3 file named myMP3File.mp3 into the myLoadedSound Sound object instance. The second parameter, true, will cause the loaded sound to be treated as a streamed sound, meaning it will begin playing as soon as enough data has been downloaded.

If this setting were changed to false, the loaded sound would be treated as an event sound, meaning the entire file would be downloaded before the start() method could be employed, to initiate playback of the loaded sound. Invoking the start() method before the sound has completely loaded will have no effect. To automatically initiate a loaded (event) sound's playback as soon as it has finished loading, we can incorporate an onLoad event handler in the following manner:

myLoadedSound = new Sound();
myLoadedSound.loadSound("myMP3File.mp3", false);
myLoadedSound.onLoad = function(){
  myLoadedSound.start();
} 

Here you can see that we've implemented an event handler method (in the last three lines of script), so that when the external file has finished loading into the myLoaded-Sound Sound object instance, it triggers an unnamed function whose sole function is to initiate the playback of myLoadedSound.

NOTE

For detailed information on event handler methods, see Chapter 13, "Understanding ActionScript."

String Objects (Instances)

An instance of the String object—which holds a string value such as "Hello" or "What did you eat for lunch today"—can be created in one of two ways:

favoriteFood = new String("Pizza"); 

Or

favoriteFood = "Pizza"; 

The latter is the more commonly used, just because it's simpler.

Using the methods available to the String object, you can manipulate string values such as those that exist in input and dynamic text fields. The following demonstrates some of the things you can do with strings.

TIP

Both variables and text field instances can contain string values. When a variable contains a string value, String object methods are invoked in the following manner: myVariable.toLowercase(), which will convert the string value of the variable to all lowercase characters. When a text field contains text, the value of its text property (such as myTextField.text) can be considered an instance of the String object. As such, you can use String object methods to directly manipulate the text within the field; for example, myTextField.text.toLowerCase() will convert the text in the field to all lowercase characters.The sample code below can be changed as described for use in either circumstance.

Let's assume there's a dynamic text field on the stage named myText, which contains the text "Creative Web Animation." Take a look at the following script:

myVariable = myText.text.charAt(4); 

Using the charAt() method, the expression to the right of the equals sign is used to locate the fifth character in the myText text field, which is then assigned as the value of myVariable. As a result, the value assigned to myVariable is "t". This is because counting from the left (with C being 0), t is the fifth character in the text string "Creative Web Animation" (Figure 14.17).

Figure 14.17Figure 14.17 The first character in a string value is always assigned an index value of 0, the next character a value of 1, and so on.

NOTE

Within strings, spaces are counted as characters.

The following example demonstrates how you could use this method to check the validity of a phone number entered by the user. Assume there are two text fields on the stage, one named phone (into which the user enters a phone number, including area code) and another named myMessage (which will display a message, depending on the validity of the phone number entered). The user is asked to enter his or her phone number, then press the button that has the following script attached to it:

on(release){
  if(phone.text.charAt(3) != "-" || phone.text.charAt(7) != "-") {
    myMessage.text = "That is an invalid phone number!";
  }else{
    myMessage.text = "That is a valid phone number!";
  }
} 

The if statement in this script states that "if the fourth or eighth characters in the phone text field are not dashes, display 'That is an invalid phone number!' in the myMessage text field. Otherwise, display 'That is a valid phone number!' "

Next we'll look at the substring() method, which allows you to extract a portion of a string. The syntax for this method is as follows:

nameOfField.text.substring (from, to); 

In the above line of script, nameOfField is the instance name of the text field whose text property (string) you wish to evaluate. The from parameter value is the character number (counted from the left of the string, beginning with 0) at which you wish the extraction to begin; and the to parameter value specifies the character number (again, from the left) that should serve as the ending point for the extraction.

Take a look at the following example, which assumes there is a dynamic text field on the stage named myText, which contains a text property (string) value of "Macromedia".

myVariable = myText.substring(3, 7); 

As you can see from the script, the section of the string to be extracted begins with the character at Position 3 (or r), and extends to the character at Position 7 (or e). Thus, myVariable is assigned a value of "rome".

You would use the substring() method to isolate parts of strings, so that they could be evaluated separately from the overall string itself. Consider the following example.

Imagine a dynamic text field on the stage with an instance name of title. If a user were to enter the text "Dr. Frankenstein" in the field and push a button, the script below would be executed:

on(release){
  if(title.text.substring(0, 2) == "Ms."){
    myMessage.text = "Hello Madam.";
  }else if(title.text.substring(0, 2) == "Dr."){
    myMessage.text = "Hello Doctor.";
  }
} 

Based on the information entered into the text field title, when this script has executed, another text field named myMessage will display the string "Hello Doctor."

You can use the toUpperCase() and toLowerCase() methods to convert a string to all uppercase or all lowercase characters. Take a look at the following example:

myText.text.toUpperCase(); 

If myText contains a string value of "Creative Web Animation!" this will change it to read "CREATIVE WEB ANIMATION!"

String object instances have a single property, length, which is a numeric value based on the number of characters in a string. For example, if you had a text element that contained the string "Flash," its length would have a numeric value of 5 because the word Flash has five characters.

You can use this property to easily check the length of strings—for example, to verify data that must contain a specific number of characters, such as Zip codes and phone numbers.

Say you have a text field on the stage named zipCode, in which a user has entered the text 46293. The user pushes a button, and the script below is executed:

on(release){
  if(zipCode.text.length == 5) {
    myMessage.text = "That is a valid Zip code.";
  }else{
    myMessage.text = "Please enter a valid Zip code.";
  }
} 

Based on the information entered into the zipCode text field, when this script has executed, another text field named myMessage will display the string "That is a valid Zip code."

Stage Object (Global)

The Stage object allows you to control and get information about stage characteristics, such as alignment, width, height, and so on. Take a look at the following script:

Stage.align = "TL";
Stage.scaleMode = "noBorder"; 

You could use these two lines of script to dynamically set (that is, override) the alignment and scaling settings that are set with the <OBJECT> and <EMBED> tags when your movie is embedded on an HTML page—giving you control over how your movie is presented on an HTML page, even as it plays.

NOTE

For information about movie settings available within the <OBJECT> and <EMBED> tags, see Chapter 20,"Publishing."

TextField Object

You create instances of TextField objects whenever you place an input or dynamic text field on the stage. However, you can also create them dynamically using the create-TextField() method of the MovieClip object (more on this in a moment). Whichever way you create a text field, you must assign an instance name to it in order to control it dynamically via ActionScript.

Since text field instances always belong to a particular timeline, the createTextField() method—which dynamically creates a text field instance on a particular timeline—is actually a method of the MovieClip object (rather than the TextField object, as you might think). Using this method, you can create a text field on any present timeline by using syntax that resembles the following:

targetPath.createTextField(instanceName, depth, x, y, width, height); 

The following sample script will create a text field in the movie at the target path of _root.myFormClip, and assign it a depth of 1, an x position of 50, a y position of 100, a width of 150, and a height of 20 (Figure 14.18):

_root.myFormClip.createTextField("age", 1, 50, 100, 150, 20); 

Figure 14.18Figure 14.18 The x and y coordinates defined using the createTextField() method are calculated relative to the registration point of the movie in which the text field instance is being created (usually its top-left corner).


TIP

Although you wouldn't know it by looking at the properties available to text field instances in the Toolbox List window of the Actions panel, they share several properties with movie clip instances.These include _alpha, _height, _name, _rotation, _width, _x, _xmouse, _xscale, _y, _ymouse, and _yscale. Properties for individual instances can be set or read at any time using the following syntax: nameOfField._property

Once a dynamic text field has been created, users can interact with it (and you can control it via ActionScript) just as you would a text field that had been manually placed on stage.

The TextField object contains several methods that allow you to format text in the field using instances of the TextFormat object, which we'll look at in the next section.

By using properties of the TextField object, you can dynamically set (and read) details such as the following:

  • Whether a text field will resize automatically as text is typed into it:

    myTextField.autoSize = "left";
  • Whether a text field has a border:

    myTextField.border = true;
  • Whether the field can interpret HTML text:

    myTextField.html = true;
  • HTML-formatted text displayed in the field:

    myTextField.htmlText = "<b>Bold text</b><i>Italicized text</i>";
  • The maximum number of characters the user can enter into a field:

    myTextField.maxChars = 25;
  • Whether text in the field is selectable or not:

    myTextField.selectable = false;
  • Regular text (non-HTML-formatted) displayed in the field:

    myTextField.text = "I want a new iMac!";

Scrolling Text Vertically

Scrolling is one of the most common tasks associated with viewing text in a field.Although Flash MX provides a Scrollbar component to quickly add this type of functionality (see "Scrollbar Component" in Chapter 15), it's worth understanding the basic functionality so that you can incorporate special scrolling features,such as text bookmarks,into your own projects.

Two properties of the Text Field object make vertical scrolling possible:

    scroll Property

  • Syntax: myTextField.scroll

The scroll property is a numeric value that represents the line number of the topmost visible line currently displayed in an input or dynamic text field.Thus,if the text field has ten lines of text and the user has scrolled to the point where Line 4 is the topmost visible line, the scroll value for this text element would be 4.This value is constantly updated as your movie plays.It can be evaluated in expressions, or you can create buttons that reset the topmost line to wherever you want (see script that follows).

The following script uses an expression to evaluate the current scroll property of the text field named myTextField. If the value is greater than 3, the movie will stop playing:

if (myTextField.scroll > 3) {
  stop();
}

The following script shows a mouse event that will cause the text field named myTextField to make Line 6 its topmost visible line (text bookmark functionality):

on (release) {
  myTextField.scroll = 6;
} 

maxscroll Property

  • Syntax: myTextField.maxscroll

The maxscroll property is a numeric value that represents the line number of the topmost scrol-lable line in an input or dynamic text field.If you have a text field that is high enough only to show two lines of text even though it actually contains five, the maxscroll value is 4. This is because at its highest scroll point, Line 4 is the topmost visible line. If a text field contains ten lines of text but can only display four lines at a time, the maxscroll value for this text field would be 7.This is because at its highest scroll point, Line 7 is the topmost visible line (Figure 14.19).

Figure 14.19Figure 14.19 In a ten-line text field that can only display four lines at a time, Line 7 would be the maxscroll value.


You can use the value in an expression attached to a button instance in order to create a looping scroll—that is, one in which a text element's text scrolls continuously (see the script below).

The following script causes the text field named myTextField to go to a line number based on the value of count, which is updated with each click of the button. Also, with each button-click the value of count is compared to the value of myTextField.maxscroll. When the value of count equals the value of myTextField.maxscroll, this means the end of the scroll has been reached, and the count is reset so that with the next button-click, the text field will display Line 1 and start the process over again:

on (release) {
  ++count
  myTextField.scroll = count;
  if (count == myTextField.maxscroll) {
    count = 0;
  }
} 

TextFormat Object (Instances)

TextFormat objects are used to change the format of text displayed in text fields. Once created, you apply the TextFormat object to a text field using the setTextFormat() or setNewTextFormat() method of the TextField object.

You create and style (set the formatting characteristics for) instances of the TextFormat object in the following manner:

format1 = new TextFormat();
with (format1){
  align = "left";
  bold = true;
  color = 0x003366;
  italic = true;
} 

The first line in this script creates a new instance of the TextFormat object, named format1. A with statement is then used to define several formatting characteristics for this instance. Once you've created a TextFormat object, you can apply it to a text field in several ways: to all of the text in a field, to a portion of text in a field, or to any new text entered into the field. Take a look at the following examples:

myTextField.setTextFormat(format1); 

The above script will apply the formatting of the format1 TextFormat object instance to all text in the myTextField instance (and in the process will replace any existing formatting).

myTextField.setTextFormat(5, 25, format1); 

The above line of script will only apply format1's formatting to the characters in myTextField between Positions 5 and 25 (Figure 14.20).

Figure 14.20Figure 14.20 The setTextFormat() method allows you to format all the text in a field, or just portions of it.

If you want the current text in a field to maintain its formatting, while styling any new text entered into the field, you would use the setNewTextFormat() method as shown:

myTextField.setNewTextFormat(format1); 

Any new text entered into the field will adopt the formatting described by the format1 TextFormat object instance.

A project can contain multiple instances of the TextFormat object, any of which can be applied to text fields or portions of text fields, as just discussed.

Properties of the TextFormat object allow you to define margins, tab stops, and even a URL that will be opened when text styled in that format is clicked.

XML Object

Instances of the XML object are used to work with chunks of data that have been formatted in XML. However, to really understand this object's use, you need a basic grasp of XML-formatted data.

XML is a language for structuring data; it resembles HTML code in that it uses tags, attributes, and values. However, the similarity ends there: While HTML uses prede-fined tags (for example, <body>, <head>, and <html>), an XML document contains tags that you define. Take a look at the following XML-structured document:

<FlashUsers>
  <Person>
    <Firstname>Derek</Firstname>
    <FavShow Network="CBS">JAG</FavShow>
  </Person>
  <Person>
    <Firstname>Jack</Firstname>
    <FavShow Network="HGTV">Surprise Gardener</FavShow>
  </Person>
</FlashUsers> 

This document represents a list of Flash users, and includes their names and information about their favorite TV shows. There are two users listed. As you can see, the structure of the document is similar to that of an HTML page. There are opening tags (<Person>), with accompanying closing tags (</Person>). The difference with these

tags is that we made them up (their names), in order to identify the data between them. In fact, the tags have no purpose other than to describe this data. They can't create anything (as an HTML <table> tag does) or format anything (as the HTML <b> does, to make text bold). As you can see, just as HTML tags are nested (one tag is actually contained within another), some XML tags are nested in order to give the data within the document a hierarchical structure, something we'll explore shortly.

Let's proceed through the steps you would employ to load it into Flash, so that you know how to access its data. We'll assume that the XML document is named flashUsers.xml (an XML document can be created with any simple text editor by saving a text document with an .xml extension).

The first step in getting this data into Flash is creating an XML object instance, which would look like the following:

myXML = new XML(); 

The above script creates a new XML object instance named myXML. Next, we need to load our external XML document into this object instance. Before we do so, however, we'll add a line below the one above that reads:

myXML.ignoreWhite = true; 

This line of script will cause any XML data loaded into the myXML XML object instance to be stripped of carriage returns, spaces, and so on—all of which can cause the XML data to be read incorrectly by Flash. Next, we add the action for loading the document, as shown below:

myXML.load("flashUsers.xml"); 

The above line of script will load the XML data in the flashUsers.xml file into the myXML XML object instance.

NOTE

It's typical to define an event handler method for the XML object instance (such as myXML.onLoad = nameOfFunction;), prior to loading an external document.This enables you to call a function (once the external data has finished loading) to extract data from the loaded-in XML.The focus of our discussion here is how Flash interprets XML, not the mechanics of its extraction. For more information on this, see Chapter 21,"Projects."

Each beginning and ending tag group in the loaded XML document is called a node. The above document has a root node of <FlashUsers> (Figure 14.21). The value of everything between the <FlashUsers> and </FlashUsers> tags can be accessed using the following code:

myVariable = myXML.firstChild; 

Figure 14.21Figure 14.21 Each beginning and ending tag group in a loaded XML document is called a node.The node structure determines the code required to navigate the document's data.

As you can see, even though <FlashUsers> is the root node, it's also the first child node of the overall document. To move deeper into the node hierarchy, the next line of script allows us to access the value of everything between the first opening <Person> and </Person> tags:

myVariable = myXML.firstChild.firstChild; 

Here, myVariable has a value of:

<Person>
  <Firstname>Derek</Firstname>
  <FavShow Network="CBS">JAG</FavShow>
</Person> 

To go deeper still, the following line:

myVariable = myXML.firstChild.firstChild.firstChild; 

will assign myVariable a value of:

<Firstname>Derek</Firstname> 

And finally, the following:

myVariable = myXML.firstChild.firstChild.firstChild.firstChild; 

will assign myVariable a value of:

    Derek 

Whew! It takes some time to get there, but that's how it's done. As you can see, the firstChild property is used to stair-step your way down the XML object's node hierarchy. This property denotes the first node in the next level within the document.

But how do you get the value of Jack, which is in the second <Person> node of our document? This is where the concept of sibling nodes comes into play. A sibling node is simply the next node in the same level of the XML document's structure. For example, the first <Person> node is a sibling of the second <Person> node, while the <First-name> node is a sibling of the <FavShow> node (Figure 14.22). Thus, to get to the value of Jack, you would use the following syntax:

myVariable = myXML.firstChild.firstChild.nextSibling.firstChild.firstChild; 

Figure 14.22Figure 14.22 Sibling nodes are nodes that exist in the same level of an XML document's structure.

Notice the addition of the nextSibling property. This basically tells the program to look in <FlashUsers>, then <Person>, then skip to the next <Person>, then <Firstname>, then the value of <Firstname>, which is Jack. This can be a tricky concept, so you should review it a few times if necessary.

TIP

There are techniques that make navigating between nodes easier. For more information, see Chapter 21,"Projects."

Let's look at one more aspect of our XML document. You'll notice that the <FavShow> tag has an attribute named Network. To access this value (for the first <Person> node), you would use the following syntax:

myVariable =
myXML.firstChild.firstChild.firstChild.nextSibling.attributes.Network 

In essence, this states, "Look in <FlashUsers>, then <Person>, then <Firstname>, then skip to the next sibling of <Firstname> (which is <FavShow>), then the value of the attribute at this node with the name Network." In this case, myVariable is assigned a value of "CBS".

These are just a few samples of how XML can be used in a Flash project. If you're ready to push Flash to its limits, XML is a language worth learning—and if you know how HTML works, XML should be a breeze.

TIP

For more information on XML, visit the XML home page at http://www.xml.com.

  • + Share This
  • 🔖 Save To Your Account