ActionScript 3.0 for Journalists

Tutorial: ActionScript 3.0 for Journalists


flash actionscript

ActionScript is a scripting language that extends the Flash software program. One can only get so far into Flash before they will need to work with code.

For most journalists, learning ActionScript can be an intimidating process. Programming languages are filled with esoteric commands and letters. But once the elements of the language are broken down into small digestible pieces, most people will find learning ActionScript is on par with pre-algebra math.

Learning to code requires thinking abstractly and lots of patience. In much the same way one learns a new spoken language, learning ActionScript requires understanding the punctuation and grammatical rules that it is built upon.

ActionScript is built on a standards technology known as ECMAScript, which means it is very similar – and in some cases identical – to JavaScript.

Differences Between ActionScript 2.0 (AS2) and ActionScript 3.0 (AS3)

In 2006, Adobe restructured the ActionScript language. The new version added several features that made it very powerful for Flash developers, but at the same time made it much more difficult for the average user to learn. This tutorial will cover the newer ActionScript 3.0. Even though Adobe has continued to maintain support for ActionScript 2.0 in Flash, most components and third-party programs now require knowledge of ActionScript 3.0. Here are some key differences:

ActionScript 2.0

  1. More flexible, loosely typed. (You can make some mistakes and the program will still run)
  2. More procedural in format. (follow the steps from top down)
  3. Harder to scale or reuse code.

ActionScript 3.0

  1. Strictly typed (throws errors if you make mistakes)
  2. More object oriented, modular and abstract.
  3. Very scalable, reusable

This tutorial will demonstrate the basics of ActionScript 3.0 using Flash Professional CS4. This is not an introduction to the Flash program itself. This tutorial is designed for people who have had some introduction to the Flash interface and want to learn ActionScript more in-depth. Note: only Flash versions CS3 and above will work with ActionScript 3.0.

Variables and Syntax

When learning any spoken language, some of the first things that are generally covered are basic punctuation and grammar rules. The same could be said with programming languages. ActionScript follows some universal conventions that apply to the majority of programming languages.

Due to the strictly-typed nature of ActionScript 3.0, most of these example will not work just yet if you attempt them in Flash. This part of the tutorial is meant to be read without performing the examples. It will build up to the point where the examples will be meant to follow along using your own copy of Flash.

Using variables to store information

A variable is one of the most basic and fundamental parts of coding. Much like algebra, a variable is a letter or a word used to represent a value. Take the following example:

x = 7

In this example we have the letter x representing a number, 7. We know that every time we see the letter x, that it really stands for a number.

The equals character, not what you think

There is a minor but very important difference between algebraic expressions and programming expressions. That difference lies in the equals symbol. In algebra, a single equals character (=) represents an equivalency. It means both sides of the equals character must be the same. However, this is not the case with programming. In most programming languages, including ActionScript, a single equals symbol represents something called the assignment operator. An equals character takes the value that is on the right side, and assigns it to the variable on the left side of the equation. Take the following example:

x = 7 
k = 15 
x = k

What is the value of x? If this were an algebraic expression, this would simply be “not true” or “false” because it is obvious that x and k have different values. However, if this were a programmatic expression, the value of x would be 15. Why? Let’s start from the top. x = 7, check. k = 15, got that. x = k, in this last line of code, we are replacing the value of x, with the value of k. Any time a single equals character is used, it assigns a value from the right side to the left side.

Semicolon; The period of ActionScript

In ActionScript, a semicolon (;) is much like a period in the English language. It ends each statement and tells Flash to move on to the next statement of code. However, one difference between English and ActionScript is that typically every “sentence” or statement of code, starts on a new line. While this is not a requirement, it is a best practice that allows the code to stay readable.


i = 7; 
k = 15; 
age = 21;

Notice how each line of code has a semicolon at the end. There are some exceptions to this rule that we will get to later. Also notice the variable age. Unlike algebra, variables are almost always words in ActionScript, not just single letters. This is a good practice so that we know what is stored in the variable. In fact, this will be the last time we use a single letter as a variable in this tutorial.

Variables, store more than just numbers

Variables can store more than just numbers. In fact, in ActionScript you can use a variable to store pretty much anything in the program (more on that later). For now, it is important to know how to store different datatypes. In this example, we can see that we can store words or numbers:

age = 21; 
firstName = "John"; 
lastName = firstName;

If we want to assign a number to a variable, the process is pretty basic. But if we want to store a word (also called a string), you will need to put quotes around the word to indicate that you want to store the literal word itself – in this case the word “John”. Without quotes, Flash will think you want to assign the value of another variable. For example, in the last line of code from above, the variable lastName stores the value of another variable, because there are no quotes around firstName. Just remember, putting quotes around a value represents the literal, or intrinsic value, of the word. No quotes means Flash will think it is variable.

Colon, specifying a datatype

The colon character is something that is often used with ActionScript 3.0. The colon (:) tells Flash the type of data that is to be stored in a variable. This part will require you to first learn a few of the different datatypes. (Also note that datatype names are case sensitive and are almost always uppercase) A Number is just what is sounds like, a numeric value. A String is a word or sentence in quotes. A Boolean is a datatype with only two possible values, true or false. A Boolean is named after George Boole, the inventor of Boolean Logic.

age:Number = 21; 
firstName:String = "John"; 
lastName:String = "Smith"; 
oldEnoughToDrink:Boolean = true;

