Sunday, November 22, 2009

Flash CS3/Actionscript 3 Hover ALT TEXT

I needed to create some hover text over my buttons in Actionscript 3. I Google around and couldn't successfully find an AS3 version. I did find a AS1/2 version at kirpa.com. So I ventured out and did a quick write of my own.

First thing you need to know how to do is pass in multiple parameters on an "addEventListener". Then you just need to write a function to accept these parameters.

Here is what I did. I wrote a generic function called, HoverText. It accepts three parameters. The first is a text string, this is what I want the hover to display. The second is the X position of the hover text. The third is the Y position of the hover text.
HoverText(_text:String,capX:Number,capY:Number)

Since I knew the X & Y coordinates of the buttons and the hover text I wanted to pass in, it made the function really simple. I didn't have calculate anything. Just display at the proper spot.

In AS3 I put two MouseEvent eventListeners on each button, a MouseOver, and a MouseOut. All I had to do was create a function on the eventlistener to allow me to pass multiple parameters. This is a bit different than Javascript, but I figured it out.

Here are my two eventListeners for each button:
btn_1.addEventListener(MouseEvent.MOUSE_OVER, function(e:Event) { HoverText("This is my main hover text sentence",713,256);});
btn_1.addEventListener(MouseEvent.MOUSE_OUT, function(e:Event) { HoverText("out",0,0);});

The first one, Mouse Over, I setup to be the display of the hover text. The second one, is my mouse out. So I set this text to be "out". I could have probably done a NULL, but didn't.

Then my function takes the three params and generates a text field.



var captext:TextField;

function HoverText(_text:String,capX:Number,capY:Number):void {
trace(_text + " " + capX + " " + capY);
if (_text == "out") {
trace("out");
removeChild(captext);
}
else {
trace("in");
captext = new TextField();

captext.x = capX;
captext.y = capY;
captext.text = _text;
captext.background = true;
captext.autoSize = TextFieldAutoSize.RIGHT;


addChild(captext);
}

};



So the function has its three parameter pass ins. The first if the message I want to display. The second is the X coordinate. The third is the Y coordinate. You can see that I create a new dynamic textfield called "captext". I set the X and Y to the proper coordinates. Then the text to the string passed in. I turn the background on. Why you ask? If I don't, the background is transparent and the text blends right in. I set the text field to autosize in width and height from the "RIGHT", which means the top right corner of the text field.

I put in an "IF" statement too...if I'm passing in the "out" statement. I want the hover text to disappear so I just do a removeChild on the element I added on the mouse in event.