By Dan Carr
Dan Carr
Created
16 December 2011
 

Requirements

 
Prerequisite knowledge

The article is designed for all levels of Flash users. The tutorial starts by providing beginning-level exercises and progresses to intermediate levels. For best results, you should have prior experience using the Flash workspace and a basic understanding of working with ActionScript 3 in Flash.
 

 
User level

All
 

 
Required products

Buttons are a simple and fundamental part of web-based and desktop applications. They are an intuitive way to connect the user experience of browsing the web with the process of building controls in Flash. This article covers the types of buttons you can create in Adobe Flash Professional (CS4 and later) and the pros and cons of working with each type.
 
Explore the anatomy of a button and learn various ways to create custom buttons. Use the provided sample files and the step-by-step instructions to follow along with a series of simple exercises ranging from beginning to intermediate skill levels (see the interactive buttons in Figure 1). Along the way, you'll learn how to use button symbols and button components as well as add common ActionScript functionality, such as launching a web page by specifying its URL and sharing a link on Facebook.
 
Figure 1. Different button types from the exercises included with the sample files.

 
Understanding the basic structure of Flash buttons

Web and desktop applications collect user interaction through button clicks. Understanding the types of buttons available and how to use them opens up possibilities for creating engaging user interfaces.
 
Buttons are commonly used to do the following:
 
  • Control the user interface of an application
  • Select options and submit data in a form
  • Navigate to sections within a website or application
This section provides an overview of button types, key terms used to describe button anatomy, and options available in Flash when creating buttons.
 
 
Identifying different types of buttons
I like to organize button functionality into three categories: push buttons, toggle buttons, and grouped buttons. Understanding the pros and cons of each functionality makes it easy to choose the right control for the task at hand.
 
Push buttons are the simplest and most common type of Flash button. They are basically clickable graphics that might show a rollover state, an icon, and a label (see Figure 2). Push buttons have the benefit of being simple to set up and use but they don't interact with other buttons or save their selected (clicked) state visually. Generally speaking, you use push buttons to create common controls when you simply need to capture a click event. For example, push buttons are the ideal choice if you need to turn an icon or a text field into a button, or if you need to create an invisible button as a hotspot.
 
Figure 2. A simple push button composed of an icon graphic.
Figure 2. A simple push button composed of an icon graphic.
Toggle buttons are push buttons that save their selected state (see Figure 3). Most commonly, you'll see push buttons in the form of a check box control. When you click a toggle button, it visually remains in the selected state until another click toggles the button back to its default state. Toggle buttons have the benefit of saving their selected state but they don't interact with other buttons without additional support. Use toggle buttons when you need to provide a single true or false type of option. A simple example of a toggle button would be something like a "Send me updates by e-mail" check box at the end of a registration form. Developers often set the control to appear selected by default to allow someone to opt-out of a requested action.
 
Figure 3. A toggle button check box in its selected state.
Figure 3. A toggle button check box in its selected state.
Grouped buttons are toggle buttons that save their selected state in a group (see Figure 4). This type of button is called a radio button or radio group. When you create a group of radio buttons, only one selected state is visible at a time. The buttons behave as a group, so making a new selection automatically deselects the old selection. Grouped buttons have the benefit of saving the selected state in a group of buttons but they are more complex to set up. Use grouped buttons when you need to capture a selection from a list of options. A simple example involves a series of radio buttons allowing the visitor to choose their salutation (Mr., Mrs., Ms.) in a form. It's best to expose a short list of options like this in a radio group. The radio group should always display a default selection. A more complex example of a button group might involve a tabbed panel presentation. In this scenario, the buttons would look different but they behave the same way by showing a single selection in a group.
 
Figure 4. A radio button group only allows a single selection from a group of options.
Figure 4. A radio button group only allows a single selection from a group of options.
 
Examining the anatomy of a button
The structure of a button can be as simple as a single frame containing a graphic, or as complex as an animation that plays within a button's timeline. Most commonly you'll see buttons in Flash use the metaphor of the four button states assigned to frames of a button symbol (see Figure 5). The states correspond to the interactivity of the mouse cursor in relation to the button. Up is the default state; this is the visual that appears when the cursor isn't over the button. Over is the state that appears when you move the cursor over the button. Down is the state that appears when you press down on (click) the button.
 
