Flash Explained

Learn Flash easily.

Learning to use the conditional if/else statement in Flash 8

October 16th, 2008 | Author: Luka | Category: ActionScript


In this lesson, I will explain to you what the ActionScript if/else conditional statement is and how to use it in your Flash movies through a visual example. You will learn:

  • What is a conditional statement,
  • What is a circumstance,
  • Various comparison operators and more.

Click on the dark area in the Flash movie below to see how the conditional if/else statement works behind the scenes to turn the light on and off.

Setting up your document

Before starting to write ActionScript code, you need to go through a few simple steps to prepare your workspace.

1 Open a new Flash document. Select Modify > Document (shortcut key: Ctrl+J). Set the width of your document to 320 pixels and the height to 240 pixels (see 1 below). Select black as background color (2) and click OK.

Adjusting the document's dimensions and background color.

2 Download the image below by right-clicking on it and choosing "Save image as..." and put it somewhere on your hard drive where you will quickly and easily find it.

This image will be a part of the Flash movie in which you will use the if/else conditional statement.

3 Back in Flash, select File > Import > Import to Stage. In the little window that appears, find the image you just saved to your computer, select it and click Open. The image will appear on the stage of your Flash document.

4 However, the image is not centered on stage, so do just that: go to the Align panel. If it isn't opened already, just select Window > Align or press Ctrl+K to open it. While the image is still selected (it automatically is when you import it to the stage), do the following in the Align panel:

  1. Make sure that the Align/Distribute to Stage button is turned on,
  2. Click on the Align horizontal center button and
  3. Click the Align vertical center button.

The process of centering an image in Flash.

5 Hit F8 (or select Modify > Convert to Symbol) to convert this image into a movie clip symbol. Select Movie clip as type, and call it room light (actually, you may call it any way you like, since this name serves for Library storage purposes only, more or less). Click OK.

Selecting the options for the new symbol.

6 This newly created movie clip will be selected by default. Go to the Properties Inspector (also called the Properties panel, below the scene), to its left side. You will find the Instance name input field there. Contrary to the Library name of a symbol, this one is much more important. Call this movie clip roomLight_mc.

An instance name was just assigned to the new movie clip on stage.

Without an Instance name, you could not possibly control a movie clip via ActionScript. Also, you cannot name it any way you like. You can NOT use spaces inside an Instance name or any special characters (for example !$-%.,& etc). Stick to using letters and numbers, and the underscore character ( _ ). While you can use any number you like inside the Instance name, it can NOT BEGIN with a number.

ActionScript is a case-sensitive programming language. The Instance name roomLight_mc is NOT the same as roomlight_mc or Roomlight_mc. A good rule of thumb when searching for errors in a Flash movie that doesn't work is to begin by checking to see if the Instance names of your movie clips are typed exactly the same in your ActionScript code as they were when you assigned them. Also remember that giving the suffix _mc to an Instance name of a movie clip will help ActionScript instantly recognize that this is a movie clip and not some other type of object that you are writing code about.

7 Lock this layer and call it lamp.

The first layer was just locked and had a name assigned to it.

8 Create a new layer and call it actions.

A new layer is inserted, which will exclusively serve to host ActionScript code inside it.

And that's it for preparatory steps. Move on to actionscripting! Yeah!

Top of page

The if conditional statement explained

9 Click on the first (and only) keyframe of actions layer to be able to insert ActionScript inside it.

Selecting the first keyframe of the actions layer for code input.

10 Hit F9 (or select Window > Actions) to open up the Actions panel.

11 As you have seen at the beginning of this exercice, the light is turned off once the movie starts. To be able to that, you must tweak a simple property of your movie clip. By lowering its alpha (transparency) value to zero, the movie clip containing the image of the light bulb that illuminates the room will effectively become invisible. This will allow the movie's black background to show through and create the atmosphere of complete darkness. To do this, write this simple line of code in the Actions panel:

roomLight_mc._alpha = 0;

12 Test your movie by selecting Control > Test Movie. If you have done everything correctly up to this point, you should only see the black background. The movie clip with the image inside it should not be visible at all.

The testing movie window in Flash.

Close the testing window and go back to ActionScript code. Let me explain you the simple line you just typed in a few memonets before: the Instance name, roomLight_mc is followed by dot (.) and than comes the _alpha property. This particular property defines the degree of transparency for a movie clip. So, to tell Flash to make the movie clip invisible, you have added the equals sign (=) and wrote zero on the right side of it. The line is ending with a semicolon (;), which means that's it - end of this chunk of code. It is much like putting a fullstop at the end of a sentence to mark its, well, end.