Notice the placement of the colon. The colon is used to describe the type of data of the variable preceding it. You only have to include the colon the first time you use each variable. After that, you will not have to use the colon for that variable again.

Var keyword, used to declare a variable

The first time you use any variable in a Flash program, you must include the keyword “var” in front of it. This is called the declaration. By declaring a new variable, you are telling Flash the name of your new variable and how you intend to use it (by using the colon character from above). When you declare a variable, Flash will do a bunch of technical things like allocate memory for your variable.

var age:Number = 21; 
var firstName:String = "Jane"; 
var lastName:String = "Smith"; 
lastName = "Doe"; age = 22;

Pay attention to the last two lines of code in the example above. We have reassigned the lastName variable. Maybe Jane Smith remarried and changed her last name to Doe. Since we have already declared the lastName variable, we no longer need the var command and the colon and datatype.

At this point in the tutorial, the code above would actually work within Flash. If you do not declare a variable the first time you use it, Flash will likely throw an error.

CamelCase and other variable naming rules

You might have noticed by now that many variables are actually multiple words smashed together with no spaces. We capitalize each new word in the phrase in order to make it readable and eliminate ambiguities. This convention is called camel case. It allows us to make variable names specific enough so that we know what information it stores. Variables always start with a lower case letter. We do this so it won’t be confused with datatypes and something called Classes, which are always uppercase. (more on that later).

These are the rules for variable names:

  1. No spaces in variable names. Best practice is to use camel case for different words
  2. Must start with a letter. Though, you can have numbers after the first character.
  3. No symbols. Only letters, numbers and underscores ( _ ) can be used.
  4. Cannot use a variable name reserved by Flash. If your variable turns blue when you type it, that word has special meaning in Flash and is reserved. For example, Flash reserves the word text. Try using something like myText or descriptionText instead.

The Trace Command

In this section, we will put into practice some of the concepts covered in the syntax and variables section. This section is a follow-along instruction. If you have your own copy of Flash CS3 or CS4, open it now and choose ActionScript 3.0 from the new document menu.

Choose ActionScript 3.0 from the new document menu

Once inside the Flash program, select the Window menu at the top of the screen, and choose Actions. This will open the ActionScript window.

The Actions option is in the window pull down menu.

When writing ActionScript, it does not matter what line number you put your code on. The line number are for your reference only. It is generally acceptable to spread the code out by inserting some carriage returns.

The trace command

Trace is a command in ActionScript that will become invaluable throughout the process of learning to code. Trace does only one thing: It sends a message (also known as an expression) to the output window when you test your program. These messages allow you to know what is going on with your program, and are helpful in the debugging process. Trace commands can only be seen during the authoring phase. This means that if you publish a Flash project to the Web with trace commands, the public will not see these messages.

Let’s try it out. In your ActionScript window type trace(“Hello World!”);

tracing the message hello world

Now test your program. Mac users can do this by holding down the Command key on their keyboard, and pressing Return. PC users should hold down the Ctrl key and press Return. Or, find the test movie option under the control menu at the top of the screen.

Once you do this, you will notice your project simply shows a blank stage. That’s because we haven’t actually produced a project yet. However, behind our movie, we will see the message we typed in the output window.

The Flash output window showing hello world

Pretty simple so far. It’s important to notice that the trace command only caused our exact message to display because we put it in quotes. Remember, when quotes surround text, it becomes a string of text.

Tracing variables

Let’s try to output a variable. Close the project preview window to get back to your Actions window. Then type the following code:

var myName:String = "Jeremy"; 

As you type in this code, you may notice that when you type the colon character, a drop down menu appears.

Code hints in the Actions window of Flash

This is called a code hint and it’s optional. It simply a way for Flash to give you a list of the available options. In this case, Flash is giving you a list of built-in datatypes and classes. You can either scroll down and select String or begin typing the word. As you type the letters, the selection will drill down and eventually highlight the option you want. When it finds it, you can press the return key and it will select that option.

Trace outputing the myname variable

When you test this program, you will notice that the output window does not display the actual “myName” text, but the value of the myName variable we created. Try going back into the code and assigning your own name to the myName variable and test it again.

Concatenation of strings and variables

In programming languages, the process of concatenation means linking several strings of text together to form one sentence. In ActionScript, we use the ( + ) symbol to link together strings of text. Type the following into your Actions window and test your program:

trace("Jeremy" + " " + "Rue");

Concatenating two strings

Notice how Flash will connect the three strings together including the second string, which is nothing more than a space to separate the words. Let’s take this a step further:

var firstName:String = "Jeremy"; 
var lastName:String = "Rue"; 
trace(firstName + " " + lastName);

Concatenating two strings

As we can see in this last example, we are using variables to store information and send that information to the output window. Event though these examples might not seem like they have a lot of applicability just yet, it sets a foundation of how everything in ActionScript works.

This last example shows how some code might appear in a video game program:

var firstName:String = "Jeremy"; 
var score:Number = 320; 
trace("Congratulations " + firstName + ", you earned " + score + " points");

Concatenating strings with numbers

Writing code like this makes it reusable. All we have to do is change the firstName and score variables and the message will adapt to many situations.

The Anatomy of a Function

For many people who studied under ActionScript 2.0, functions might seem like one of the more drastic changes in ActionScript 3.0. However, they haven’t actually changed at all, it is just that Flash is now more strict in the way they are typed out. But, before we even go that far, let take a look at how a function works.

