Thursday, October 29, 2009

Detecting when mouse leaves stage

This is how you detect if the mouse leaves Flash and rolls over to web page:
stage.addEventListener( Event.MOUSE_LEAVE, mouseLeaveListener );
Additionally you can also tell when the flash movie gains and loses focus, which you couldn't do in AS 2, by listening for Event.ACTIVATE and Event.DEACTIVATE.

Here is some code that detects enter/exit. Just paste into main timeline, compile, then view embedded in an html page:

//draw a box for demonstration purposes
var c:Sprite = new Sprite();
c.graphics.beginFill(0xFF);
c.graphics.drawRect(0, 0, 200, 200);
addChild(c);

//NOTE this only works embedded in a web page
//detect mouse leaving flash and rolling over web page
stage.addEventListener(Event.MOUSE_LEAVE, cursorHide);

//there is no mouse exit so you need to use this
stage.addEventListener(MouseEvent.MOUSE_MOVE, cursorFollow);

function cursorHide(evt:Event):void {
c.alpha=.2
}


function cursorFollow(evt:MouseEvent):void {
c.alpha=1
evt.updateAfterEvent();
}

No comments: