Tutorial – ActionScript 3 Buttons

April 19th, 2011 | 7 Comments

In a previous tutorial, I demonstrated how to create a Movie Clip button in Flash. Movie Clips are much more flexible than Button Symbols, so it often makes more sense to use a Movie Clip and treat it as a Button. However, even the previous tutorial was a little limited in its possibilities in that it still relied heavily on the Timeline. Today, I want to demonstrate how break free from the Timeline and create a truly dynamic button that can be reused with very few changes to the original. We're still going to create a Movie Clip button, but the functionality for this particular button will rest entirely in the ActionScript 3 code that we will apply to it.

Before we get started, let's take a look at the final result:

Creating the Button

For the purpose of this tutorial, I want to keep the button's text separate from its background. This will allow us to animate the width of the background without affecting the text.

Step 1 - Create the background. Let's keep it simple. Using the Rectangle Tool (keyboard shortcut 'R'), create a rectangle, applying whatever visual attributes you prefer. Switch to the Selection Tool (V) and hit F8 to convert the rectangle to a Movie Clip symbol. This Movie Clip will contain only the background for the button, so name it "btnBG" and set the registration to the center, like so:

(Note: If you want your button to expand out to the right instead of from the center, set your registration point to the left when converting your shape to a Movie Clip.)

Give your new background Movie Clip an instance name of "bg_mc". This is the name we will use to refer to the background in our ActionScript.

Step 2 - Label your button. Create a new text field using the Text Tool (T) and align it to the center of the button using the Align Panel. To make things really dynamic, make your text field dynamic. If you're using Flash CS4 or earlier, make your text field a Dynamic text field in the Properties Panel. If you're using CS5, you can use the new TLF Text property. With your text field selected, give it an instance name of "label_txt".

Step 3 - Embed Your Fonts. This is a very important step if you want your text to show up properly. With your text field still selected, click on the "Embed" button in the Properties Panel. In the popup, select Uppercase, Lowercase, Numerals, Punctuation, and any other options that you might end up using in your text field. Click "OK" to apply your changes.

Step 4 - Create your Movie Clip button. Using the Selection Tool (V), select both your button background and your text field and hit F8 to convert your graphics to a symbol. Again, set your registration point to the center, choose "Movie Clip" for the symbol type, and give it the name "mcButton". Select your new Movie Clip button and give it an instance name of "button_mc".

Coding the Button

Double check to make sure your instance names are all the same as mine. Once this is confirmed, create a new layer named "Actions", click on frame one of this new layer, and hit F9 (or Option+F9 on a Mac) to open up your Actions Panel. (Additionally, you can also access the Actions Panel from the Window menu.)

Add the following code to frame one of your Actions panel:

import caurina.transitions.*;
import flash.events.MouseEvent;
import flash.net.URLRequest;

button_mc.buttonMode = true;
button_mc.label_txt.text = "home";

button_mc.addEventListener(MouseEvent.MOUSE_OVER, hover);
button_mc.addEventListener(MouseEvent.CLICK, clicked);

function hover(e:MouseEvent):void {
	Tweener.addTween(button_mc.bg_mc, {scaleX:1.5, transition:"easeOutElastic", time:1});
	button_mc.removeEventListener(MouseEvent.MOUSE_OVER, hover);
	button_mc.addEventListener(MouseEvent.MOUSE_OUT, out);
}

function out(e:MouseEvent):void {
	Tweener.addTween(button_mc.bg_mc, {scaleX:1, transition:"easeOutElastic", time:1});
	button_mc.removeEventListener(MouseEvent.MOUSE_OUT, out);
	button_mc.addEventListener(MouseEvent.MOUSE_OVER, hover);
}

function clicked(e:MouseEvent):void {
	navigateToURL(new URLRequest("http://www.schoolofflash.com"),"_self");
}

The first three lines of our code import the necessary ActionScript classes. Note that I have decided to use the Tweener class for our animations instead of the traditional Tween class. The Tweener class is much easier to use, not to mention much less buggy. Click here to learn more about the free Tweener class. Line 1 of our code imports the Tweener class, as well as other classes in the caurina.transitions package.

In line 5, we set the buttonMode property to "true". When we do this, we make our Movie Clip behave more like a Button symbol in that it causes the mouse cursor to turn into a hand cursor whenever you hover over the button. Line 6 sets the label text of the button to read "home".

The next two lines create our hover and click events, which trigger the "hover" and "clicked" functions, respectively.

