Express in Bits Blog

AS3: Use Dynamic TextField in Buttons

Posted in Actionscript 3 by xding78 on February 17, 2010

When you develop Flash animation for a while you’re bond to run into this issue: How can I use dynamic textField in a button and make it behave like a button?

To make any Sprite or MovieClip a button is as simple as telling AS3 that:

mc.buttonMode = true;

However, if you happen to use a dynamic textField in the MovieClip or Sprite then you have a problem. Whenever mouse hovers the textField, the mouse cursor changes to the cursor that typically associate to text input field. While that’s not what you want for a button.

I’m sure there are many solutions, the solution I use is kind of quick and dirty. I call it Button Mask.

Here are the steps (use timeline):

  1. Draw a shape that covers the entire button mc.
  2. Make in a MovieClip itself, give it an instance name, i.e. “btnMask
  3. Make sure the “btnMask” object is on the top layer.
  4. Make sure that the “btnMask” object is there but invisible: either set the Alpha value of the “btnMask” object to zero or make sure that the fill Alpha of the object is zero.
  5. In the actionscript code:

    mc.btnMask.buttonMode = true//mc is the instance name of the MovieClip

    mc.btnMask.addEventListener(MouseEvent.CLICK, mcClicked);

    function mcClicked(e:MouseEvent):void{

         e.target.parent.gotoAndStop(2); //when clicked, mc goes to frame 2

    }

The key here is that you have to remember to manipulate on the e.target.parent (which is the mc), instead of e.target (which is the btnMask). If you encounter any problem, such as the compiler complains no such object, then it’s  always useful to first use :

trace(e.target.name);

to find out what exactly is the object that hovered by mouse.

If you construct everything from actionscript 3 code, then what you need to do is

  1. draw a shape
  2. give it an instance name
  3. add it to MovieClip
  4. set the index of this shape to the top
  5. Then the same code.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: