16 December 2011
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.
All
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.
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:
This section provides an overview of button types, key terms used to describe button anatomy, and options available in Flash when creating 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.
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.
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.
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.
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.
Flash Professional provides both prebuilt buttons and options for creating custom buttons. You'll explore the following topics the remaining sections of this article:
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.
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.
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 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).
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.
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.
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:
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:
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);
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.
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:
stop();
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));
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:
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.
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.
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).
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.
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.
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.
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).
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.
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.
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.
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.
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);
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.
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.
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).
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.
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.
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.
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.
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:
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.
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();
import flash.events.MouseEvent;
function onButtonClick( event:MouseEvent ):void
{
trace("Handle custom button clicks here...");
}
myButton.addEventListener(MouseEvent.CLICK, onButtonClick);
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:
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.
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:
See my article titled Working with the Project panel in Flash Professional for more information on using author-time shared assets.
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.
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:
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.
| 04/23/2012 | Auto-Save and Auto-Recovery |
|---|---|
| 04/23/2012 | Open hyperlinks in new window/tab/pop-up ? |
| 04/21/2012 | PNG transparencies glitched |
| 04/01/2010 | Workaround for JSFL shape selection bug? |
| 02/13/2012 | Randomize an array |
|---|---|
| 02/11/2012 | How to create a Facebook fan page with Flash |
| 02/08/2012 | Digital Clock |
| 01/18/2012 | Recording webcam video & audio in a flv file on local drive |