Inside the "hover" function, we want to animate the width of the button background to get that elastic, bouncy animation. We do this using the Tweener.addTween() method. This method takes two main parameters: the instance name of the object being animated and an object containing information on the animation itself. In this case, we want to animate the background of the button by itself. If we just applied the animation to the button, then the text would animate, too. We don't want that, so we're pointing to the bg_mc Movie Clip within the button_mc Movie Clip.

The second parameter is a little more complicated, because it contains numerous property/value pairs that define our animation. The documentation on the Tweener class describes a number of different properties that you can include here, but for this animation, we just want to look at the property of the Movie Clip that we want to animate, the easing function we want to use, and the duration of the animation itself. For this animation, we just want to animate the width of the background; but instead of using the width property, notice that I referenced the scaleX property, which allows you to modify the width of the object as a percentage of its original width. In this instance, I used 1.5 to scale it up to 100% of its original width. To scale it back to its original width in the out function, simply animate the scaleX property back to a value of 1.

Another property commonly used within the Tweener.addTween() method is the "transition" property. By default, if you choose not to specify a value, the Tweener classes uses a simple ease out. If you don't want any easing at all, you would set the transition to "linear." Again, the Tweener documentation contains a description of all the different transition types--which are much more robust than the easing options available with the traditional Tween class. If you decide to use the Tweener class on a regular basis (which I do), then I highly recommend these handy little cheat sheets, which I keep posted on my desk.

The third property I used in this example is the "time" property, which determines the duration of the animation. This number is in seconds, so our button animation will last 1 second. Note that this does not have to be a whole number. If you want your animation to last half a second, you can enter a value of 0.5.

After creating your new Tween, be sure to remove the event listener for the MOUSE_OVER event and add a listener for the MOUSE_OUT event. Try to stay in the habit of removing unneeded listeners. When you're already hovering over a button, you no longer need the MOUSE_OVER event using up processing power. Just remember to add the event back after you move your mouse away from the button (as seen in the out() function).

By now, you should be able to figure out what's going on inside the out() function. When the user moves the mouse cursor away from the button, we simply play the reverse of the previous animation, returning the button to its original width. Then we remove the MOUSE_OUT event and restore the MOUSE_OVER event.

Flexible ActionScript 3 Buttons

As you can see, breaking away from reliance on the timeline allows you to create much more flexible and dynamic interactions. With only very minor tweaks to the code, you can create a variety of different effects.

Click here to download the project file for this tutorial.

Related Post: ActionScript 3 Tutorial - Tweener Transitions

Tags: , , , , , , , , , , , , , ,

7 Responses

  1. Tom says:

    Hi,

    I love all your tutorials and help, but here’s a question that’s bothering me: Apple iPads— Is it worth learning Flash and ActionScript if the Apple iPad is going to make it irrelevant? I understand Adobe has an implementation that will adapt Flash to iOS, but should we be working directly in apps that address iOS and HTML5 instead of working in Flash and ActionScript? Your comments are greatly appreciated.

    __
    Tom

    • Craig says:

      At this point, I think that’s a decision every Flash developer needs to make for himself/herself. There is still a lot that can be accomplished in Flash that you can’t do in HTML5. So if you are a Flash developer, it would certainly be advantageous to learn HTML5, CSS3, and things of the sort, but keep Flash in your tool belt. Right now, Apple products are the only big contenders refusing to support Flash, and who knows what’s going to happen in the future? Right now, it’s all speculation. In the mean time, I love Flash, and I’m going to keep using it!

  2. James says:

    Hi Craig,

    i was wondering if you could tell me how to make the buttons the same as above but instead how to make it go to a different frame. It would be much appreciated.

    James

  3. Larry says:

    I cannot open the source file.

  4. mrfreddy says:

    I set this up exactly the way you described, but when I run the swf, I can’t click on the text??? What’s missing.

    Also, I think your sample file must be CS5, I can’t open it with CS4.

  5. Pieter says:

    Hi Craig,

    I did your tutorial and it worked partly. The hover transitions worked
    The naming of label_txt did not change into home, while I just copied your code.

    But when I try to run the code now, it gives me the a ReferenceError: Error #1065: Variable TCMText is not defined.

    What should I do now? I am working in CS5.5 and have read some threads on this but I can’t get grip on the problem. Can you help me with this??

    Thanks in advance!

    Pieter

  6. Lordoomer says:

    This tutorial is awesome I just used it to make menu buttons in my platform game it was very easy to understand and very effective to use thank you very much for making such a great tuts…

Leave a Reply