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.
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

Releated Posts


40 Responses to “ToolTip In AS3”


  1. 1 myrddin

    Nice, I download, maybe i will use it. Thanks.

  2. 2 Hugo

    just one thing when you mouseover on the tip with the red label and go to the others it keeps the red color, it only changes color when you go to the one with the grey color

  3. 3 admin

    @Hugo: That’s because I didn’t change label color to back on all buttons, the same happens with arrow distance. If you download source files u will see that all u need to do is use: tooltip.labelColor = 0×666666 to restore color back.

  4. 4 kanu kukreja

    “unexpected file format” while opening .fla in flash CS3 :(

  5. 5 admin

    @kanu I use CS4 for fla, will include cs3 file as well as soon as I get home :)
    thx

  6. 6 Jack

    When I create a file using the tooltip code it works fine. But when I then load this into my main app via urlrequest, i’m getting a #1009: Cannot access a property or method of a null object reference. Any idea on this?

  7. 7 admin

    @Jack There should be no problem when you load. I have just make quick test loading tooltip inside another swf, works fine for me.
    here is is the simple code for load example inside another swf.
    //————————————————
    stop();
    var loader:Loader = new Loader();
    loader.load(new URLRequest(”tooltip.swf”));
    addChild(loader);
    //————————————————

    I would suggest you to init/add tooltip in you holder swf file, than use it from anywhere.

  8. 8 vir

    Hi, a great work for tooltip.

    I am wondering whether I can use it on Flash CS4 ActionScript3 since I kept getting the error message: WARNING: The component ‘Button’ requires ActionScript 2.0.

    Thank you.

  9. 9 admin

    @vir: zip files contains both cs3 and cs4 .fla files, you need tooltip.fla for cs4, the warning could be related only with the button component in stage to show functionality, u can simply remove that button and use ur own.

  10. 10 Actionman

    AWESOME!

    I’m trying to place the tooltip and am having a hard time.
    I won’t stop until I figure it out but I’m hoping you resond so I can prevent some frustration…lol

    Thanks very much :)

  11. 11 Obiez Devil

    Great Tutorial…It’s very useful…
    Thanx a lot…

  12. 12 FlashNoob

    I have no idea where to start. :( I am a UI developer and typically work with client-side js. Your multi-line tooltip looks like it fits with what I want.

    I am trying to modify an existing flash movie (CS3 with AS3). It dynamically loads movieclip extension “modules” based on a json dataloader which gives the id and the coordinates. I would like to add a tooltip to each of these components where the content is pulled via ajax request and not pre-loaded.

    Any help would be greatly appreciated. :)

  13. 13 admin

    @FlashNoob Well, you can see from the example source file how u can show and hide multiLine tooltip.
    As I understand you have to create functions in main timeline that show and hides tooltip. show function should have parameters of label,x,y position which can be related based on ur ui controls as well, the same way im showing tooltip in example, based on control locations.
    Once you have that functions in main timeline you can call them from javascript.

  14. 14 roy

    Your script was very useful and I appreciate your efforts. Thanks!

  15. 15 admin

    @roy welcome.

  16. 16 FlashNoob

    Thanks so much. I am now handling showing and hiding the tooltip. Initially the tooltip text will be some attribute of the component that is triggering the tooltip. I would then like to make an ajax request to get additional data and when the response is received, replace the text or append to the text the response. Can you point me to a reference that can help me with this portion?

  17. 17 Murat

    works great in tileList component, thank you!

  18. 18 Anwar

    A really nice work. My question is how I can make your tooltip display Arabic? Thanks.

  19. 19 admin

    @Anwar if you open .FLA file, in library you can find Tooltip Symbol, when u open it: the textfield is in top layer(label_txt).
    Set your custom font there and embed characters.

  20. 20 Brad

    When I put the AS3 on my fla the site stops. I have already removed the stop cmd in the AS3. Any idea why it would be stopping?

  21. 21 admin

    @Brad tooltip can’t stop ur main timeline, stop action is related to the class itself not to the main timeline, i guess u have problems with the class path in library.
    Make sure to keep the folder structure and check the tooltip symbol class path in library.
    also make sure to include src folder to the fla files main class path.

    hope that helps

  22. 22 Brad

    it was actually much simpler. I can’t place the AS before I have the button on the screen and the instance name in place.

    I place the AS3 in the first frame and didn’t have the buttons showing up in the 15th frame. So for some reason it stops.

    if I move the AS3 to frame 15 where all my buttons show up with an instance name it all works GREAT.

    not really sure why, but it worked.

  23. 23 Brad

    One last question as I got everything else working. I put most of the AS3 on the first frame and then added the actual

    quote_btn.addEventListener(MouseEvent.MOUSE_OVER,onOver,false,0,true);
    quote_btn.addEventListener(MouseEvent.MOUSE_DOWN,
    quotes_btnMain_P_Handler);function
    quotes_btnMain_P_Handler(event:MouseEvent):void {

    gotoAndPlay(1, “Quotes”);

    }
    quote_btn.addEventListener(MouseEvent.MOUSE_OUT,onOut,false,0,true);

    on my as layer (at the top) on the same frame where the button shows up in the timeline.

    Everything works, but the tooltip shows up behind the buttons.

    Thoughts??

    Thanks so much for all the help. This is the last thing until its all done.

  24. 24 admin

    @Brad u should add tooltip after ur controls, so it will come top on display list, Im about addChild method.

  25. 25 Brad

    Again you are correct. Problem fixed. It is now on top. The only problem I can think of is what if I have some controls then a stop cmd I would have to load the tooltip at that time so it would function, then I have more controls later in the movie and another stop.

    What would I do in this case?? Since I can not load the tooltip after all the controls due to the stop in the timeline?

  26. 26 admin

    @Brad Tooltip is displayobject, just change the depth any time u want,
    if u are adding later another display object u can use swapChildren to swap depths and bring tooltip to front. Or u can use addChildAt(numChildren-2) method to add ur new controls one level down.

    to avoid this situation u could use different holders for controls and for tooltip from start by putting tooltip holder on top. But u have to think that coordinate system is changing here and use relative positioning based on holders in mind :):)

  27. 27 Brad

    ummm did I mention I am new to this LOL I have no idea what you said and when i add the tooltip code more than once I get more errors.

    1151: A conflict exists with definition tooltip in namespace internal.
    1021: Duplicate function definition.
    Warning: 3596: Duplicate variable definition.

    I don’t know how to recall some of this again across scenes … I guess i’m in over my head.

  28. 28 Brad

    ignore the other errors I got it working across scenes.

  29. 29 Alex

    I’m brand new at Flash programming and I find this tooltip to be really cool.

    But when I try to use the tooltip in my project I get errors regarding the label_txt and bg_mc objects. Where are these object declared? When I run the code provided it works fine. What am I not seeing?

    Thanks

  30. 30 admin

    @Alex make sure u move library items from example to your FLA file’s library

  31. 31 Alex

    Wow. Thank you very much.

  32. 32 jsaagerbier

    Where can I get the example of tooltip, I have searched buy no luck.
    Thank you very much.

  33. 33 admin

    @jsaagerbier download source files link is located under ToolTip.as block source file.
    http://abrahamyan.com/wp-content/uploads/2009/tooltip/tooltip.zip

  34. 34 JAJ

    This a wonderful tooltip. I have it working fine when I use it like your example .fla file. (In that example, the timeline contains all of the event listeners, etc.)
    I have troubles when I implement this from a class, though.

    I have a class that handles all of my event listeners for my roll over areas that use your tooltip. I have this on frame 1 of the timeline:

    stop();
    var tooltip:ToolTip=ToolTip.getInstance();
    addChild(tooltip)
    stage.scaleMode= StageScaleMode.NO_SCALE;
    stage.align = StageAlign.TOP_LEFT;

    But when I try to call the tooltip methods from one of my class’s methods I get ‘Access of undefined property tooltip.’

    The function that calls the tooltip looks like this:

    function mouseOverListener(evt:MouseEvent):void {
    tooltip.followMouse=true;
    tooltip.fixedWidth=150;
    tooltip.multiLine=true;
    tooltip.show(”Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut sodales placerat ligula. Proin elementum, ante vel consectetur pharetra”); ;

    }//end mouseOverListener

    Please help. Its the best tooltip out there and I want to get it to work from my class.

    Thanks!

  35. 35 admin

    @JAJ
    thx for the kind words.
    from what u wrote:
    u have: var tooltip:ToolTip=ToolTip.getInstance(); -in main timeline, but u don’t have it inside ur castom class.

    try to add tooltip as private var inisde ur custom class:
    private var tooltip:ToolTip=ToolTip.getInstance();

    as its singleton, it will refer to the same class instance as u have in root, should work.

  36. 36 JAJ

    Awesome. Works well. Thanks!
    When you say ‘root’ you mean the timeline?
    (I am very new to Flash and AS3.)

  37. 37 admin

    @JAJ , y, I mean the main timeline(old school), glad that it get fixed.

  38. 38 Andy

    hello Armen,

    Thanks for sharing your code, time, and efforts. I’ve been searching for a nice tooltip but without avail. Yours finally came along and saved my hair pulling!

    Your tutorial and code are easy and results sleek looking. Keep up the great work!

  39. 39 admin

    @Andy Thx, glad that it worked for u.

  40. 40 Andy

    hello Armin,

    Your tooltip works perfect and displays nicely. My only question: is there a way to make the font display different colors or sizes? I tried to add “private var label_txt:Boolean = true;” and “label_txt.htmlText = true;” but it keeps throwing errors.

    I also changed the properties of label_txt to render html in the Properties tab.

    Any suggestions?

    Thanks in advance!

Leave a Reply