The four frame states of a button symbol.
Figure 5. The four frame states of a button symbol.
Notice the Hit frame in Figure 5. In a button symbol, the Hit state is an non-visible frame which defines the active area (also known as the area of influence) of the button. Custom-built buttons use the concept of an active area as well. The active area creates the area that interacts with the cursor—even if that area is not the same shape as the visible graphics used to display the button. If there are no visible graphics in the button, the active area defines a hotspot, creating what is commonly known as an invisible button.
 
 
Options for creating buttons in Flash
Flash Professional provides both prebuilt buttons and options for creating custom buttons. You'll explore the following topics the remaining sections of this article:
 
  • Using button symbols to create custom buttons
  • Using button components as configurable prebuilt options
  • Using movie clip symbols to create custom buttons

 
Working with button symbols

Since the beginning, button symbols have been the most common way to create buttons in Flash. Button symbols allow you to easily create a button using custom graphics, sounds, and even nested animations.
 
The benefit of using button symbols is their simplicity. It's very easy to create push buttons. The drawbacks are that you don't have an easy way to create toggle buttons or grouped buttons when working with button symbols.
 
This section guides you through the basics of working with button symbols. Follow along with the two exercises to learn more about push buttons.
 
 
Symbol structure
Button symbols contain a special adaptation of the timeline; instead of containing numbered frames, they contain frames labeled with button states (see Figure 6). This is the only time you'll see the timeline appear differently in Flash. In a button symbol, the Up, Over, and Down frames appear as the mouse interacts with the button. The Hit frame is invisible and defines the active area of the button. The Hit frame is useful for activating the button using a shape that might not necessarily match the visible graphics of the button. The Hit state can be used by itself to create an invisible button (hot spot) or it can be omitted if graphics exist on the Up, Over, or Down frames. If the Hit state is omitted, the last frame with graphic content is used as the active area of the button.
 
Figure 6. The layers and frame states in a button symbol.
Figure 6. The layers and frame states in a button symbol.
The process of building a button using a button symbol includes adding graphics and sounds to the labeled frames. You can add as many layers as you like. The timeline shown in Figure 6 uses a layer for sound and a second layer for graphics.
 
Tip: If you add a sound to the Up, Over, or Down frame, be sure to set the sound to the Event Sync type in the Property inspector.
 
 
Button instance properties
Button symbols are stored in the Library. You can use as many instances of a symbol as you like across any timeline. To enable functionality through coding, you'll assign a unique instance name to each button instance in the Property inspector (see Figure 7).
 
Figure 7. Button instance properties in the Property inspector.
Figure 7. Button instance properties in the Property inspector.
Also notice the button tracking options in Figure 7. Setting a group of button instances to the Track as Menu Item option changes the way they behave as a group. This option can be used if you're creating a menu containing button symbol instances to allow them to share mouse events as the visitor clicks and drags their cursor over the buttons.
 
 
Event handling through simple ActionScript
Creating the button symbol is part one of two steps involved to set up a button. The second step is to add a bit of ActionScript to respond to the mouse events broadcast from the button.
 
Events are timing cues that signal Adobe Flash Player when something happens. ActionScript 3 makes event handling easy because there is only one way to do it. First you assign an instance name to the button. Then you create an event handler function to hold the code that will respond to the event. Finally you assign the event handler function to the button instance to tie them together.
 
The following example assumes the button's instance name is: myButton.
 
import flash.events.MouseEvent; function onButtonClick( event:MouseEvent ):void { trace("hello, world!"); } myButton.addEventListener(MouseEvent.CLICK, onButtonClick);
The MouseEvent object contains many events which you can use to respond to mouse interactivity with the button. The sample above responds to the CLICK event, which occurs when you press and release the button. You could also set a button to respond to MOUSE_OVER, MOUSE_DOWN, MOUSE_UP, and so on.
 
See the MouseEvent class in the ActionScript 3 Help pages for a full list of event options.
 
Tip: In ActionScript 3, code cannot be placed directly on the button instance. Instead, the code is attached to a keyframe on the main Timeline. In the exercise, you'll create an actions layer and attach code to Frame 1. This is considered a best practice when coding inside a FLA file.
 
 
Using buttons from the Buttons common library
Flash Professional provides the Buttons common library as a resource for prebuilt button symbols in various themes. You can use these buttons as a quick start or customize them to meet your needs.
 
Follow these steps to open the Buttons common library:
 
  1. Choose Window > Common Libraries > Buttons.
  2. Select a button in the common library panel and drag an instance of it to the Stage on any timeline.
 
