ToolTip In AS3

Here is the way I made Tooltip for my flash projects.
It's class attached to library symbol, in order to change skin you have to just modify movieclip in library. Background contains guides for 9 slice scaling.
Update
Example of accessing tooltip from external movie is uploaded with the source files.

It changes also direction automatically based on stage width and height if its near borders.
Here is the example of using it:

Get Adobe Flash player

ToolTip.as

Actionscript:
  1. package com.abrahamyan.liquid
  2. {
  3.     import flash.display.MovieClip;
  4.     import flash.events.Event;
  5.     import flash.events.TimerEvent;
  6.     import flash.text.TextFieldAutoSize;
  7.     import flash.text.TextField;
  8.     import flash.utils.Timer;
  9.     import gs.TweenLite;
  10.     import gs.OverwriteManager;
  11.     import gs.easing.*;
  12.     /**
  13.      * ...
  14.      * @author Armen Abrahamyan | http://abrahamyan.com | armflash (at) gmail.com
  15.      */
  16.     public class ToolTip extends MovieClip
  17.     {
  18.         public var _multiLine:Boolean = false;
  19.         public var  labelMargin:Number = 10;
  20.         public var arrowMargin:Number = 10;
  21.         public var showDelay:Number = .5;
  22.         public var hideDelay:Number = .5;
  23.         //
  24.         private static var instance:ToolTip;
  25.         private static var allowInstance:Boolean;
  26.         private var _label:String;
  27.         private var _fixedWidth:Number = 50;
  28.         private static const DIRECTION_LEFT:String = "directionleft";
  29.         private static const DIRECTION_RIGHT:String = "directionright";
  30.         private static const DIRECTION_TOP:String = "directiontop";
  31.         private static const DIRECTION_BOTTOM:String = "directionbottom";
  32.         private var _horDirection:String;
  33.         private var _verticalDirection:String;
  34.         private var _followMouse:Boolean;
  35.         private var _timer:Timer;
  36.         private var _xposition:Number;
  37.         private var _yposition:Number;
  38.         private var _stageWidth:Number;
  39.         private var _stageHeight:Number;
  40.         private var _labelColor:Number;
  41.        
  42.         /**
  43.          *
  44.          */
  45.         public function Tooltip()
  46.         {
  47.             if (!allowInstance)
  48.             {
  49.                 throw new Error("use ToolTip.getInstance() instead of new keyword !");
  50.             }
  51.  
  52.         }
  53.         /**
  54.          *
  55.          * @return
  56.          */
  57.         public static function getInstance():ToolTip
  58.         {
  59.             if (instance == null)
  60.             {
  61.                 allowInstance = true;
  62.                 instance = new ToolTip();
  63.                 allowInstance = false;
  64.             }else
  65.             {
  66.                 trace("ToolTip instance already exist !");
  67.             }
  68.             instance.init();
  69.             return instance;
  70.         }
  71.         /**
  72.          * sets label multiline /singleline
  73.          */
  74.         public function set multiLine(pEnabled:Boolean):void
  75.         {
  76.             _multiLine = pEnabled;
  77.             if (_multiLine)
  78.             {
  79.                 label_txt.multiline = true;
  80.                 label_txt.wordWrap = true;
  81.                 label_txt.width = _fixedWidth;
  82.                 label_txt.autoSize = TextFieldAutoSize.RIGHT;
  83.                
  84.             }else
  85.             {
  86.                 label_txt.multiline = false;
  87.                 label_txt.wordWrap = false;
  88.                 label_txt.autoSize = TextFieldAutoSize.LEFT;
  89.             }
  90.        
  91.         }
  92.         /**
  93.          * sets fixed width for the multiline tooltips
  94.          *
  95.          */
  96.         public function set fixedWidth(pWidth:Number):void
  97.         {
  98.             _fixedWidth = Math.max(pWidth, 50);
  99.         }
  100.         /**
  101.          * sets new label color
  102.          */
  103.         public function set labelColor(pColor:Number):void
  104.         {
  105.             _labelColor = pColor;
  106.             label_txt.textColor = _labelColor;
  107.         }
  108.        
  109.         /**
  110.          * returns label color
  111.          */
  112.         public function get labelColor():Number
  113.         {
  114.             return _labelColor;
  115.         }
  116.         /**
  117.          *
  118.          */
  119.         private function init():void
  120.         {
  121.             alpha = 0;
  122.             visible = false;
  123.             cacheAsBitmap = true;
  124.             this.mouseChildren = false;
  125.             this.mouseEnabled = false;
  126.             label_txt.x = labelMargin;
  127.             label_txt.autoSize = TextFieldAutoSize.LEFT;
  128.            
  129.             _horDirection = DIRECTION_RIGHT;
  130.             _verticalDirection = DIRECTION_TOP;
  131.             addEventListener(Event.ADDED_TO_STAGE, onAdded, false, 0, true);
  132.             reSize();
  133.         }
  134.         private function onAdded(e:Event):void
  135.         {
  136.             removeEventListener(Event.ADDED_TO_STAGE, onAdded);
  137.             onStageResize();
  138.             stage.addEventListener(Event.RESIZE, onStageResize, false, 0, true);
  139.            
  140.         }
  141.         private function onStageResize(e:Event=null):void
  142.         {
  143.             _stageWidth = stage.stageWidth;
  144.             _stageHeight = stage.stageHeight;
  145.        
  146.         }
  147.        
  148.        
  149.         private function reSize():void
  150.         {
  151.             bg_mc.rect_mc.width = label_txt.textWidth + 2 * labelMargin +6;
  152.             bg_mc.rect_mc.height = label_txt.textHeight +16;
  153.             bg_mc.arrow_mc.scaleX = (_horDirection == DIRECTION_RIGHT)?1: -1;
  154.             bg_mc.arrow_mc.scaleY = (_verticalDirection == DIRECTION_TOP)?1: -1;
  155.             bg_mc.arrow_mc.x = (_horDirection == DIRECTION_RIGHT)?arrowMargin:(bg_mc.rect_mc.width-arrowMargin);
  156.             bg_mc.arrow_mc.y = (_verticalDirection == DIRECTION_TOP)? bg_mc.rect_mc.height:0;
  157.         }
  158.         /**
  159.          * shows tooltip
  160.          * @param   pLabel label of tooltip
  161.          * @param   pXpos  if followMouse property is set to true, this property is X offset from mouse position, else postion of x coord. of tooltip
  162.          * @param   pYpos  if followMouse property is set to true, this property is Y offset from mouse position, else postion of y coord. of tooltip
  163.          */
  164.         public function show(pLabel:String="", pXpos:Number=0,pYpos:Number=0):void
  165.         {
  166.             this.alpha = 0;
  167.             this.visible = false;
  168.             _label = pLabel;
  169.             label_txt.text = _label;
  170.             _xposition = pXpos;
  171.             _yposition = pYpos;
  172.             // check for timer, just in case...
  173.             if (_timer)
  174.             {
  175.                 _timer.stop();
  176.                 _timer.removeEventListener(TimerEvent.TIMER, onTimer);
  177.                 _timer = null;
  178.             }
  179.             updatePosition();
  180.            
  181.             TweenLite.killTweensOf(this);
  182.             TweenLite.to(this, showDelay, { autoAlpha:1, ease:Linear.easeNone } );
  183.            
  184.             if (_followMouse)
  185.             {
  186.                 _timer = new Timer(20);
  187.                 _timer.addEventListener(TimerEvent.TIMER, onTimer, false, 0, true);
  188.                 _timer.start();
  189.             }
  190.         }
  191.         private function updatePosition():void
  192.         {
  193.             var xpos:Number = _followMouse?(stage.mouseX + _xposition):_xposition;
  194.             var ypos:Number = _followMouse?(stage.mouseY + _yposition):_yposition;
  195.             _horDirection = (xpos + bg_mc.rect_mc.width - arrowMargin> _stageWidth)?DIRECTION_LEFT:DIRECTION_RIGHT
  196.             _verticalDirection = (ypos -bg_mc.rect_mc.height - bg_mc.arrow_mc.height <0)?DIRECTION_BOTTOM:DIRECTION_TOP;
  197.             reSize();
  198.             this.x = Math.round((_horDirection == DIRECTION_LEFT)?(xpos-bg_mc.rect_mc.width+arrowMargin):(xpos-bg_mc.arrow_mc.x));
  199.             this.y = Math.round((_verticalDirection == DIRECTION_TOP)?(ypos - bg_mc.rect_mc.height - bg_mc.arrow_mc.height):(ypos + bg_mc.arrow_mc.height));
  200.         }
  201.         /**
  202.          * hides tooltip
  203.          */
  204.         public function hide():void
  205.         {
  206.             if (_timer)
  207.             {
  208.                 _timer.stop();
  209.                 _timer.removeEventListener(TimerEvent.TIMER, onTimer);
  210.                 _timer = null;
  211.             }
  212.             TweenLite.killTweensOf(this);
  213.             TweenLite.to(this, hideDelay, {autoAlpha:0,ease:Linear.easeNone } );
  214.         }
  215.         private function onTimer(e:TimerEvent):void
  216.         {
  217.             e.updateAfterEvent();
  218.             updatePosition();
  219.         }
  220.         /**
  221.          * if true, tooltip will foloow mouse
  222.          */
  223.         public function set followMouse(pFollow:Boolean):void
  224.         {
  225.             _followMouse = pFollow;
  226.         }
  227.         /**
  228.          * returns boolean value if tooltips follows mouse or not
  229.          */
  230.         public function get followMouse():Boolean
  231.         {
  232.             return _followMouse;
  233.         }
  234.         /**
  235.          * use destroy() method before removing tooltip from stage
  236.          * cleans/removes listheners/timers
  237.          */
  238.         public function destroy():void
  239.         {
  240.             TweenLite.killTweensOf(this);
  241.             stage.removeEventListener(Event.RESIZE, onStageResize);
  242.             if (_timer)
  243.             {
  244.                 _timer.stop();
  245.                 _timer.removeEventListener(TimerEvent.TIMER, onTimer);
  246.                 _timer = null;
  247.             }
  248.         }
  249.     }
  250.    
  251. }

