Check if Mouse is Over an Object in AS 3

Knowing how to tell AS to do things depending on mouse events is basic yet very useful. In this tutorial we'll talk about MOUSE_OVER event, but you can easly modify the FLA file so other events are also taken into consideration (for example, CLICKED).

swf

 

 

1 Step.

Create three squares and tint them with whatever colors you like. Also, give them appropriate instance names (for example: red_sq, green_sq, and so on).

2 Step.

Copy and paste this code on the first frame.

 

red_sq.addEventListener(MouseEvent.MOUSE_OVER, myfunc);
green_sq.addEventListener(MouseEvent.MOUSE_OVER, myfunc);
blue_sq.addEventListener(MouseEvent.MOUSE_OVER, myfunc);
function myfunc(e:Event){
var overSq:MovieClip = (MovieClip)(e.target);
mouse_text.text = "Your mouse is over:" + overSq.name;
}

3 Step.

Now, add a nice textfield and give it an instace name so our function can communicate with the viewer.

4 Step.

Check other mouse events (a list of suggestion will usually roll down when you type "MouseEvent.").

 

FLA file attached below.

 

AttachmentSize
mouse_hover.rar10.03 KB
Average: 3.3 (3 votes)