Exercise 1: Create a button symbol
Button symbols can be used to quickly turn any graphic, text, sound, or combination thereof into a button. If you're new to Flash, this is your easiest and quickest option for creating buttons. The frame states are already set up for you and no ActionScript code is required to navigate the frames or activate the hand cursor icon when a visitor rolls over the button's active area.
 
This exercise guides you through the process of creating a button using a button symbol. You'll build the frame states inside the button and add ActionScript to the button instance that opens a web page by specifying its URL:
 
  1. Download the buttons_exercises.zip file from the link provided at the beginning of the article, if you haven't already done so. Unzip the files and save the sample file folder to your desktop. As you work, you'll save your files into this folder and open the supplied files from the assets subfolder.
  2. In Flash, create a new ActionScript 3 FLA file and name it exercise1.fla. Save the file in the buttons_exercises folder.
  3. Create a new button symbol by choosing Insert > New Symbol.
  4. In the Create New Symbol dialog box, enter the name PushButton and set the Type menu to Button (see Figure 8). Click OK to create the symbol and enter its timeline for editing.
Figure 8. Use the Create New Symbol dialog box to create a button symbol.
Figure 8. Use the Create New Symbol dialog box to create a button symbol.
  1. Add graphics by importing the supplied share button artwork or use your own graphics, if you prefer. Choose File > Import > Import to Stage and browse for the PushButton.ai file located in the assets folder. Click Open to open the file and then click OK in the Import to Library dialog box to accept the default import settings. Notice that artwork appears on the Timeline across two layers named "+" and "back" (see Figure 9).
Figure 9. The PushButton symbol timeline as it appears after importing the artwork.
Figure 9. The PushButton symbol timeline as it appears after importing the artwork.
  1. Add graphics to the Over and Down frames to complete the button artwork. Select the frames in both layers across the Over and Down frames and press F5 to insert frames.
  2. Select the plus (+) graphic and choose Modify > Break Apart twice to ungroup the artwork. This step allows you to change the color of the icon after it has been copied to the Over and Down frames.
  3. Select the Over and Down frames on the "+" layer and press F6 to copy the keyframe from the Up frame to Over and Down frames.
  4. Select the icon graphic on the Over frame and change its color to yellow. Then select the icon graphic on the Down frame and change its color to orange. This step builds the different visual states that will display when the cursor interacts with the button.
  5. You could continue to add a Hit state graphic, although it's not necessary in this case since the button shape is a solid rectangle.
  6. Add ActionScript to the button instance to add functionality to the button. Return to the main Timeline and rename Layer 1 to button. Drag an instance of the PushButton symbol from the Library to the Stage.
  7. Select the button instance and assign it the instance name myButton in the Property inspector.
  8. Add a new layer named actions above the button layer. You'll add your ActionScript to Frame 1 of the actions layer as a general best practice.
  9. Select the blank keyframe on Frame 1 of the actions layer and press F9 to open the Actions panel. Copy and paste the following code into the Script window of the Actions panel:
