Detecting when a button is pressed in Flash with ActionScript 3.0

by Peter deHaan on November 25, 2008

in Button

The following example creates a listener for the click event on a Button instance called myButton.

Full code after the jump.


You can detect when a Button instance is pressed by listening for its click event (using the flash.events.MouseEvent.CLICK constant) or its change event (using the flash.events.Event.CHANGE constant) to be dispatched. Using ActionScript 3.0, you listen for events using the addEventListener() method. For more information on handling events in ActionScript 3.0, see the “Event handling” Quick Start article.

Note: ActionScript 2.0 provided three event handling models. ActionScript 3.0 simplifies the process by using a single event handling model. Also, ActionScript 2.0 didn’t use constants for event names but ActionScript 3.0 does.

// ActionScript 3.0
// Requires a Button component instance on the Stage with an instance name of "myButton".
myButton.addEventListener(MouseEvent.CLICK, clickHandler);
 
function clickHandler(evt:MouseEvent):void {
    trace("clicked");
}

The following example uses an event listener to detect when the button’s click event has been dispatched, and updates the label accordingly:

// ActionScript 3.0
// Import the required component classes.  
import fl.controls.Button;
 
// Create a new Button component instance, and add it to the display list.
var myButton:Button = new Button();
myButton.label = "Click me";
myButton.move(10, 10);
myButton.addEventListener(MouseEvent.CLICK, clickHandler);
addChild(myButton);
 
/* Handler function for the Button component instance. This function updates
   the button's label property when the button is clicked. */
function clickHandler(evt:MouseEvent):void {
    myButton.label = "Ouch!";
}

For more information on the Flash/ActionScript 3.0 Button component, see the “Using the Button component” Flash Quick Start on Adobe.com.

{ 0 comments… add one now }

Leave a Comment

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

Previous post:

Next post: