Events

Events

Flash CS4 ActionScript 3.0 Tutorial

 

How to Add an Event that Triggers a Function Using Flash ActionScript

 

 

There are numerous events that occur in Flash. Once an event happens, a function is run. Examples of events include clicking a button, mousing over an object and checking the progress of a download.

You can also have events that are tied to the document's frame rate. In other words, if you're project is set to 24 frames per second (fps), the event occurs 24 times per second.

In this example we will illustrate how to create a MouseEvent that triggers a function. The function is also called the Event Handler.

For more information on Events, see topics, Enter Frame Event - Rotate Object at Current Frame Rate, Keyboard Press - Move Object, Mouse Event - Drag Object, Mouse Event - Hide Object and Timer Event - Count a Number.

Tutorial Elements

Button Symbol with instance name button01_btn

Movie Symbol with instance name of oval_mc

 

Step One

Open a new document and add a new layer.

Step Two

Name the upper layer Actions and the lower layer Content, then select the keyframe on the Content layer.

Step Three

Add a Button Symbol to the Content layer. A quick way is to choose Window > Common Libraries > Buttons.

Step Four

Select the Button Symbol and assign it an instance name of button01_btn in the Properties panel.

Step Five

Using the Oval tool, add an oval object to the Content layer.

Step Six

Select the oval object and press F8 to convert it to a Movie Symbol.

Step Seven

With oval Movie Symbol selected, assign it an instance name of oval_mc in the Properties panel.

Step Eight

Open the ActionScript panel for your keyframe in the Actions layer by Option double-clicking (PC - Alt double-clicking) the keyframe.

Step Nine

Copy/Paste the following code in the ActionScript Panel:

button01_btn.addEventListener(MouseEvent.CLICK, onClick01);

function onClick01(e:MouseEvent):void {

oval_mc.x +=10;

}

Step Ten

Click the Auto Format button to format the code

Step Eleven

Test your movie by pressing Cmd/Return (PC - Ctrl/Enter). Each time you press the button, the oval object moves 10 pixels to the right.

Dissecting the Code

The first line of the code at Step Nine adds an event listener to the button01_btn. Whenever the button is clicked, the onClick01 function is triggered.

The next lines of code define the function. Each time the function is called, the oval_mc moves to the right 10 pixels.

This Causes That

Events (button click) and Event Handlers (onClick01 function) work as a team. By clicking the button, you tell the function to run.

 

Lynda.com career skills