Download source files
Access from external source files.

Bookmark and Share

Releated Posts

95 Responses to “ToolTip In AS3”


  • I am come from China.I find your blog in Google.Then I try the ToolTips Class in my project,then I found a problem.when I use Like this: toolTip.show(“你好”); I can see nothing on screen,but not english.so I trace the label_txt.text.I can see “你好”.What’s the problem?

  • @Jerry problem is in font, you have to select textfield inside library, change the font to the one that supports Chinese and embed all chars for the font. Try to change the font to Arial for example.

  • Very nice !!!
    But just problem when i try use ‘à’ in the tooltip.show.
    It’s ok with ‘é’ ans ‘è’ but not with ‘à’ …this character is not displayed

  • @cyril thx, read prev comment regarding embeding fonts and special characters.

  • This tooltip doesn’t seem to work with movieclip buttons. Am I missing something?

  • Actually, correction. It works perfectly fine with movieclip buttons generally. However, I have a movieclip button with a 45% transparent layer inside of it, and that seems to make it not work for some reason.

  • @Amir problem is in ur movieclip/button, doesn’t have any relationship with tooltip

  • Hello, how do you get the auto direction to work? I can’t figure it out?

  • ahhh ok, i see it only changes direction near the stage borders. I thought it changed based on where the mouse was on the button.

  • @thien it should work automatically based on stageWidth and stageHeight.
    U might need to set:
    stage.scaleMode= StageScaleMode.NO_SCALE;
    stage.align = StageAlign.TOP_LEFT;

    take a look at example fla file, try to change the stage size and run it again.

  • Armen, what if I wanted to use several differently designed tool tips in my poject? For example, in addition to the tooltip you created in the example, I also wanted to use a tooltip I designed. Right now it seems I can only use one tooltip design. Is this correct?

  • @thien right now its working with one design/skin.
    you can edit symbols in library, give them different look, but still will be one type.
    well, in general in most cases from my experience in one project tooltips are same style.
    From the other hand adding skin change functionality is not hard, all you have to do is write a public method to change rect and arrow(remove the existing and add new).
    Tooltip design I use is simple-> rounded rectangle, arrow, textfield. Once the new design keeps that structure will be no problem to update it/change it runtime.
    that should cover with the new method-> changeSkin(rect, arrow)
    I will try to find a time to add that functionality in a week.
    thx

  • hi, I just wanted to add a contribution that may help whenever you want the tooltip to be added as a child only when a ui component is instantiated and the stage is not the “root stage” but the ui component stage…


    private function updatePosition():void
    {
    var xpos:Number = _followMouse?(stage.mouseX + _xposition):_xposition;
    var ypos:Number = _followMouse?(stage.mouseY + _yposition):_yposition;
    var point:Point;
    if(this.parent)
    {
    point = this.parent.globalToLocal(new Point(xpos, ypos));
    }
    else
    {
    point = (new Point(xpos, ypos);
    }
    _horDirection = (point.x + bg_mc.rect_mc.width - arrowMargin > _stageWidth)?DIRECTION_LEFT:DIRECTION_RIGHT
    _verticalDirection = (point.y -bg_mc.rect_mc.height - bg_mc.arrow_mc.height < 0)?DIRECTION_BOTTOM:DIRECTION_TOP;
    reSize();
    this.x = Math.round((_horDirection == DIRECTION_LEFT)?(point.x-bg_mc.rect_mc.width+arrowMargin):(point.x-bg_mc.arrow_mc.x));
    this.y = Math.round((_verticalDirection == DIRECTION_TOP)?(point.y - bg_mc.rect_mc.height - bg_mc.arrow_mc.height):(point.y + bg_mc.arrow_mc.height));
    }

  • Thanks for the tutorial, very useful!!

    I’m just having a little trouble with something, I’ve added the tooltips to a website I’m designing and it’s all working fine.The page loads with a page transition and then the content loads..but when the content loads (which has a map with the tooltips) my swf moves from the centre stage to top left. I tried changing the

    addChild(tooltip)
    stage.scaleMode= StageScaleMode.NO_SCALE;
    stage.align = StageAlign.TOP_LEFT
    ;

    and also had a look in the as files, but no luck. Would you be able to point me in the right direction.

    Thanks again!

  • @Anneka pls read the comments.
    my suggestion: init/add tooltip inside main container swf.
    as its singleton u can get him from everywhere.(ToolTip.getInstance())

    thx

  • Thank You for this excellent tutorial. There are not too many on the web that are understandable to a newbie like myself. I have the tooltips appearing in an SWF which is working fine. The problem is when I load this SWF into another movie (into a loader) the tooltips are appearing off the stage (towards the bottom). I have tried to figure out why this is happening and have had no luck. Could you help me out please? I hesitated to write you as I am sure you are busy with more important matters, but I really don’t know where else to turn.

    Thanks in advance!
    Dallas

  • @Dallas thx for comment. The problem is in coordinates, when u load inside another container coordinates are changing.
    I mention about it several times in comments.
    >>>
    @Anneka pls read the comments.
    my suggestion: init/add tooltip inside main container swf.
    as its singleton u can get him from everywhere.(ToolTip.getInstance())
    >>>
    you always setup tooltip in main container, and you can access it from everywhere as its singleton: ToolTip.getInstance() will always return you same instance of tooltip that you have setup in main container.
    hope that helps.
    thx

  • Armen,
    Thanks for the reply. I understand what you are saying about initializing the tooltip in the main container. However, I need the buttons to appear within a nested movie (it is a cursor controlled panning image, so the buttons have to be nested within that movie so that they pan with the image). If I call the tooltip in the main containing movie and the instances of the buttons are all within the nested movie, the relationship becomes broken and I get errors. Could you perhaps explain this to me a bit more? I am still needing training wheels at this stage. :)
    Sincerely appreciated!
    Dallas

  • If it helps, here are my files:
    http://www.mediafire.com/?7ct9zf6b956kloz
    Again, thanks, yours is the very best tutorial on tooltip class AS3. I just need a bit of help. Thanks!!!!
    D

    P.S. I’m sorry if I wasn’t supposed to post links here… :)

  • Armen,

    If you ever get around to answering the last post from Dallas, it would be a good thing. It seems like more than one person has asked you about this topic. However, your answers are so brief, it is hard to understand what you mean or how to go about solving the problem. Maybe if you answered the post in a bit more detail people would stop asking the same question. Otherwise, thanks for the post.

    Cheers,

    Ed

  • @Eddie, @Dallas
    Example of using tooltip from external SWF is uploaded with source: http://abrahamyan.com/wp-content/uploads/2009/tooltip/tooltip_with_external_call.zip

    I simply use public/untyped var for referencing tooltip, this way you don’t need to include tooltip assets in ur external library. If you need them there for some reason( test external swf with tooltip) you have to include assets and use var tooltip:ToolTip = ToolTip.getInstance()

    hope that helps.
    thx

  • Thanks Armen,
    That rally helps!

    Cheers,

    Ed

  • Hi Armen,

    thanks for this great tutorial.

    There is only one thing to mention: showDelay and hideDelay are not named correctly. this parameters are not for the delay, but the fade time for showing/ hiding.
    To add a delay you could take TweenMax instead of TweenLite and set the delay to showDelay/ hideDelay:

    TweenMax.to(this, showTime, { delay:showDelay, autoAlpha:1, ease:Linear.easeNone } );

    thx

  • @Johannes.
    I meant delay before show & hide. Works Exactly the same,
    and “delay” property exist in tweenlite as well. I don’t think there is any difference for the “delay” property in tweenlite & max.

    thx

  • Thanks Armen! Your tooltip class are very usefull, but you should update your class take into consideration changing greensock library.

    1)import com.greensock.TweenLite; instead of gs.TweenLite;
    2)activate autoAlpha plugin:
    TweenPlugin.activate([AutoAlphaPlugin]);

  • @Mike thx, well was a long time ago when I wrote this, things are changed for sure.
    Feel free to change the class files, I’m sure I have included old library files with the source, so it should still be fine if you don’t change them :)

  • @armen Thanks a lot! I have changed them at once. But I wrote previous comment hoping you’ll updated sources (in this page) for other people that may be intrested in it.

  • How would I go about adding the capability to put a picture in the tooltip?

    Thank you so much for this example of tooltip. It looks great!
    Ray

  • @Ray You can change textfield inside library to support html, use html tag to show image. Also inside ToolTip.as change:
    label_txt.text = _label; to label_txt.htmlText = _label;

    Thx

  • I hope I am not bothering you with my questions.
    I am new to AS3.

    In ToolTip.as (In public function show)changed:
    label_txt.text to label_txt.htmlText = _label;

    In Library of tooltipCS3.fla (mc Tooltip Symbol) changed:
    selected label_txt and clicked “Render as HTML”

    Then I changed tooltip.show in switch, case, “btn1″
    by placing before the word TOOLTIP and after it.

    I then did Control – Test Movie to run it.
    Results: It ran but “TOOLTIP” was not bold. And text was not Red.
    (seems to have overridden the textfield command that made the text Red)

    I then tried the image tag.
    Results: I got was a very small tooltip box and the arrow (it was not attached and was full size).

    Do have any suggestions as to what I may have done wrong?

    Thanks again,
    Ray

  • Armen,

    I got it to work! It no longer accepts some of the Textfield properties(I think that’s the right word, I’m also new to OOP), labelColor for example, but I can get an image in the tooltip and I can control formatting of text with HTML. I am going to play with the code and see if I can get both to work. I am having more fun with Flash. Before I retired I was a COBOL and Fortran programmer.

    Ray

  • @Ray glad that worked for you and good luck with exploring flash! :) :)

  • hai armen..
    i am a beginner in using flash…
    i like ur tutorial..it easy to understand…
    the prob is when i open ur source file, i couldn’t find what actually is label_txt and bg_mc feature..can u help me…

  • @sakura window -> Library or CTRL+L

  • Thanks for your contribution to help AS3 beginners like myself.

    Question: How can I implement a Tooltip with AS3 to work with Photoshop layers imported into Flash CS5.

    Objective: When a mouse is moved over a particular layer => A Tooltip appears with a text.(different text for different layer)

    Can anyone please as soon as possible? It’s for a school project and I’m even willing to donate a few dollars if anyone can implement this for me.

    Thanks

  • @Joe get the example FLA from download. Import graphics from PSD and change the tooltip view from the library. Read the comments. Thx

  • @ Ray – Can you tell me how you got the HTML styling to work in the Tooltip? I got some tags to work, but stuff like etc. don’t seem to work.

  • I see my tags whent missing, I’m trying to get the BOLD html tags to work ‘strong’ etc.

  • Anyway to make the tooltip disappear after a specific time? I find that when used over images, it distracts, and I’d like to hide it after the user has hung over the button for say, 5-10 seconds. I’m having problems figuring that out within this class.

    Thanks, you really did a great job with this, by far the easiest to use I have found!

  • @jbn there is a public “hide()” method. Look in provided example files.
    Thx

  • Very good!

    Only I have a problem. If I try the *. fla file downloaded from the web, everything is correct. However, when I create a new project and import the library, the text seems cut. I do not know you should. For example “ToolTip WITH GREY LABEL” as in the example of the third button, I get “LELABEL” as if taking a last word and transformed. I have added to the project folder “COM” and folder “GS” as well as add the folder “Tooltip” to my library, it contains “Tooltip Symbol”, “Tooltip Arrow”, “Tooltip BG”, “Tooltip. bg.rect. “If I try to change the text to lower case shows nothing at all, appears empty balloon, if I put text in capital letters but other than I get only the first letter. For example, if I put “HELLO”, I get “H”. I tried the library with the *. fla example and it works perfectly, but create my own button does not appear correctly. This is the code for my *. fla file:


    stop();
    /**
    * ...
    * @author Armen Abrahamyan | http://abrahamyan.com | armflash (at) gmail.com
    */
    import com.abrahamyan.liquid.ToolTip;
    var tooltip:ToolTip=ToolTip.getInstance();

    addChild(tooltip)
    stage.scaleMode= StageScaleMode.NO_SCALE;
    stage.align = StageAlign.TOP_LEFT;

    btn1.addEventListener(MouseEvent.MOUSE_OVER,onOver,false,0,true);
    btn1.addEventListener(MouseEvent.MOUSE_OUT,onOut,false,0,true);
    function onOver(e:MouseEvent):void
    {
    switch(e.target.name)
    {
    case "btn1":
    tooltip.followMouse=true;
    tooltip.labelColor=0xff0000;
    tooltip.multiLine=false;
    tooltip.arrowMargin=50;
    tooltip.show("TOOLTIP WITH RED LABEL");
    break;
    }
    }
    function onOut(e:MouseEvent):void
    {
    tooltip.hide();
    }

    And the library is intact, as its downloaded. What caused this problem to display the text? Thank you very much in advance!

  • @Alex check the embeded font, if u dont have the same choose another one and embed.
    Inside tooltip in library, select textfield-> properties panel -> embed

  • I’m pretty green with as3 and I am having real trouble making this work with text input components, any advice.
    Thank you for your efforts.

  • I was curious, is it possible with multiline being able to create “new line” or breaks?

    I would like to have a tool tip that will go to the next line based on the entry.
    Thank you!

Leave a Reply