Listening to MouseEvents in ActionScript 3
May 3rd, 2009
There are a number of MouseEvents that a MovieClip can listen to. You can see them all at the ActionScript 3.0 Flash Player 9 Language Reference here. The most common is listening to when something is clicked.
To listen for when a MovieClip is clicked, we need to add a listener to the MovieClip, and a assign a function to be called when the event happens. This is where giving your MovieClip an instance name comes into play. You use the instance name that you gave the MovieClip in the Properties Panel to target that MovieClip with ActionScript. In this example, we are targeting the sun_mc MovieClip;
// this gives the movieclip a pointer cursor
sun_mc.buttonMode = sun_mc.useHandCursor = sun_mc.mouseEnabled = true;
// this adds a listener to the sun, whenever its clicked, the handleMouseUp function is called
sun_mc.addEventListener(MouseEvent.MOUSE_UP, handleMouseUp);
// this is the handleMouseUp function
function handleMouseUp(e:MouseEvent) : void {
// Because its an event handler you can grab a reference to whatever was clicked through the MouseEvent parameter, in this case clicked will always be sun_mc
var clicked:MovieClip = e.currentTarget as MovieClip;
// clicked is the same thing as sun_mc, we tell it to go to and play the clicked frame on its timeline
clicked.gotoAndPlay("clicked");
}
Get the source example files here.
If you have questions feel free to post comments to this blog post or post to the forum.