While working on an application that has some drag and drop functionality, I noticed something very interesting about the dropTarget property of the Sprite class. It seems that the dropTarget returns the DisplayObject that is at the bottom of the display list which may not yield the result you are expecting. I added a MouseEvent.MOUSE_MOVE event listener to the Sprite being dragged and traced out the dropTarget to see what kind of result I would get.
Instead of seeing the names of Sprite instances that were set-up on the timeline, the trace output was nothing but generic names such as instance42. The reason for this is that the object at the very bottom of the display list is not the Sprite that was created, but the contents of that Sprite such as a Shape or Bitmap. It seems that the Flash Player automatically creates a DisplayObject for these internal Sprite elements and assigns them a unique instance name. Tracing out the dropTarget.parent then reveals the DisplayObject that we’re looking for. One thing to note is that a Sprite that only has visual elements that were created with the drawing API will not exhibit this behavior.
There are a couple of other things to be aware of when using the dropTarget. First, setting the mouseEnabled or mouseChildren properties to false will not keep a DisplayObject from being assigned to the dropTarget property. Second, depth has no effect on the assignment of a DisplayObject to the dropTarget propery. Objects at a higher depth than the object being dragged will react the same way as those that are under it. Third and probably the most important is that the assignment of the value for the dropTarget property is that of the DisplayObject that is directly under the mouse and has nothing to do with the bounding box of the DisplayObject being dragged. Lastly, there are definitely situations where the dropTarget will be null, so be sure to check for that before trying to access properties of the dropTarget or you’ll get everyone’s favorite error – TypeError: Error #1009: Cannot access a property or method of a null object reference.
example:
import flash.events.MouseEvent; import flash.display.Sprite; dragee.addEventListener(MouseEvent.MOUSE_DOWN,mouseDownHandler); dragee.addEventListener(MouseEvent.MOUSE_UP,mouseUpHandler); addEventListener(MouseEvent.MOUSE_MOVE,mouseMoveHandler); function mouseDownHandler(evt:MouseEvent):void { dragee.startDrag(); } function mouseUpHandler(evt:MouseEvent):void { dragee.stopDrag(); } function mouseMoveHandler(evt:MouseEvent):void { if (dragee.dropTarget!=null) trace(dragee.dropTarget.name); }
May the Null Object be your Friend.
That is EXACTLY what I was looking for. The parent thing worked perfectly. I wonder why that is not specified on the livedocs