Mouse click event handling in Flash Actionscript 3 (AS3)

When I first used Flash I learned to program Actionscript 2, and handling clicks on objects was easy: you could simply attach code to the movieclip or button. Today I had to do the same thing in Actionscript 3, and it’s all changed, so I thought I’d write the whole process down – from scratch, as it’s a handy first step for those new to ActionScript and Flash. Here’s how it works.

First, you’ll need a movieclip or button on the stage with an instance name assigned. To create one, click the rectangle tool and drag out a box. Choose the selection tool and double-click it to select.

Right-click and choose Convert to Symbol from the menu. Give the symbol a name for the library (“block”, perhaps) and leave Type as Movie Clip. Click OK.

Make sure the clip is selected (if not, left-click), then look in the Properties toolbar. Enter an instance name: I’ve used “m_block_1”. Here’s how it should look:

The MovieClip in Flash CS5

Now it’s time to add the ActionScript. Right-click on the current frame – frame 1 – in the timeline, and choose Actions. The Actions window or panel will appear.

In ActionScript 2 (AS2) you could add the actions you want performed when the MovieClip is clicked directly to the clip (or by using something like m_block_1.onRelease = function() {}). In AS3, though, we have to add them to the timeline, and we need to add two bits of code: an EventListener for the MovieClip, telling it to do something (a function) when something happens (a mouse event), and the function to perform on that event.

In this case, we need to add the event listener to m_block_1, and we’ll have it call a function called doSomething. Code:

m_block_1.addEventListener(MouseEvent.CLICK, doSomething);

Then define the function doSomething. We’ll simply have it trace for now. Code:

function doSomething(event:MouseEvent):void{

trace(“Box has been clicked”);


And that’s it. In this case the function will execute when the MovieClip is clicked, but you can also listen for mouse button press (use MOUSE_DOWN instead of CLICK), release (MOUSE_UP) and other non-button actions such as leaving the object (MOUSE_OUT). There’s a list on the Adobe site here.

You may, later on, wish to remove this event handler. To do so, replace addEventListener with removeEventListener:

m_block_1.removeEventListener(MouseEvent.CLICK, doSomething);

It’s even possible to put removeEventListener in the function called by addEventListener, limiting the function to running on the first click only. If you’re using a Button rather than a MovieClip the whole process is just the same – it makes no difference to the code.

All © 2022 Tom Royal