ActionScript3:Using EventListeners to change a Button Event
|Flash10 (CS4) | Flash11 (CS5) <|
|Table of contents|
Use EventHandlers to change the reaction that occurs when you click on a button.
By the end of this exercise you should:
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
photo_btn. Doubleclick the
photo_btn 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
myText. 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
photoContainer. 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
photoContainer that you just created in a variable
myPhoto. The next line allows a movieClip, in this case the one we called
photo_btn, 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
eventListener 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:
onEnter 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
removeEventListener method is used to stop the reaction, remove the
eventListener that listens for the mouse click on the button and initiates the
showPhoto function and adds the
eventListener to call the
removePhoto 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.