import flash.events.MouseEvent; import flash.net.navigateToURL; import flash.net.URLRequest; function onButtonClick( event:MouseEvent ):void { // Open a URL navigateToURL(new URLRequest("http://www.adobe.com")); } myButton.addEventListener(MouseEvent.CLICK, onButtonClick);
  1. Choose Control > Test Movie to test your work. You should see the Over and Down states appear as you interact with the button. When you click and release the button the web page that corresponds to the specified URL launches in a browser window.
  2. Save the file.
The ActionScript code shown in Step 14 can be used to open any URL. All you need to do is update the website URL and the button instance name to reuse it. In fact, this code will work when assigned to any display object instance—whether it's a button symbol instance or not.
 
 
Exercise 2: Modify the button with a nested animation and a Hit state
One of the great things about a button symbol is that you can nest animations in the Up, Over, and Down states. To create a nested animation, you simply build an animation in a movie clip symbol and add an instance of that symbol to one of the three visual button state frames.
 
This exercise guides you through the process of updating the button from Exercise 1 with a nested animation and a Hit state. Start by building a simple text animation using the word Share and then add a rectangle to the Hit frame that covers the area of the button and the animation. Finally, update the ActionScript code to share a link on Facebook:
 
  1. Choose File > Save As and save the exercise1.fla file as exercise2.fla in the same folder.
  2. Choose Insert > New Symbol to create a new movie clip symbol. Name the symbol OverAnimation and make sure the Type menu is set to Movie Clip. Click OK to create the symbol and enter its timeline for editing.
  3. Rename Layer 1 to animation.
  4. Select the Text tool and type the word Share on the state. Position the text at the 0, 0 coordinate (the registration cross-hairs) and set the text formatting as desired in the Property inspector.
  5. Create a fade-in animation. Select the text and make sure it's set to use TLF Text in the Property inspector. Right-click the text and choose Create Motion Tween in the menu that appears. The timeline automatically extends to 24 frames. On Frame 1, select the text and change the alpha to 0 under the Color Effect section in the Property inspector. At Frame 24, select the text and set its alpha to 100 to create the fade-in animation.
  6. Add a new layer named actions above the animation layer. Select the Frame 24 in the actions layer and press F7 to add a blank keyframe. Select the keyframe and type the following code into the Actions panel:
stop();
  1. Double-click the PushButton symbol in the Library to enter its timeline for editing.
  2. Add a new layer named anim above the existing "+" layer.
  3. Select the Over frame in the anim layer and press F7 to add a blank keyframe. Drag an instance of the OverAnimation symbol from the Library to the Stage on the new keyframe you just created. Position it to the right of the button graphic.
  4. Add a rectangle to the Hit frame which covers both the button graphic and the animation area. This step assures that all the pieces of the button behave as expected, because the active area will overlay both of the button elements. Create a new layer named hit above the anim layer.
  5. Add a keyframe to the Hit frame on the hit layer and draw a rectangle covering both the button and animation (see Figure 10). The Hit state graphic isn't visible to the visitor, so it doesn't matter what color you choose to set the stroke and fill of the rectangle.
Figure 10. The completed button timeline showing the Hit frame graphic.
Figure 10. The completed button timeline showing the Hit frame graphic.
  1. Return to the main Timeline and select Frame 1 of the actions layer to view the code in the Actions panel.
  2. Copy and paste the following code to update the navigateToURL line:
var params:String = "u="+ escape("http://www.adobe.com/devnet/");// url params += "&t="+ escape("ADC"); // title navigateToURL(new URLRequest("https://www.facebook.com/sharer.php?"+ params));
  1. Test your work. You should notice that the animation appears when you roll over the hit area and that the button click shares the URL on your Facebook page.
  2. Save the file.
Tip: If you're creating a button containing text and notice that the cursor flickers when you roll over it, add a rectangle on the Hit frame that completely covers the text content area to resolve the issue.
 
See the following resource and videos for more information on creating button symbols:
 

 
Working with button components

Flash components are prebuilt widgets that provide user interface functionality (see Figure 11). Components can be customized visually. You can also customize them by adding ActionScript or adjusting their component parameters.
 
Figure 11. The Components panel.
Figure 11. The Components panel.
The benefit to using button components is that you gain access to advanced functionality with little to no effort. The drawbacks are the included file size of the component code and possible challenges with customizing the look and feel in some cases.
 
This section provides an overview of working with Flash button components.
 
 
Using Flash components and component parameters
Flash components are easy to use. Simply open the Components panel (Window > Components) and drag a component instance to the Stage on any timeline. Once you create your component instance, you can select it and edit its component parameters in the Property inspector (see Figure 12).
 
Figure 12. The CheckBox component's parameters are displayed in the Property inspector.
Figure 12. The CheckBox component's parameters are displayed in the Property inspector.
Notice in Figure 12 that you can adjust the label and selected state in the parameters. You can accomplish this with ActionScript as well, but Flash components are designed to be easy to configure at author-time.
 
 
Flash button component types
The User Interface group of Flash components contains three button-type components: Button, CheckBox, and RadioButton (see Figure 13). A Button component provides a simple push button with a background and a label. A CheckBox component provides a check icon to show a selected state. A RadioButton component contains the ability to group together with other RadioButtons to allow for a single selection from a list of options.
 
Figure 13. Examples of the Button (top), CheckBox (middle), and RadioButton (bottom) components.
Figure 13. Examples of the Button (top), CheckBox (middle), and RadioButton (bottom) components.
Flash components are a great way to build complex forms or user interface elements that contain functionality beyond button symbols. Flash components can be styled and reskinned, and they work with a focus manager among other scripts to create fully functional form elements. In particular, when you find that you need form-level functionality or check boxes and radio buttons, this is the easiest option to choose.
 
 
Customizing component graphics
The Flash button components are editable just like regular movie clip symbols. You can edit the graphics for the button states by double-clicking the component instance and editing the graphics on Frame 2 (see Figure 14).
 
Figure 14. The graphic states of the Button component.
Figure 14. The graphic states of the Button component.
You can edit the graphics as you would any other graphics in Flash. For best results, I usually keep the graphic shapes similar to the supplied files and focus on changing color themes, text labels, and other aesthetic details.
 
Tip: Each of the button component skins uses 9-slice scaling to allow the skin to resize without distorting the graphic. Add your graphics to the skin symbols and make sure they scale as intended as you go.
 
 
Working with component ActionScript APIs
Flash components are movie clip symbols at their core and therefore can be controlled with any ActionScript code you would use to control a display object. In addition, each component contains an extended ActionScript API capable of setting parameters, styles, and commands. If you find that the component parameters don't include the functionality you need, try exploring the ActionScript documentation to find working samples.
 
See the fl.controls package documentation in ActionScript 3 Reference for the Adobe Flash Platform for more information.
 
 
Exercise 3: Create a form using components
Websites and applications use forms to collect user information. A simple example of this functionality is a signup form posted on a website. A more complex example of a form could be a questionnaire, a survey, or even a quiz. Flash components have common form functionality built in, such as tab control and focus management. Components in Flash make it easy to set up forms in a few quick steps.
 
This exercise guides you through the process of creating a simple sign up form using the Button, CheckBox, RadioButton, and TextInput components (see Figure 15). You'll also add ActionScript code that posts the form data to a specified URL.
 
Figure 15. The completed layout of the sign up form.
Figure 15. The completed layout of the sign up form.
  1. Create a new ActionScript 3 FLA file and name it exercise3.fla.
  2. Import the supplied background artwork for the form. Choose File > Import > Import to Stage and browse for the FormBackground.ai file located in the assets folder. Accept the default import settings to import the background and text graphics. Notice that two layers of artwork (background and text) are added to the main Timeline. Go ahead and select the text and embed the font, if you'd like.
  3. Add a new layer named components above the text layer. You'll add your Flash components to this layer.
  4. Open the Components panel (Window > Components) and drag instances of the RadioButton, TextInput, CheckBox, and Button components to the Stage. Press the Q key and drag the handles of the Transform tool to resize the width of the components as needed. The layout should look something like Figure 15 when you are finished.
  5. Add instance names and component parameters to each component using the Property inspector. Select the first radio button in the top left, and set its instance name to mr. Set its component parameters in the Property inspector to:
    • group: sharedRadioGroup
    • label: Mr.
    • selected: true
    Notice that you set the radio group name in the last step. You could have used the default radio group name, but setting an explicit name allows you to use more than one radio group in the same form. This is a best practice when configuring a set of radio buttons.
     
  1. Select the middle radio button. Set its instance name to mrs and its component parameters to:
    • group: sharedRadioGroup
    • label: Mrs.
  1. Select the radio button on the right. Set its instance name to ms and its component parameters to:
    • group: sharedRadioGroup
    • label: Ms.
  1. Select the top text input and set its instance name to firstname. Select the text input in the middle and set its instance name to lastname. Select the text input on the bottom and set its instance name to email. You don't need to adjust any component parameters for the text inputs, but notice that there are a few parameters available.
  2. Select the check box. Set its instance name to maillist and set its component parameters to:
    • label: Add to mailing list
    • selected: true
  1. Select the button instance. Set its instance name to submit and its component parameters to:
    • label: Submit
  1. Add an actions layer and code to add functionality to the form. Create a new layer named actions above the components layer.
  2. Select the keyframe on Frame 1 of the actions layer and open the Actions panel (F9). Paste the following code into the Actions panel:
import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.MouseEvent; import flash.net.URLLoader; import flash.net.URLRequest; import fl.controls.RadioButtonGroup; var radioGroup:RadioButtonGroup = mr.group; var urlloader:URLLoader = new URLLoader(); // 1. collect form results and submit to server function onSubmitForm( event:MouseEvent ):void { // get parameters var params:String = "salutation="+escape(radioGroup.selection.label); // salutation params += "&fname="+escape(firstname.text); // first name params += "&lname="+escape(lastname.text); // last name params += "&email="+escape(email.text); // email params += "&mailinglist="+maillist.selected; // mailling list option // create loader and send url request urlloader.load(new URLRequest("http://www.dancarrdesign.com/cgi/submit.php?"+params)); } submit.addEventListener(MouseEvent.CLICK, onSubmitForm); // 2. evaluate result returned from server and show feedback in UI function onUrlloaderResult( event:Event ):void { var result:String = urlloader.data as String; trace("Success: "+result); } urlloader.addEventListener(Event.COMPLETE, onUrlloaderResult); // 3. show feedback in the UI if an error occurs function onUrlloaderError( event:IOErrorEvent ):void { trace("Form submission failed."); } urlloader.addEventListener(IOErrorEvent.IO_ERROR, onUrlloaderError);
  1. Choose Control > Test Movie to review the form. You should see the radio button group toggles its selection. Fill in the form and click the submit button. You should see a trace action appear in the Output panel showing either a success or error statement.
  2. Save the file.
The form sample builds on the concept of calling a URL by using the URLLoader object to send the form data and receive a response. The code uses three event handler functions to build the core functionality of the form: one event handler to respond to the submit button click and send the data, another to respond to a successful result, and another to respond to a failed result. In a real-world scenario, the form would also include form field validation and display feedback in the user interface to indicate when the form submission results in success or failure.
 
See the Using ActionScript 3 Components documentation for more information about Flash components.
 

 
Creating custom buttons from movie clip symbols

Another approach you can take is to create your own custom button functionality in a movie clip symbol. You can easily simulate the structure of a button symbol using frame labels along a movie clip's timeline. Add a bit of ActionScript and you can create customized buttons of any type.
 
The benefit of this approach is that you can create as many button states and custom functionalities as needed. The drawback is the need to understand ActionScript at a more in-depth level. This approach requires intermediate level work with the timeline and ActionScript, but it's not hard to accomplish once you get the pattern down.
 
This section provides a brief overview of creating custom buttons using movie clip symbols.
 
 
Creating a push button
A simple push button is easy to create with a movie clip. Technically, adding a mouse event listener to any display object turns it into a button. If you add mouse event listeners inside the movie clip, you can easily jump between an up frame label and an ov frame label to show different graphic states (see Figure 16).
 
Figure 16. The up and ov frame labels in the timeline of a movie clip symbol.
Figure 16. The up and ov frame labels in the timeline of a movie clip symbol.
In this scenario, the timeline never plays through the frames consecutively. Instead, a stop action and mouse event code are placed on Frame 1. When a mouse event is triggered, a gotoAndStop action sends the playhead to the intended frame label.
 
Add the following code sample to Frame 1 of the movie clip to enable the rollover state:
 
import flash.events.MouseEvent; this.buttonMode = true; function onButtonOver( event:MouseEvent ):void { gotoAndStop("ov"); } this.addEventListener(MouseEvent.MOUSE_OVER, onButtonOver); function onButtonOut( event:MouseEvent ):void { gotoAndStop("up"); } this.addEventListener(MouseEvent.MOUSE_OUT, onButtonOut); stop();
The code example above only includes two states; these control the display of the Up and Over states. You can easily add a Down state by adding a dn frame label to the movie clip's timeline and adding event handler functions for the MOUSE_DOWN and MOUSE_UP events in the code.
 
 
Creating a toggle button
A toggle button is similar to a push button except that it toggles between an Up state and a Down state (see Figure 17). By adding a selected property and a setSelected function, you can jump between the two frames and retrieve the selected value as needed.
 
Figure 17. The up and dn frame labels in the timeline of a movie clip symbol.
Figure 17. The up and dn frame labels in the timeline of a movie clip symbol.
The following code sample can be added to Frame 1 of the movie clip to enable the selected state:
 
import flash.events.MouseEvent; this.buttonMode = true; var selected:Boolean = false; function setSelected( b:Boolean ):void { selected = b; if( selected ) gotoAndStop("up"); else gottoAndStop("dn"); } function onButtonToggle( event:MouseEvent ):void { // toggle value setSelected(!selected); } this.addEventListener(MouseEvent.MOUSE_DOWN, onButtonToggle); stop();
Here again you can add an Over and Down-over state following the same pattern using additional frame labels and event handlers.
 
 
Creating a button group
A button group is created by adding a script to control a series of toggle buttons. The button group script keeps a list (an array) of toggle buttons which it uses to maintain a single selected state across the group of buttons.
 
The following code sample can be added to Frame 1 of the movie clip containing the toggle buttons to enable the button group:
 
import flash.events.MouseEvent; var group:Array = new Array(tb1, tb2, tb3); var selectedButton:MovieClip; function onButtonSelect( event:MouseEvent ):void { selectedButton = event.target as MovieClip; for each(var btn:MovieClip in group){ bt.setSelected( btn == selectedButton ); } } tb1.setSelected(true); tb1.addEventListener(MouseEvent.CLICK, onButtonSelect); tb2.addEventListener(MouseEvent.CLICK, onButtonSelect); tb3.addEventListener(MouseEvent.CLICK, onButtonSelect);
The sample above assumes there are three toggle buttons on the Stage whose instance names are tb1, tb2, tb3. Notice that the tb1 button is set to selected as a default. It's a best practice to always define a default selection when configuring a set of radio group buttons.
 
 
Exercise 4: Create a custom button with a movie clip symbol
Building buttons using movie clip symbols is a good approach if you're comfortable with ActionScript at a basic level and understand how events and event handlers work. The benefit of this strategy is that you can create highly customized buttons which often times will be part of other controls that require specific functionality. You might find this approach handy if you need to create buttons that can be dragged and dropped, or buttons used in sliders or volume bars, and other specialized interface elements.
 
This exercise guides you through the process of creating a simple custom button using a movie clip symbol. You'll add ActionScript that creates the Over and Down states and then set up the button to respond to a mouse click on the main Timeline:
 
  1. Create a new ActionScript 3 FLA file and name it exercise4.fla.
  2. Start by creating a new movie clip symbol to contain the button states and code. Choose Insert > New Symbol. Enter the name PushButton in the Create New Symbol dialog box and set the Type menu to Movie Clip. Click OK to create the symbol and enter its timeline for editing.
  3. Import the PushButton.ai from the assets folder. You'll create the same button you did in the first exercise, but this time you'll build it from scratch. Notice that the PushButton timeline now contains two layers: "back" and "+".
  4. Select Frame 15 across both layers and press F5 to add frames.
  5. Add a new layer named actions above the "+" layer.
  6. Select Frame 1 of the actions layer and press F9 to open the actions panel. Add a stop action to make sure that the timeline doesn't play and advance to Frame 2.
  7. Select Frame 2 of the actions layer and add the frame label up in the Property inspector. This frame holds the Up state graphics. Use Frame 2 for the up label so that the ActionScript on Frame 1 only loads once.
  8. Select Frame 5 on the actions layer and press F6 to add a keyframe. Select the keyframe and add the frame label ov. This frame will contain the Over state graphics.
  9. Select Frame 10 on the actions layer and press F6 to add a keyframe. Select the keyframe and add the frame label dn. This frame holds the Down state graphics.
  10. Add keyframes to Frames 5 and 10 on the "+" layer and change the color of the plus icon the same way you did in Exercise 1.
At this point you've set up the graphic states and added the frame labels needed for the code to jump within the timeline (see Figure 18). Next, you'll add event handler functions to Frame 1 to power the graphic states of the button.
 
Figure 18. The completed timeline of the custom movie clip button.
Figure 18. The completed timeline of the custom movie clip button.
  1. Select Frame 1 of the actions layer. Copy and paste the following code into the Actions panel:
import flash.events.MouseEvent; this.buttonMode = true; function onButtonOver( event:MouseEvent ):void { gotoAndStop("ov"); } this.addEventListener(MouseEvent.MOUSE_OVER, onButtonOver); function onButtonOut( event:MouseEvent ):void { gotoAndStop("up"); } this.addEventListener(MouseEvent.MOUSE_OUT, onButtonOut); function onButtonDown( event:MouseEvent ):void { gotoAndStop("dn"); } this.addEventListener(MouseEvent.MOUSE_DOWN, onButtonDown); function onButtonUp( event:MouseEvent ):void { gotoAndStop("up"); } stage.addEventListener(MouseEvent.MOUSE_UP, onButtonUp); stop();
  1. Take a moment to review the code you just added. Notice that it consists of a series of event handler functions that jump the playhead to different frame labels in the button's timeline as the cursor interacts with the button. Also notice that the MOUSE_UP event handler is assigned to the Stage instead of the button, so that the Up state will resume whether the MOUSE_UP event happens over the button or not.
  2. Return to the main Timeline and rename Layer 1 to button.
  3. Drag an instance of your button to the Stage and name the instance myButton.
  4. Add a new layer named actions above the button layer.
  5. Add the following actions to Frame 1 of the actions layer:
import flash.events.MouseEvent; function onButtonClick( event:MouseEvent ):void { trace("Handle custom button clicks here..."); } myButton.addEventListener(MouseEvent.CLICK, onButtonClick);
  1. Choose Control > Test Movie to check your work. You should see the different button states appear as you roll over and press down on the button. A trace action appears in the Output panel when the button is clicked.
  2. Save the file.
 
Exercise 5: Explore the custom toggle button and grouped button samples
The process for creating toggle buttons and button groups roughly follows the same steps as Exercise 4. You set up the button timeline with frame labels, navigate to those frame labels based on mouse event timing, and dispatch events to the timeline containing the button instance for extended functionality.
 
This exercise guides you through key concepts as you explore the supplied custom toggle button and grouped button samples:
 
  1. Open the exercise5.fla file located in the buttons_exercises folder.
  2. Double-click the GroupedButton symbol in the Library to enter its timeline. Notice that the frame labels contain two states. Click Frame 1 of the actions layer and explore the ActionScript code in the Actions panel. Notice that the code includes the selected property, the setSelected function, and a mouse event handler.
  3. Double-click the ToggleButton symbol in the Library to enter its timeline. Notice that the symbol is exactly the same except for the graphics.
  4. Return to the main Timeline and view the actions on Frame 1 of the actions layer. Here you can see the radio group control code as well as the event handler for the check box. Notice that the code initializes inside of an ENTER_FRAME event handler function. This trick allows the code in the button instance to initialize before the main Timeline tries to work with it a frame later.
  5. Choose Control > Test Movie to view the file. You should be able to check and uncheck the check box button as well as change the selection in the radio group.

 
Using buttons as author-time shared assets

Flash Professional CS5.5 introduced the concept of author-time shared assets using the Project panel. This is a great feature to use if you need to create a series of branded assets that repeat across files in a project. The way it works is that an AuthortimeSharedAssets.fla file is created along with a new project. If you activate the Share symbol across files linkage option in the Library, the symbol is copied to the shared assets FLA and referenced from there by any other file in the project that uses it. The benefit of this strategy is the ability to change the button in a central location and have the change propagate out to all other files that use it in the project.
 
 
Exercise 6: Set up a Flash project containing buttons as author-time shared assets
Being able to share assets across files at author-time can make complex and repetitive projects easier to manage. For example, if you're creating a series of Flash banner ads which use the same assets across differently sized banner files, you can easily control changes across all files from a single location. Changing the color theme or graphics in any file updates all the other files that share that asset. This is quite a handy feature when you're working with dozens of banners in an ad campaign.
 
This exercise guides you through the process of setting up a project using buttons as author-time shared assets:
 
  1. Open your exercise4.fla file in Flash.
  2. Open the Project panel (Window > Project) and choose the Quick Project option in the Project menu in the top of the panel. This step creates a Flash project from the folder containing the selected FLA file.
  3. Click the Share symbol across files linkage button next to the PushButton symbol in the Library. This step copies the selected symbol to the shared assets FLA.
  4. Create another FLA file and save it into the project folder. Copy the button and paste it into the new FLA. Notice that the symbol sharing linkage comes along with it. You can now edit the button in any of the three FLA files and see the changes update across all of the files in the project.
See my article titled Working with the Project panel in Flash Professional for more information on using author-time shared assets.
 

 
Adding interactive button functionality to web and mobile applications

One of the cool things about building applications in Flash is that the content translates to a wide range of different media. For example, click events applied to buttons in a web application are interpreted as touch events on mobile devices. While you don't have the same interactive events related to a mouse in the mobile environment, the click events do translate. If you need alternative user input options to set up your application for mobile, check out the display object events specifically related to touch and gesture.
 
See the User interaction section of the ActionScript 3 Developer's Guide for more information about ways you can capture user interaction with Flash Player.
 

 
Where to go from here

Buttons are a basic part of developing user interfaces and are often the basis for other more advanced components. Take a moment to look through the Flash components and notice where buttons are used within other controls. It's helpful to spend some time working with the components and their ActionScript APIs to see how they are constructed.
 
Additionally, try creating custom buttons that use more complex button states. For example, you could add a setEnabled function to the button exercises you've been working with and create a disabled (or gray state) for the custom movie clip button.
 
To research further, check out the following online resources:
 
Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License+Adobe Commercial Rights
 
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. Permissions beyond the scope of this license, pertaining to the examples of code included within this work are available at Adobe.