Mouse Event - Drag Object

Mouse Event - Drag Object

Flash CS4 ActionScript 3.0 Tutorial


How to Click-Drag an Object in Flash



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 write ActionScript code that allows the user to click and drag an object across the stage.

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

Tutorial Elements

Movie Symbol with instance name of oval_mc


Step One

Open a new document and add a new layer above the default layer.

Step Two

Name the upper layer Actions and the lower layer Content.

Step Three

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

Step Four

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

Step Five

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

Step Six

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

Step Seven

Copy/Paste the following code in the ActionScript Panel:

oval_mc.addEventListener(MouseEvent.MOUSE_DOWN, onDrag01);

oval_mc.addEventListener(MouseEvent.MOUSE_UP, onNoDrag01);

function onDrag01(e:MouseEvent):void {



function onNoDrag01(e:MouseEvent):void {



Step Eight

Click the Auto Format button to format the code

Step Nine

Test your movie by pressing Cmd/Return (PC - Ctrl/Enter). Whenever you click-drag the oval object, it moves with the mouse.

Dissecting the Code

The first two lines of the code at Step Seven add event listeners to oval_mc. The first line listens for a mouse down event on the oval shape. The second one listens for the release. Whenever the Movie Symbol is clicked or released, the functions onDrag01 and onNoDrag01 are run.

The next lines of code define the onDrag01 function. Each time the function is called, the oval_mc moves and follows the user's mouse.

The final function (onNoDrag01) stops the dragging and releases the oval shape.

This Causes That

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