Back to Entry Page

Handler Precedence in ActionScript
Or, The Click Problem

The Problem

We need to consider another significant flaw in ActionScript: common mouse events are handled inconsistently by buttons and movie clips.

Confusingly, ActionScript uses two different pairs of events to register the pressing and releasing of the mouse button (the two parts of what we loosely refer to as a click). Movie clips interpret these actions through the mouseDown and mouseUp events--whose names, at least, will be familiar from JavaScript and other languages. Buttons, on the other hand, respond to press and release.

Press and release are localized to the software button--the Flash Symbol on the screen--over which the cursor is positioned when the physical mouse button is pressed or released. That is, the release event happens only when the mouse button is released while the cursor is over a button Symbol. A button press/release that happens with the cursor outside any button generates no event.

As the demonstration below shows, this provision does not apply to the mouseDown and mouseUp events used by movie clips. The mouseDown event simply means that the physical mouse button has been pressed. It says nothing about the cursor position. If you write a script on a movie clip that handles the mouseDown event, it will respond no matter where the cursor is. Notably, it will also respond to a click on a button symbol, which in this case generates both a press and a mouseDown.

To see the problem in action, hold the mouse button down while over any of the symbols below. Then try mousing down while your cursor is over no symbol.

If you do not address this problem, you will not be able to use movie clips with mouse event handlers in any timeline that also includes buttons--clicks on the buttons will activate the clip handlers as well.

The Solution

Luckily, there is a relatively simple solution for the click problem. ActionScript includes a method called hitTest(). This method can determine one of two things: whether two Symbols coincide on the screen; and whether the current mouse position, given as the coordinate pair _root._xmouse, _root._ymouse, coincides with a Symbol.

We'll come back to the first usage when we look at game design. For the purposes of clips and buttons, the second usage is most relevant. Here's a script to localize mouseDown for a Movie Clip:

onClipEvent(mouseDown){
  if(this.hitTest(_root._xmouse, _root._ymouse)){
      //...take some action
  }
}

To test this script in action, try the demonstration below:

If you want a Movie Clip to respond to movement of the mouse within its boundaries with no click (the classic mouseOver), then just change the handler from onClipEvent(mouseDown) to onClipEvent(mouseMove).

The source files for the example above is on Crow as MMShare/clickProblem/clickFix.fla.


University of Baltimore Logo

Copyright © 2002 School of Information Arts and Technologies