It is best to think of a function as a list of instructions, like a recipe. It is a block of code that is independent from the rest of the program. It just sits there, waiting, until you call upon it to execute. Putting code into functions is a way to make your program modular. Each function can have its own task, and can be run whenever you need.

Structure of a function

First, a function requires the actual word function. This is a word reserved by Flash, and it will turn blue as soon as you type it. This tells Flash you are writing a new function.


Next, you need a name for your function. This name follows all of the standard conventions for naming variables. No spaces; use only numbers, letters and underscores; must start with a letter and standard practice is that function names are always lowercase.

function showMessage

Next we need a set of parenthesis. These parentheses will serve a purpose in one of the next steps, but for now, we will place them there as required by Flash.

function showMessage()

The next part is specifying the boundary of the code that will be included in the function. We use the curly brackets on the keyboard: { }, not to be confused with the straight brackets. The first bracket is the opening of the function, and the second one is where the function closes. Any code between the brackets is what is contained within the function.

function showMessage(){


Notice that functions do not need semicolons. They are one exception to the rule. However, all of the code contained within a function needs a semicolon after each line, to end each statement.

Now let’s make a working example. First we will put some code into this function.

function showMessage(){
       trace("Hello World"); 

If we were to run this now (and feel free to try it), we would not see the message in our output window. Why? The reason is because a function does not run until you tell it to. It is nothing more than a block of code that we identify with a name. Once we are ready, we can run the function by calling it with some additional code.

Try adding the line of code showMessage() below the function. This is what we use to run this function.

function showMessage(){
      trace("Hello World"); 


A basic function in Flash

In our output window, we will see the trace command in action. Any time we want to run a function, we can simply type in the name and add a set of parenthesis.

Using function parameters

This is usually the step that most people get lost. Spend some time trying to understand how function parameters work. They become a valuable tool in advanced ActionScript coding.

Remember that parenthesis we left blank? That is actually a space for something called a parameter. We can actually put a variable in that space that can pass information to our function:

function showMessage(theMessage:String){
      trace("Hello World");


This new theMessage variable we have between the parenthesis is called a local variable. It means this variable is unique in a way that it only exists within the scope of this function, and it is temporary. We do not need the var command here, but we do need to let Flash know the type of data this variable can use.

Now we can use this temporary variable within our function:

function showMessage(theMessage:String){


If you tried running the program now, you would get an error that said you have an incorrect number of arguments, and that Flash expected one but you gave it none. That appears because when we call the function, we need to include some information to send to this parameter. Inside the parenthesis of the showMessage function call is a space for something called an argument. An argument is some data that is sent to a function parameter. In our last line of code, we’re going to put in a string of text inside the parenthesis.

function showMessage(theMessage:String){

 showMessage("Sending data to my function");

When we call this function using the last line of the code, we are sending a string of text to the function. That string of text is being stored in theMessage variable, and used within the function. Why would we do this? It allows us to make our function reusable. Try calling the function several times, sending different strings of text:

Using function arguments to send data

Specifying return type void on functions

There is a feature of functions that is rarely used by most beginners, and that is having a function return some data. In more complex situations, you can have your function return some data back to the section of code that called it. For example, imagine if someone wrote a calculator function. You could send that function two numbers, and the function would say add those two numbers, then return the answer back to the part of the code that called it.

We are not going to write those types of functions in this tutorial, but in ActionScript 3.0, standard convention is to specify a something called a return type. Essentially, what we are going to do is tell Flash that our functions will not return any data and not worry about it. To do this we add :void just after the parentheses of every function we write. Probably 99 percent of the functions we will write will use this same void datatype that tells Flash that our function will not return any data, but it is an important part of ActionScript 3.0.

Specifying a void return type on Flash function

Using Event Listeners to call Functions

In the previous lesson, the Anatomy of a Function, we covered how to call a function using the function name and a set of parenthesis. However there is another way to call a function, and that is to use something called an event listener.

An event listener is like a trigger. This command waits or “listens” for a specific event, and when that event occurs, it will call a function.

In order to use an event listener, we must first setup an environment whereby an event occurs. Generally, the most common event in flash is the mouse click event. This event occurs whenever a person clicks on an object in flash, like a movieclip or a button. In this tutorial, we will first setup a basic button symbol in Flash that we will use as a trigger to display a message in our output window.

First, open Flash CS3 or CS4 and choose ActionScript 3.0 from the new document window.

New document window in Flash

Once in the new document we will create a simple text button to use for our example. Choose the text tool on your tool menu bar.

The text tool icon

You can adjust the font and color of your text as you wish in the properties window. Next, click on your stage and type in some dummy text to use for your button. Be sure your text is set for static text. This option will be displayed in your properties window. Dynamic text will not work inside a button.

text box on stage

Once you have your button set, make sure your text box is selected, then click on the modify menu at the top of the screen and select convert to symbol. For the symbol type we will choose button and give our symbol a unique name. This is not an identifier name used in ActionScript, but just a name for your own reference.

Convert to symbol dialogue box

Next is one of the more important steps. We need to give our button an instance name. An instance name is what identifies your button in ActionScript. It is case sensitive and must adhere to all of the same rules for variables names. (In fact, instance names are actually variable names themselves). Click on the button to select it, and in the properties box, we will name our button my_btn.

giving an instance name to our button

Now that we have our button instance name set, we can open our Actions window from the Window menu at the top of the screen and begin using the event listener features.

Event listener ActionScript code

Before we can type in the code for an event listener, we need to first have a function for our event listener to call. We will use the function from the previous lesson we made, but with one small change. In the parameter field, we must specify a variable with the datatype Event. We can call it anything we want. Most developers just use something short like “evt” or many times just the letter “e.” The Event datatype might be a little confusing. Don’t worry about it right now since we aren’t really using this. It is more of a placeholder that Flash requires, even if you do not use the event.

function showMessage(e:Event):void {
       trace("You just clicked a button on the stage");

Why do we need this Event variable as an argument? The reasons can be a little technical. In ActionScript 3.0 event listeners work by calling a function after an event occurs. But when they call that function, they automatically pass some data to that function in the form of something called an event object. In more advanced programming, we can use that event data within the function to reference the button or movieclip that was clicked on, as well as other properties.

Even if you don’t use this event argument, you still must include it. Usually it is just a matter of including e:Event in the argument field each time you write a function that might be called by an event listener.

Next, we need to write out the event listener itself. Event listeners are always attached to some type of object that they are listening to. In this case, we are going to attach an event listener to the button we created. We do this through a process called dot syntax. We will learn more about dot syntax in the Object Oriented Programing lesson.

function showMessage(e:Event):void {
       trace("You just clicked a button on the stage");

my_btn.addEventListener(MouseEvent.CLICK, showMessage);

Event listener with a function in ActionScript 3

The event listener consists of a pair of parenthesis and two arguments, separated by a comma. The first argument is the event that will trigger this event listener. The second argument lists the function that will be called once the event occurs. Note: there are other optional arguments that are beyond the scope of this tutorial.

Here are a list of some of the different mouse events you can listen for:

  1. MouseEvent.CLICK Triggers when the object is clicked and the mouse button is released.
  2. MouseEvent.DOUBLE_CLICK Triggers when the object is clicked twice rapidly.
  3. MouseEvent.MOUSE_DOWN Triggers as soon as the mouse button is pressed down on an object (release is not necessary)
  4. MouseEvent.MOUSE_UP Triggers any time the mouse is release over the object, even if it is pressed down outside the object.
  5. MouseEvent.MOUSE_OVER Triggers as soon as the mouse moves over the object, regardless if the button is pressed.
  6. MouseEvent.MOUSE_OUT Triggers when the mouse leaves the object, regardless if the button is pressed.

Test your movie and click on the button you created. Every time you click on the button, the function will run and you will see your text appear. You can put any code in this function that will execute once the button is clicked. Spend some time swapping out the different event types and see how they react to the mouse.

Listening for other type of events, like videos

Event listeners are not only for listening to mouse events like clicks. There are lots of objects in Flash that can trigger events, and thus execute a function. In this next example, we will setup a basic video player in Flash and add an event listener to listen when the video completes. In a more advanced program, this might be used to switch out the video or close the video after it is done playing.

First, start a new ActionScript 3.0 Flash document. In the Window menu at the top of the screen, select components.

Component pane in Flash CS4

Select the FLVPlayback listed under the video section, and drag it to your stage.

Video player in Flash CS4

The next step will require that you have saved your Flash document. Take note of the exact location you save your document. In order to load a video using the FLVPlayback component, the video must reside in the same location as your .fla file. You can download a sample video for this lesson here, or you can use your own video file as long as it was encoded in H.264. Make sure the sample video, countdown.flv is in the same location as your Flash document (.fla) file.

Next, select the Window menu at the top of the screen and choose component inspector. The component inspector will show you options related to your component when it selected. If you do not see the option in this image, select the video component on your stage.

component inspector in Flash CS4

Click on the source option in the component inspector, and click on the magnifying glass icon. In the next dialogue window, select the folder icon to browse to the location of your video file.

select source component dialogue box

In this example we will choose the countdown.flv sample file. Flash will read the meta data and set the correct video dimensions automatically. At this point, the video would play if we were to test our Flash project. Embedding video in Flash is that easy! But, since this is an ActionScript tutorial, we are not quite done yet. The next step is to select the video component on your stage and then give it the instance name of myVideo. The instance name box is located in your properties pane.

component instance name

With an instance name, we can now reference this component in ActionScript. Remember, all instance names must conform to the conventions outlined in the rules of variable naming.

Next, open your ActionScript dialogue box by selecting Actions under the Window menu at the top of the screen.

This time we are going to use an event that is not automatically included as a part of the core Flash package. We must use a line of code at the top of our ActionScript to include it. This is a common task in ActionScript 3.0, as it lets users include only code they need in each program.

Click on the layer named actions and open your Actions window. In the top of your action window, write out the line:


Next, we will type in our function from before, but this time we’ll trace the output “Finished!” inside our function. For the event listener, we will listen to the video event COMPLETE.

function showMessage(e:Event):void {

myVideo.addEventListener(VideoEvent.COMPLETE, showMessage);

ActionScript for detecting the end of a video

Test your movie, and click the play button if your video does not start automatically (the option to autoplay a video is located in the component inspector window). Once the video is completed, a message in your output window should let you know that the video is finished playing.

Now, you might be asking yourself how one is suppose to memorize all of these many event types. The truth is, no one does. It is all located in the Flash online documentation. We will cover how to sort through the documentation to find the commands and events you might need to run your programs. For now, try playing with some of the other video event types and see how they react when you use them. Simply replace the word “COMPLETE” with a different event type listed on Adobe’s Online Documentation page on video events.

Function and Event Listener Example

In this example, we will build a simple form to demonstrate how a function and event listener can operate in practice. The form is simple: It asks the user to enter their first name. The user enters in their first name and clicks submit. Flash takes the data from that form input, and displays a short hello message using the name that was entered into the form.

Here is a working example of the finished product:



To build this project, first launch Flash CS4 and open a new ActionScript 3.0 document. We will leave the stage dimensions and colors at their default settings.

Click on the text tool in your tool bar, and draw a text box near the top of your Stage. Then enter the text “What is your first name?” This is a static text box. This means the text box has no other functionality than to display text to the user. Feel free to choose a font of your choosing in the properties inspector. This example used Gill Sans at 33 points.

text box that displays instructions to user

Next, click on the text tool again, but this time we will make a different type of text box. This newer text box is called an input text box. It allows the user to input some text that we can assign to a variable in ActionScript. To change the text setting so that the user can input text, select input from the top menu on the property inspector.

Input text box setting in property inspector

Before we can draw the text box, we must do two more things. First we need to make sure this text box is visible to the user, so they know where they can type in text. We do this by clicking on the show border icon in the property inspector.

Checking the show border option in property inspector

Secondly, we need to embed the font we are using. When creating static text boxes, Flash takes care of the font embeds automatically for us. However, when working with input or dynamic text, we have to tell Flash which font glyphs to embed. The reason is so that Flash doesn’t have to embed every font and produce large files.

In the properties inspector, click on the Character Embedding button. Next select which glyphs you want to embed. You can type in specific characters at the bottom, or embed whole sets of characters by holding the shift key down and selecting each set. For this project, we will have the user type only their name. However we will also embed numerals and punctuation just in case the user types decides to use those characters. Hold the shift key down, and select: Uppercase, Lowercase, Numerals and Punctuation.

embedding fonts in Flash

Now we can finally draw our input text box. Place it just below the text that is already on your Stage.

In order for Flash to identify the text that is inside this text box, we must give this input text an instance name. Instance names identify elements on the Stage to ActionScript. Anything you want to reference in ActionScript needs to have an instance name and only certain elements can have instance names.

Using the selection tool (black arrow) click on your input text box you just created to select it. In your properties inspector, type in name_txt in the instance name form.

instance name

Now we will make the submit button so the user has a way to activate the response. A button can be just about anything in Flash; an image, text, a graphical shape or any combination of these. We will create a very simple button by drawing a rectangular box and adding some text on top of it. First, click on the rectangle tool in your tool palette.

rectangle tool

Change your stroke and fill color at the bottom of the tool palette. You can choose any colors, but this example used #000000 (black) for the stroke and #cccccc (gray) for the fill.

Draw a rectangle below the input text box you created.

drawing a rectangle shape

Next, click on your text tool again. But this time, switch the type of text box back to static in your properties inspector. This is important. You cannot have dynamic or input text inside a button.

switching back to static text

Draw a text box over your gray rectangle and type the word “submit.”

Next use your selection tool (black arrow) to select both the fill, the stroke and the static submit text. The easiest way to do this is to draw a box around all of them.

selecting both text and shape

In the Modify menu at the top of the screen, select Convert To Symbol. Choose button for the type of symbol and give the symbol a relevant name, like submit button. This name is only for your reference and won’t affect any part of the example. Feel free to go into the button and modify the various button states as you wish.

From the main timeline (scene 1) use the selection tool (black arrow) to select your button. Then in your properties inspector, give the button an instance name of submit_btn. Remember, instance names are case sensitive.

instance name of submit button

Next, we will draw a third text box below the submit button. This time, the type of text box will be dynamic. Dynamic text is text that you can set in ActionScript. Dynamic text boxes also require fonts to be embedded, but since we already embedded fonts with the input text box, we do not have to repeat the process (unless we we decided to use a different font for this text box). Also, make sure the text border that we set in the input text box is off.

Once you draw the dynamic text box on your stage, select it with your selection tool and give the text box an instance name response_txt. We are now ready to start with our ActionScript.

ActionScript for the Event Listener Example Form

Create a new layer in your timeline above the current layer and call it Actions. With this layer selected, click on the Window menu at the top of the screen, and choose Actions to open your Actions panel.

Where do we start? Well, we know that we want the program to display a hello message once the user clicks on the submit button. So we will use the event listener code we learned about in the last lesson to create an event listener that will activate a function when the user clicks the submit button. Let start by writing our function first:

function displayMessage(e:Event):void {


This function is incomplete. We want to fill it with code that will display our message in the response_txt text box. To set some text inside a dynamic text box in ActionScript, we use the .text property of the text box’s instance name. We would type this code as follows:

function displayMessage(e:Event):void {
       response_txt.text =

Notice the response_txt.text = portion of the code. This tells Flash that we want to assign a value to the dynamic text box called response_txt. The next part of the code is:

function displayMessage(e:Event):void {
       response_txt.text = "Hello " + name_txt.text + " how are you?";

We are taking the lesson we learned about concatenating text, but using the input text (name_txt.text) to represent the name the person typed in.

Lastly, we need to run this function when a user clicks on the submit button. We do that by adding an event listener to the button.

function displayMessage(e:Event):void {
 	response_txt.text = "Hello " + name_txt.text + " how are you?";

submit_btn.addEventListener(MouseEvent.CLICK, displayMessage);

actionscript for the example

This is an example of how we can trigger a function with an event listener. This is a fundamental task in Flash, because most Flash projects have some sort of clickable area that the user will interact with.

Object Oriented Programming

Flash, like many modern programming languages, utilizes a convention called Object Oriented Programming (OOP). The premise of OOP is to treat code like everyday objects that a person could interact with. At the core of Object Oriented Programming is the idea of using objects. Objects are pieces of code that you use in much the same way you would use a physical object in the real world.

Let’s draw an analogy to the English language. An object would be considered a noun. With nouns, we can:

  • Describe them with adjectives.
  • Perform physical tasks with verbs.

ActionScript is similar in this respect. With an object, we can describe its appearance with properties (these are like adjectives), or we can have our object perform a task using something called methods (these are like verbs). Almost every object in Flash has a set of properties and methods that allow you to perform some type of task.

Objects are derived from something called classes. For example, if an object was a car, then a class would be the factory it was made in. You can create multiple objects from a class (just like you can make lots of cars from a factory). Each of these objects are unique and are called instances.

classes and objects

MovieClips, buttons and dynamic/input text fields are all considered objects. This is why we give them instance names, to identify each one that is on our stage for ActionScript. While we have been creating text fields and buttons in Flash using symbols, in actuality we were creating objects from classes.

Object Properties

Properties are like adjectives in the English language. Just as you would describe the color or size of a car, you can use properties to describe an object in ActionScript.

As discussed in a previous lesson, ActionScript uses dot-syntax to separate an object name from its property or method. Take for example the following code which specifies the width of a text field:

response_txt.width = 300;

The first word of the code is the object that you are affecting (also known as the instance name). The period is a separator. In fact, if you were to type this code in to Flash, as soon as you typed in the period, a code hint box would appear listing all of the properties and methods that belong to the TextField class (it knows we are referring to a text field because our instance name has the _txt suffix).

code hint

As you can see, the TextField class has lots of properties, many of them for highly technical purposes. You can see a full list of properties on the Adobe AS3 Help Documentation.

One of the more notable properties of the TextField class is the text property, which specifies the contents of a text field. We just used this in our previous lesson example on functions. Here is an example of setting the text of a text field:

response_txt.text = "Here is some text.";

Using the .text property, we can easily set the text contents of a text field. This is one of the more commonly used properties with the TextField class.

Object Methods

Methods are like verbs in the English language, because the usually perform some type of action. In reality, they are simply function calls that are associated with our object. Methods are easily identifiable by the parenthesis at the end of the command.

Using our car analogy, a hypothetical method for a car class would be go() or stop() or even start(). In practice, we would put the instance name of the car first, then using dot-syntax we would include the method.


Now, this is not a real class or method. But the idea is the same. The inside of the parentheses can be used to include arguments, which is extra data that would describe how the method runs. Be careful, because in ActionScript 3.0, some methods require a certain number of arguments and if you don’t include them, the program will throw an error.

Let’s take a look at a real example of a method. We will use the TextField object we used in the previous example. One of the methods is appendText() which will append some text to what is already in the text field without replacing it. Here is how it would work:

response_txt.text = "Here is some text "; 
response_txt.appendText("...and add some more to the end");

Without the appendText method, we would have replaced the existing text in the text field. Another method is getParagraphLength() which requires one argument. The argument Flash wants is the line number of your text field where you want Flash to count the characters in a paragraph. Line numbers start on zero, so putting a 0 in the parenthesis would indicate the first paragraph in a text field.

This method is different that the others, because it returns information. It does not actually perform an action on the text field.

response_txt.text = "Lorem ipsum dolor sit amet, consectetur adipisicing."; 

Notice how we put the getParagraphLength method inside a trace command:


The reason is because getParagraph returns data – a number. So we can’t just state the method by itself. We could store the returned value to a variable, or a variety of other tasks.

Object Events

The one aspect of object that hasn’t been mentioned before is object events. Events are tied to event listeners. These are the types of events that an object will listen for before running a function. Here are a few examples from the TextField class:

responseText.addEventListener(TextEvent.TEXT_INPUT, report); 
responseText.addEventListener(Event.SCROLL, report);

In this code, Flash would run the report function (not shown here) if a certain event takes place. In the first line, Flash is listening for TEXT_INPUT. This occurs when a user types in a letter in an input text field. Perhaps you want to run a Flash script that will count the characters every time a user types in a new letter, this would be the event to use.

Events have their own classes, as you can see from the word TextEvent above just before the event type. They are associated with the main class (in this case TextField) but are a subset of a separate events category. Flash bundles the documentation so you can see what events are associated with your classes.

Conditional Statements

Conditional statements are the foundation to logical expression in virtually every programming language.

Oftentimes, you will want your program to make a decision based on a set of conditions. If a condition is true then you will want to perform some type of action, otherwise if that condition is false, then you may want your program to perform a different action.

In ActionScript, as with many languages, we do this with the if keyword. The word “if” is preceded by a set of parenthesis which contain the condition. If the condition is true, then Flash will execute the code in the curly brackets, otherwise it will ignore the statement altogether. Take the following example in which we test the variable “age” to see if the value is 21.

if(age == 21) {
      response_txt.text = "You are old enough to have a drink"; 

In this piece of code, we assess the condition (age == 21) to see if it is a true statement. The double-equals symbol is the equivalency operator, which is used to compare two values to see if they are equal. The code that is between the parentheses will only run if the condition is true, otherwise it skips over it completely.

This example has only limited practicality because it tests to see if the age variable is exactly equal to 21. Really, it should be testing if the age variable is over 21. We do this with the more than or less than operator.

if(age > 20) {
       reponse_txt.text = "You are OVER 21, you can have a drink";

Notice the difference from the previous example. We are now asking the question if the age variable is more than 20 (We check to see if it is over 20 instead of 21 because the more than does not include the value itself.)

Checking Multiple Conditions

Suppose we wanted to test if two or more conditions were true. We have a few options available to us. We need to know if we want both conditions have to be true, or if either condition could be true. This is called Boolean logic and uses the terms AND and OR to test values.

Let’s pretend we are writing an application that will test to see if a child is old enough and tall enough to go on an amusement park ride:

if(age > 12 && height > 48){
      response_txt.text = "You can ride the Ferris wheel"; 

Notice the double-ampersand which is the AND operator. In this situation BOTH conditions have to be met in order for Flash to execute the code in-between the curly brackets. But what if the requirements said that either of these conditions could be met?

if(age > 12 || height > 48){
      response_txt.text = "You can ride the Ferris wheel"; 

Notice the double-bar symbol. This is the OR operator. Either condition could be met for Flash to execute the code within the curly brackets. The only way Flash will ignore the statement is if both conditions are false.

List of available operators

Here is a table of operators that you can use in conditional statements.

Conditional Operators
Symbol Description
== The EQUIVALENCY operator requires both sides to be exactly the same for the statement to be true.
&& The AND operator requires several conditions be met in order for a statement to be true.
|| The OR operator requires one of several conditions to be met in order for the statement to be true.
> The MORE THAN operator requires the left side to be greater than the right side for the statement to be true.
< The LESS THAN operator requires the left side to be less than the right side for the statement to be true.
>= The MORE THAN OR EQUALS operator requires the left side be more than or the same as the right side for the statement to be true.
<= The LESS THAN OR EQUALS operator requires the left side be less than or the same as the right side for the statement to be true.

Here are a few examples of these operators in action:

In this example, three conditions have to be met for the response text to be shown; 1) you have to be 21 or over, 2) you have to have an ID card and 3) You have to pay the $10 cover charge

if(age >= 21 && idCard == true && cover == 10){
        response_txt.text = "Welcome to the club"; 

In this example, a photo slideshow counter in Flash has to be less than 10 or have a null value:

if (currentImage < 10 || currentImage == null){

Using the Else keyword

Let’s say the condition from any one of the examples above is not met. Flash will ignore the block code in the curly brackets and continue executing the program normally. However, in many cases you may want to execute a different set of code, but only if the condition is not met. This is where the else keyword comes into play. The else allows you to post a different block of code that will execute should the condition not be met.

if(gameScore > 1000){
        response_txt.text = "Congratulations, you passed 1,000 beating the game!";
 } else { 
       response_txt.text = "Sorry, you didn't reach score of 1,000 yet, try again.";

In this example, we use the else keyword to present a second set of brackets that presents an alternative block of code to execute should the condition be false. It is important to note the difference of using the else keyword and simply running the code without it. Flash will only run the else block of code if the condition is false. Take these two examples:

Example 1: Using else keyword

var score:Number = 1001;  
if(score > 1000){ 
        trace("You win");
 } else { 
       trace("You lose"); 

output:  you win

Example 2: Excluding the else keyword

var score:Number = 1001;  
if(score > 1000){  
       trace("You win"); 
trace("You lose");   

output:  you win you lose 

Without the else keyword, Flash will execute the code following the “if” statement. But if you include the else keyword, you create an either/or situation in which Flash only executes the code should the condition be false.

Tween Class

The Tween class is a piece of code that allows you to animate objects using ActionScript. Using the Tween class to animate an object requires only one line of code, however that one line requires multiple arguments.

Before you can use the Tween class, you must import the code in so it can be available to you. Flash automatically includes several classes that are commonly used by most people, however the Tween class (and several others) have to be manually imported. This is a way to reduce the overall size of Flash projects by not including unnecessary classes.

To import the Tween class, include the following two lines of code:

import fl.transitions.Tween;
import fl.transitions.easing.*;

You only have to include these two lines of code once for each Flash document that uses the Tween class. The class will be available to you throughout the rest of your Flash document. The second line of code has an asterisk ( * ) at the end which is a wild card and means that you will import all of the easing classes.

Using the Tween class

The Tween class has several parts. Here is a list of the arguments required to use the Tween class:

new Tween( [object], “[property]”, [easing type], [from value], [to value], [how long], [use seconds?] );

  • [object] – The instance name of the object that is being animated.
  • [property] – The property being animated. Could be anything from the x value to the alpha. Must be in quotes! Some examples are “alpha” “x” “y” “scaleX” and “scaleY.”
  • [easing type] – The easing type of how the animation will accelerate or decelerate. (see easing section below)
  • [from value] – The starting value of the property that is being animated.
  • [to value] – The ending value of the property that is being animated.
  • [how long] – How long the animation will take to play. Either in frames or seconds.
  • [use seconds?] – Should the previous [how long?] parameter refer to seconds or frames? If this is set to true, it will use seconds, if it is set to false it will use frames.

Let’s take a look at an example of a line of code that will animate a movieclip symbol called ball_mc from an x value of 50 to 400 in one second.

new Tween(ball_mc, “x”, Strong.easeOut, 50, 400, 1, true);


You can animate a number of properties, like the alpha. This allows you to fade movieclips in and out in your Flash project.

new Tween(ball_mc, “alpha”, Strong.easeOut, 1, 0, 2, true);


Easing Class Options

Performing animations is pretty straightforward with the Tween class. But what about the easing animations? The easing signifies how the animation accelerates or decelerates. There are six easing types and four ways to show those easing types. Here are the easing types:

Easing Types
Type Description
Back The animation goes past the ending or starting value and snaps back.
Bounce The animation bounces from the starting or ending value, like a ball on a basketball court.
Elastic Like the Back easing type, but with a much more spring-like effect. Goes past the starting or ending value, then springs back and forth.
None No easing. Only use with easeNone.
Regular A standard acceleration or deceleration.
Strong A more pronounced acceleration or deceleration.

Below are four ways to display each of these six easing types. You can pair up any of the six easing types with one of the following properties for describing how the easing will display.

Easing Properties
Property Description
easeIn The easing is at the beginning of the animation, and will accelerate until the end.
easeOut The easing is at the end of the animation, and will decelerate until the end.
easeInOut The easing is at both the beginning and end of the animation. It will accelerate until half way through the animation, then begin to decelerate and finish with the easing.
easeNone No easing. Only use with None ease type.


The best way to understand the combinations of easing types is to see examples. Here are a few examples of the different easing types.

The animation starts slowly and begins to accelerate through the animation.


The animation starts quickly and slows down (decelerate) through the animation.


The animation includes elements from the previous two. It accelerates until half way, then starts to decelerate in the second half of the animation.


Tweens not completing when they are declared inside functions

A common issue with tweens occurs when you try to declare a tween inside a function. In Flash ActionScript 3.0, new garbage collection features will delete variables that are inside of functions once the function completes. To prevent this from happening, you should declare a variable first outside the function, so that they will be available globally and Flash will not delete them. Once you are done with the tween, you can delete the variable yourself. This only happens when you are running a tween inside a function. Here is an example of the correct way to do this.

//declare your variable outside the function 
var myTween:Tween;   
function startTween(e:Event):void { 
        //assign the tween to the variable 
        myTween = new Tween(ball_mc, "x", Strong.easeOut, 50, 400, 2, true); 

Tween Events and methods

The Tween class, like any class, has a series of properties and events that extend its functionality beyond standard animation. A full document of the Tween class can be found on the Adobe Web help documentation.

There is a list of several methods on the Adobe Website, but this tutorial will only show three of the most commonly used events.

  • TweenEvent.MOTION_FINISH – Triggered once the animation completes. This is very useful for triggering actions that you want to occur after a tween has completed.
  • TweenEvent.MOTION_STOP – Triggered any time the animation stops. You can stop the animation (even half way through) using the stop() method.
  • TweenEvent.MOTION_RESUME – Triggered if you have stopped the tween using stop(); and restart the animation using the resume(); method.

The MOTION_FINISH tends to be one of the more common events. It is used generally to execute a function after a Tween has completed. However, to use any of these events, you must attach them to a variable. This requires you to declare a variable for your Tween. Once you declare your variable, you can use this variable to add the event listener. (Make sure your event listener comes after you declare your variable, otherwise Flash will throw an error.)

import fl.transitions.Tween; 
import fl.transitions.easing.Strong; 
import fl.transitions.TweenEvent;  

var animation:Tween = new Tween(ball_mc, "x", Strong.easeOut, 50, 400, 2, true);  
animation.addEventListener(TweenEvent.MOTION_FINISH, playAfterDone);  

function playAfterDone(e:Event):void { 
      trace("Tween is done"); 

Notice the third import line import fl.transitions.TweenEvent; This is required to include the class necessary to run Tween Events. In the example, the tween is assigned to the variable animation, and is used for our event handler. Once the Tween is finished, it will run the playAfterDone function.

Methods of the Tween class

The tween class has several methods that allow you to perform functions such as stopping your tween while it is playing, resuming the tween, rewinding the tween to the beginning after it has completed, or even having the tween play in reverse. Here is a list of some of the more common tween methods.

Tween Methods
Method Description
yourTweenVariable.stop() Stops the tween if it’s currently playing, otherwise it does nothing. Useful if you want to stop an animation before it completes.
yourTweenVariable.start() Starts the tween from the beginning, even if you stopped it using the stop() method.
yourTweenVariable.resume() Resumes the tween from the current point in which it was stopped using the stop() method.
yourTweenVariable.rewind() Rewind is useful to put the animation back to its starting position once it completes. It does not play the animation again.
yourTweenVariable.fforward() The opposite of rewind(), and much like the stop() method this method will instantly end the animation to the last frame. Could be useful in situations where you want to allow the user to skip a long animation.
yourTweenVariable.yoyo() Plays the animation in reverse.

About this Tutorial

This tutorial was written by Jeremy Rue, multimedia training instructor for News21 and the Knight Digital Media Center at the UC Berkeley Graduate School of Journalism. He can be reached using the contact form on the journalism school’s Web site.

Republishing Policy

This content may not be republished in print or digital form without express written permission from Berkeley Advanced Media Institute. Please see our Content Redistribution Policy at