As you have seen, the equals sign (=) is used to assign a value (to a movie clip's property in this case) and that's why in ActionScript programming language it is called the assignment operator. It serves to assign values and not to test for equality.

Ok, by making the movie clip in question invisible, you have "turned off the light" in your Flash movie. But you must somehow tell Flash that this condition exists. That's really easy.

13 Add the line shown in bold to your existing code:

roomLight_mc._alpha = 0;
var lightOn:Boolean = false;

There is no need to test your movie now, as nothing visible to the eye will happen. But, a variable will be created and stored in computer's memory while this movie is running.

A variable is created by writing the keyword var followed by the variable's name, which is lightOn in this case. After that follows a colon (:), followed by the keyword Boolean. This part of variable definition tells Flash what type of variable this is. Unlike a String (text) type of variable which can store any kind of text inside it or a numerical one, which can hold any number you want, a Boolean type of variable can have only two values inside it: true or false. In fact, this is very handy: it serves exactly that - to determine is something is true or not, if something exists or not. This will serve you very well in this exercise.

So, by writing

var lightOn:Boolean = false;

you are using this practical ActionScript routine to tell Flash that the light is turned off once the movie loads.

14 Add the next piece of code right after the two already exisiting lines:

roomLight_mc.onPress = function() {
if (lightOn == false) {
roomLight_mc._alpha = 100;
}
}

15 Test your movie again (shortcut key: Ctrl+Enter). Click anywhere on it. Ta-daa! The light will turn on (the movie clip will appear)!

How did this happen? Let's have a look at the code. To make possible for a user to click the movie clip, an event handler is introduced: the onPress event handler. In ActionScript, an event handler server just that - to handle events - things that happen in your Flash movie. So, for Flash to be able to do something when a user presses his mouse while over this movie clip, you use the onPress event handler. Bear in mind that this event handler reacts when the mouse button is pressed over a movie clip, not when it is pressed and released, which is handled by the onRelease event handler.

By writing roomLight_mc.onPress, you are assigning the onPress event handler to roomLight_mc movie clip, i.e. beginning to tell Flash that something should be done when the mouse is clicked while it is over this particular movie clip. Next, you see the good ol' assignment operator (=), followed by the start of a function definiton: function() {. What this means is that this function should be run when the mouse is clicked. It is that simple.

So when a user clicks on your movie clip, the above mentioned function is called (meaning it is being run, it is executed). The code that is being executed is the one placed between the function's curly brackets, { and }. In this case, what will be executed are three lines of code:

if (lightOn == false) {
roomLight_mc._alpha = 100;
}

And what's that? The if conditional statement! It works like this: the first thing that must be written is the ActionScript keyword if. It is in turn followed by some code placed between parenthesis, which is called a circumstance. In this tutorial, the circumstance used is: lightOn == false. Not unlike in real life (offline life :), by way of evaluating a circumstance, a computer can decide for itself what to do.

To be able to understand this more easily and quickly, imagine for a moment that you are standing on the sidewalk, about to cross the street. You can see cars passing by and the pedestrian red light turned on, therefore you decide not to cross the street yet. You have made a decision based on current circumstances. By putting together a conditional statement in ActionScript, you enable Flash to decide what to do next, based on a circumstance or set of circumstances.

And it works like this: if the circumstance (sometimes also called a condition) between the parenthesis turns out to be true, the code placed between the conditional statements curly brackets will be executed. To help you better understand this, I will translate the ActionScript code into English:

if (this circumstance tuns out to be true) {
... run all the code that is placed here,
between the curly brackets.
}

Ok? Fine. Let's get back to real code.

if (lightOn == false) {
roomLight_mc._alpha = 100;
}

As you can see, Flash checks if it is true that the value of the lightOn variable equals false: lightOn == false. To put it in plain words, is it true that the light is turned off? Yes, it is true, because the value of the lightOn variable really equals false - you have defined it as such in the second line of your ActionScript code, to tell Flash that there is no light when the movie starts.

Another important thing here: to check for equality, you must use the equality operator (==). This operator is represented by two equals signs joined together, unlike the assignment operator (=) which I mentioned before on this page.

So, Flash looks at the circumstance, sees that it evaluates as true (it is true that the value of the lightOn variable equals false) and it proceeds to run the code placed between the conditional statement's curly braces. Which in turn consists of a single line of code:

roomLight_mc._alpha = 100;

It sets the _alpha property of roomLight_mc movie clip back to 100, making it completely opaque and fully visible.

But what if the circumstance (condition) turns out to be false? Let's have a look at that. Suppose that, at the beginning of your code, instead of writing

var lightOn:Boolean = false;

you actually wrote (the modification is shown in bold)

var lightOn:Boolean = true;

Flash will evaluate the circumstance (lightOn == false) and will see that it turns out to be false. Exactly the same as before, it checks if the value of the lightOn variable equals false. No, it does not, because you defined it as true this time. In reaction to this ( the case when the circumstance turns out as being false), Flash completely ignores the code between the curly brackets. It just goes on, executing all subsequent code, if there is any.

In this case, this means the movie clip with the image won't show up at all. Try it! Change the value of the lightOn variable from false to true, test your movie and try clicking the movie clip. You will be able to click it, but nothing will happen - the black background will just stay there.

Ok, now that you've seen how Flash can decide by itself what to do thanks to the if conditional statement, let's see how to make it turn the light off again. You will use the if/else conditional logic to do that.

IMPORTANT: if you have changed the value of the lightOn variable from false to true, put it back to false. You will need it to be as it was when you started coding, to be able to successfully follow this tutorial. Once you've done that, continue onto the next step.

Save your document if you haven't already. Make this a habit, it will save you much frustration.

Top of page

Explaining the if/else conditional logic

16 Add the following to your existing code (bolded):

roomLight_mc._alpha = 0;
var lightOn:Boolean = false;
roomLight_mc.onPress = function() {
if (lightOn == false) {
roomLight_mc._alpha = 100;
} else {
roomLight_mc._alpha = 0;
}
};

Note: if confused as to where you should add the above code or if you get errors while trying to test your movie, just copy all of the code above and paste it over the existing code, erasing any previous.

Here you have the if/else conditional statement, which gives you more options and possibilities than the if statement alone. It works like this:

A user clicks the movie clip. Flash runs the function and in the exact same way as before checks out if the circumstance being presented evaluates as true. It evaluates as true and the light appears (the movie clip containing the lamp image is displayed). And the else part of the conditional statement gets completely ignored. Why?

Because the else part of the conditional statement would be executed only and only if the circumstance evaluated to false. Translated to human language, an if/else statement works like this:

if (this circumstance evaluates as true) {
... this code gets executed ...
} else {
... and this code here is ignored and skipped altogether.
}

Let's delve deeper into the possibilities that this offers you. Let's make possible for the light to be turned on and off.

17 Append this to your code (shown in bold):

roomLight_mc._alpha = 0;
var lightOn:Boolean = false;
roomLight_mc.onPress = function() {
if (lightOn == false) {
roomLight_mc._alpha = 100;
lightOn = true;
} else {
roomLight_mc._alpha = 0;
}
};

As you may have noticed, there aren't any var or Boolean keywords in this new line that you just added. The reason why is that once you have defined a variable and its type, you don't have to do it ever again. From the moment you defined it properly (as you did in this lesson), Flash is aware that this variable exists and also of its type.

18 This simple line of code enables Flash to realize that light has been turned on. So, the execution of the else part of the conditional statement will be possible. Try it:

  • Test your movie (Ctrl+Enter).
  • Click once. The light will appear.
  • Click again. The light goes off! Bingo!
  • Click once more. Nothing happens! Arrgh! How is that possible? The light should have appeared again!

Well, let me explain you: When you clicked on the movie clip the first time, the circumstance was evaluated. It turned out to be true and so the first part (the if part) of the conditional statement was executed, setting the alpha property of the movie clip to 100 and also setting the value of the lightOn variable to true.

When you have clicked the movie clip again, the evaluation process was set in motion again. This time, the circumstance evaluated as false. Therefore, the else part of the statement got executed, putting the alpha property of the movie clip back to zero and plunging everything into darkness.

But on the third click, nothing happened. Why wasn't the light turned on again? Simply because the value of the lightOn variable stayed true. Therefore, upon evaluation, the circumstance turned out as not true, meaning the value of lightOn is not set to false, but true, which makes Flash skip the if part and run the else part instead.

Once the else part is run, it sets the alpha property of the movie clip to zero again. It was already set to zero during the second click, so there is no change. It stays on zero, with the being movie in darkness.

Flash can not understand by itself that a change has happened - that light has been turned off. You, as a human being, see that. But Flash needs you to tell it that it happened, by changing the value of the lightOn variable back to false again. Computers are very, very stupid machines. They have no intelligence at all. They just have the incredible capacity to perform an enormous number of calculations in a fraction of a second. And that's it. Forget the artificial intelligence as portrayed in the sci-fi movies. It will be long since that kind of computing will see the light of day. Until that happens, stick with me and enjoy learning more Flash 😉

19 Make the final addition to your code (bolded, again):

roomLight_mc._alpha = 0;
var lightOn:Boolean = false;
roomLight_mc.onPress = function() {
if (lightOn == false) {
roomLight_mc._alpha = 100;
lightOn = true;
} else {
roomLight_mc._alpha = 0;
lightOn = false;
}
};

20 Test your movie again (Ctrl+Enter). Click until you can't click no more. The light goes on and off as intended. All thanks to a simple conditional logic statement. For a better understanding, here is a nice graph that explains it all:

The flow in the if/else conditional statement.

Top of page

Comparison operators used in conditional statements

Let me show you now some frequently used operators. These operators are also called comparison operators. That's because their purpose is to compare values - to tell if one equals another, is greater or lesser then the other one etc.

To see if a value is lesser (smaller) then some other value, you must use the lesser than (<) operator, as in the following example:

var numberOfApples:Number = 4;
if (numberOfApples < 7) {
buyMoreApples();
}

The result of the evaluation of the circumstance (also called a condition, remember) would yield as true, because 4 is lesser than 7. In much the same way, you could test if a value is greater than some other one, using the greater than (>) operator, like this:

var numberOfApples:Number = 4;
if (numberOfApples > 7) {
makeApplePie();
}

The circumstance in the example above would get evaluated as false, because 4 isn't greater than 7. Besides the two already mentioned operators, you can also test if some value is lesser than or equal to (<=) some other value or greater than or equal to (>=) whatever value it is being tested against.

Throughout this tutorial, you have used the equality operator (==) to see if a value equals some other value. On the other side, the inequality operator (!=) is used to test if something is not equal to something else:

var today:String = "Thursday";
if (today != "Sunday") {
gotoWork();
}

The string (a string value is a text value) "Thursday" does not equal "Sunday", therefore, the evaluation would be true and the function gotoWork() would be run.

But what if there are several circumstances that should be checked out? Here is where the logical AND (&&) and the logical OR (||) operators come into play. Suppose that you had to test if the current day is not sunday and that it is past 8 o'clock. You would do it like this:

var today:String = "Thursday";
var hour:Number = 9;
if (today != "Sunday" && hour > 8 ) {
gotoWorkQuickly();
}

The logical AND operator (&&) makes it obligatory for both tests performed to be true, in order for the whole circumstance to be true. In the above example, it would be enough for just one test to result as false for the whole circumstance to be false: either the value of today equaling "Sunday" or the hour value being lesser than 8. Since both conditions result as true, the whole circumstance yields as true and the gotoWorkQuickly() function gets executed. This is how this kind of situation gets interpreted by the computer:

if (today does NOT EQUAL Sunday AND the hour is GREATER THAN 8 ) {
gotoWorkQuickly();
}

When in need of testing if just one of many circumstances exists as a precondition for something to happen, use the logical OR operator (||):

if (price > 100 || shoeNumber < 8 || color != "blue") {
dontBuyShoes();
}

In this case, it would be enough for just one condition to be true for the whole circumstance to yield as true. The evaluation would proceed like this:

if (price is GREATER THAN 100 OR shoeNumber is LESSER THAN 8 OR color does NOT EQUAL "blue") {
dontBuyShoes();
}

Well, that wraps up this lesson. In the future, I will also make a tutorial on the if-else if-else conditional statement as well as the switch/case one. Use the knowledge learned in this lesson to make movies that are more interactive which in turn give your users more choices and make their experience more interesting. Also, check out other quality ActionScript tutorials made by me. Keep on ActionScripting!

Download the source FLA file for the example shown at the start of this lesson

Comments

Submit a comment

  • Andy Nov 25, 2008 at 7:27 pm

    Very nice tutorial! Very good explanation and examples! It thought me what I need to know about variables in flash, and enabled my to solve an important problem.

    Thanks.

  • Lee Nov 25, 2008 at 11:03 pm

    Great tutorial! Total lifesaver. Thanks so much!

  • sasikumar Aug 14, 2009 at 9:22 am

    Hi Luka,

    Very nice tutorials for the absolute beginers….good one…keep it up

  • Hello Luka Feb 23, 2010 at 9:43 am

    Its very interesting & well explained…we’re looking more tutorial like this..its nicely illustrated.

    keep up the good work & thanks for the efforts & time that you dedicated for this.

    Raju

  • victor Mar 29, 2010 at 10:50 am

    awesome tut, i tried this on a rollover effect but i couldnt get AS to take a the roll over comand could you please explain how to repalce the onPress if possible?

  • said Jun 8, 2010 at 9:53 pm

    it is very good thanks many for you to explain it so easy and i hope to send me more because i am learning action script
    thaaaaaaaaaaaaaaaaaaaaaaaaaaaaaank youuuuuuuuuuuuu

  • trina Jul 5, 2010 at 1:56 pm

    Several of your tutorials have been extremely helpful but I’m having problems with this one. This is probably due to the fact that I’m using CS3. I’ve worked out that ._alpha in Flash8 is .alpha in CS3, but I’m having problems with step 14:

    roomLight_mc.onPress = function() {
    if (lightOn == false) {
    roomLight_mc._alpha = 100;

    I’ve had to change it to:

    addEventListener (MouseEvent.CLICK,clickHandler)
    roomLight_mc.onMouseDown = function() {
    if (lightOn == false) {
    roomLight_mc.alpha = 100;

    but it won’t accept the clickHandler bit. I’m trying to teach myself ActionScript and so far your tutorials have been invaluable, but I find myself getting stuck on really simple things.

    So, what am I doing wrong in this case?

  • trina Jul 14, 2010 at 8:38 am

    Ah, problem solved. I need to do it in Actionscript 2.0, not 3.0. Silly me…

  • mikee pee Sep 1, 2010 at 2:04 am

    this tutorial really helped me to acheive what I wanted to achieve as I understood step by step what was going, all clearly explained so even a simpleton could get it..and better still my code worked first time!! a million thankyous 🙂

  • Maddy Sep 21, 2010 at 8:43 am

    Hi Luka,
    Your tutorial is just awesome.Actually the way you explained your tutorial is great.Everyone can understand what to do and what not to do by your tutotrial.Its very very good for beginners.Thanks a lot.Its helps me too.

    Regards!
    Maddy

  • dirtorsoil Jun 3, 2011 at 3:58 pm

    Luka- great tutorial, thanks for that. I have implemented this for a dozen movieclips in the same .fla and I have found that after the first clip is clicked I have to click each additional clip 2x to turn visibility on/off. Tried a preloader, but that does not resolve the issue. Any advice? Thanks

  • dirtorsoil Jun 3, 2011 at 4:04 pm

    Luka- great tutorial. Thanks for that.

    I have used this for 12 movieclips in one .fla. I find that after the first clip is turned on/off the others have to be clicked more than once to turn them on/off. A preloader does not solve the issue.

    Any advice? Thanks!

  • dirtorsoil Jun 3, 2011 at 4:05 pm

    Sorry for the double post, timed out connection. 🙁

  • c luke Oct 25, 2011 at 1:49 pm

    I done everything step by step but step 12 is still showing the image!!!!

  • Daria Mode Jan 12, 2012 at 4:18 pm

    Thanks for the great tutorial, I’m currently at a point where I have to use the if-else statement for my flash application, so these tipps help me a lot :-).

  • 24waves Feb 13, 2012 at 7:50 am

    Thanks for this great tutorial.it is really nice explanation and examples.

  • Bernard Jun 7, 2012 at 3:59 pm

    Very nice tutorial! Very good explanation and examples!

  • S.ORANGZEB Aug 14, 2012 at 10:54 pm

    for the first time i’ve seen such tutorial in so much depth, thanks alot you’re a life saver.

  • Jackiee Apr 3, 2013 at 7:03 pm

    this is erally great. bullshit aside. i couldnt belive it 😉

  • Ademar Morais Oct 19, 2013 at 1:02 pm

    Sensacional suas aulas! Professor, estou a tempo buscando aprender a criar um player que eu possa colocar uma playlist para tocar várias músicas, mas até agora ainda não achei uma vídeo aula ou um tutorial a respeito. Estou terminando de construir meu site de rádio e gostaria de ter um desses players com uma playlist, onde eu poderia colocar as músicas. Por favor, poste uma aula dessa para nós! Parabéns pelo profissionalismo que tens. Até mais!

  • david Oct 20, 2014 at 11:15 am

    very well explained. thank you. helped a lot.

You must log in to post a comment.