ActionScript3:Using EventListeners to change a Button Event

Introduction
Use EventHandlers to change the reaction that occurs when you click on a button.

Setting the Stage
Create a new ActionScript 3 File. In this example we only need a small stage, 400px x 200px. With the first frame of layer One selected, draw a small button shaped rectangle and position it centered near the bottom of the stage. Convert to a movieClip, and name it. Doubleclick the  movieclip and on the timeline add a second layer above layer 1. Call it text. With frame one of the text layer selected and the text tool selected, position a dynamic text box over the button. In the properties panel, name this. Return to Scene 1.

Insert above layer 1 of the main timeline, a new layer and call it Actions.

Create a new movieClip, Insert...New Symbol...movieClip. Give it the name square, tick the boxes Export for ActionScript and Export in frame 1. In the Class field, type. Click Ok, Click Ok again if you get any warning messages. This movieClip is now available in your library, but is an empty movieClip so we need to give it some content.

Double Click square within your library to bring it onto the stage. Draw a small rectangle, keeping the registration point centered - about 195 px wide and 150 px high. Any colour will do. Find a small photo from you collection and import this to the stage. Reduce in size and center over the Square. Give it a text label if you like.

It should look something like this:



Inserting the ActionScript
Return to Scene 1. Click on frame one of the Actions layer, and insert the following ActionScript:

This ActionScript stores an instance of  that you just created in a variable. The next line allows a movieClip, in this case the one we called, to act as a button. Add the eventListener method to it to call a function (showPhoto) and dynamically create the button text.

Next we create the functions that will add the photoContainer to the stage at a position determined by the x and y coordinates, add an  so each time the frame is entered an action takes place and set the conditions for things to happen.

Insert the following Actionscript directly below the script already there:

The  function in this case is moving the box containing you photo, down from the top of the stage to a resting point just above the button. When it reaches this position (y at 80 px), the  method is used to stop the reaction, remove the   that listens for the mouse click on the button and initiates the   function and adds the   to call the   function. The button label also now reads Hide Photo.



All that is left to do now, is to create a function (removePhoto) that returns the photo to its resting place off the stage and returns the button to its original state.