Create a Customizable Tooltip in ActionScript 3.0

A Tooltip is a graphical user interface element. It activates by hovering or rolling over an item, showing a box of text which displays information about that item.

In this tut, I’ll show you how to create an easily customizable tooltip using Classes in ActionScript 3.0. Take a look!

Step 1: Brief Overview

A Tooltip class will be created to handle the drawing of the tooltip, a Main class will handle the corresponding events and it will be displayed by rolling over a Button or MovieClip on the Stage.

Step 2: Starting

Open Flash and create a new Flash File (ActionScript 3).

Set the stage size to 600×300 and create a gray radial background (#F9FAF5, #E3E5E0).

””

Step 3: The Button

Select the Rectangle Primitive Tool and create a 140×40px blue (#7B90A5) rounded rectangle. Set 10 as corner radius and add some text to make it seem more like a button.

Convert it to a MovieClip or Button and name it "button". Open the properties panel and add the following filter:

You’ll end up with something like this:

Step 4: ActionScript!

Save your work and be ready for some coding.

Create a new ActionScript File and save it as Tooltip.as

Step 5: Required Classes

These are the classes we’ll need. For extended information about every class please refer to the flash help.

package classes
{
	import flash.display.Sprite;
	import flash.text.TextField;
	import flash.text.TextFormat;
	import flash.text.TextFormatAlign;
	import flash.filters.BitmapFilter;
	import flash.filters.DropShadowFilter;
	import fl.transitions.Tween;
	import fl.transitions.easing.Strong;

Step 6: Extending the Class

We extend using the Sprite class to get access to DisplayObject related functions.

public class Tooltip extends Sprite
{

Step 7: Variables

These are the variables we will use, explained in the comments.

var tween:Tween; //A tween object to animate the tooltip at start

var tooltip:Sprite = new Sprite(); //The Sprite containing the tooltip graphics
var bmpFilter:BitmapFilter; //This will handle the drop shadow filter

var textfield:TextField = new TextField(); //The textfield inside the tooltip
var textformat:TextFormat = new TextFormat(); //The format for the textfield
var font:Harmony = new Harmony(); An embedded font

Step 8: Constructor Function

This function is executed when the class is loaded, the parameters are almost all descriptive. The useArrow paramenter will draw a little arrow in the tooltip but it will just work if the direction is Up or Down. We’ll see more about that later in the code.

public function Tooltip(w:int, h:int, cornerRadius:int, txt:String, color:uint, txtColor:uint, alfa:Number, useArrow:Boolean, dir:String, dist:int):void
{

Step 9: Text Properties

These lines will set the TextField and TextFormat properties.

textfield.selectable = false; //You cannot select the text in the tooltip

textformat.align = TextFormatAlign.CENTER; //Center alignment
textformat.font = font.fontName; //Use the embedded font
textformat.size = 8; //Size of the font

textformat.color = txtColor; //Color of the text, taken from the parameters

textfield = new TextField(); //A new TextField object
textfield.embedFonts = true; //Specify the embedding of fonts
textfield.width = w;
textfield.height = h;
textfield.defaultTextFormat = textformat; //Apply the format
textfield.text = txt; //The content of the TextField, taken from the parameters

Step 10: Creating the Tooltip

This code will draw the tooltip according to the values of the parameters.

tooltip = new Sprite();

tooltip.graphics.beginFill(color, alfa);
tooltip.graphics.drawRoundRect(0, 0, w, h, cornerRadius, cornerRadius);

Step 11: Arrow Parameter

The useArrow parameter will draw a triangle in the center-top or center-bottom of the tooltip, notice that this will work only if the "dir" parameter is set to Up or Down.

if (useArrow && dir == "up")
{
	tooltip.graphics.moveTo(tooltip.width / 2 - 6, tooltip.height);
	tooltip.graphics.lineTo(tooltip.width / 2, tooltip.height + 4.5);
	tooltip.graphics.lineTo(tooltip.width / 2 + 6, tooltip.height - 4.5);
}

if (useArrow && dir == "down")
{
	tooltip.graphics.moveTo(tooltip.width / 2 - 6, 0);
	tooltip.graphics.lineTo(tooltip.width / 2, -4.5);
	tooltip.graphics.lineTo(tooltip.width / 2 + 6, 0);
}

tooltip.graphics.endFill(); // This line will finish the drawing no matter if the arrow is used or not.

Step 12: Drop Shadow Filter

This code applies a Drop Shadow Filter based in the color of the tooltip.

bmpFilter = new DropShadowFilter(1,90,color,1,2,2,1,15);

tooltip.filters = [bmpFilter];

Step 13: Add Tooltip to Stage

tooltip.addChild(textfield); //Adds the TextField to the Tooltip Sprite

addChild(tooltip); //Adds the Tooltip to Stage

Step 14: Animating

This line will create a short tween animation using the alpha property of the tooltip.

tween = new Tween(tooltip,"alpha",Strong.easeOut,0,tooltip.alpha,1,true);

Step 15: Main Class

Save your Tooltip class and create a new ActionScript File, this file will be the Main Class which will handle the Events to show the Tooltip when you roll over the button.

Save this class as Main.as

Step 16: Neccessary Classes

The neccessary classes for this file:

package classes
{
	import classes.Tooltip; //Be sure to import your Tooltip Class!
	import flash.display.Sprite;
	import flash.utils.Timer;
	import flash.events.MouseEvent;
	import flash.events.TimerEvent;

Step 17: Extending the Class

Extend using the Sprite class to get access to DisplayObject related functions.

public class Main extends Sprite
{

Step 18: Variables

The variables we’ll use in this class.

var timer:Timer = new Timer(500, 1); //A Timer that will execute 500 miliseconds after the roll over, just one time
var tooltip:Tooltip; //A Tooltip object

var dir:String = "up"; //The direction of the tooltip
var dist:int = 10; //Distance of the tooltip, in pixels

Step 19: Main Function

This function is the constructor, it will be run as soon as the class is called.

public function Main():void
{
	addListeners(); //This function adds all the necesary listeners, will be created later
}

Step 20: Tooltip Countdown

This function will run when the user rolls over the button, it will start the timer to count 500 millisecons before calling the function that will show the Tooltip.

private function startTooltipCounter(e:MouseEvent):void
{
	timer.addEventListener(TimerEvent.TIMER_COMPLETE, showTooltip);
	timer.start();
}

Step 21: Show Tooltip Function

Creates the Tooltip according to the parameters and places it in the chosen direction. It also adds the tooltip to the Stage and creates a Mouse Move listener.

private function showTooltip(e:TimerEvent):void
		{
			timer.removeEventListener(TimerEvent.TIMER_COMPLETE, showTooltip);

			tooltip = new Tooltip(80, 20, 10, "FlashTuts+", 0x222222, 0xFFFFFF, 0.5, true, dir, dist); //Using the Tooltip Class

			/* Start Position, based in the dir parameter */

			switch (dir)
			{
				case "up" :
					tooltip.x = mouseX - tooltip.width / 2;
					tooltip.y = mouseY - (tooltip.height + dist);
					break;
				case "down" :
					tooltip.x = mouseX - tooltip.width / 2;
					tooltip.y = mouseY + (tooltip.height + dist);
					break;
				case "left" :
					tooltip.x = mouseX - tooltip.width - dist;
					tooltip.y = mouseY - (tooltip.height / 2);
					break;
				case "right" :
					tooltip.x = mouseX + dist;
					tooltip.y = mouseY - (tooltip.height / 2);
					break;
			}

			/* Add tooltip to stage and add move listener */

			addChild(tooltip);

			button.addEventListener(MouseEvent.MOUSE_MOVE, moveTooltip);
		}

Step 22: Tooltip Movement

This code will move the tooltip based on the dist paramenter and the mouse position.

private function moveTooltip(e:MouseEvent):void
{
	switch (dir)
	{
		case "up" :
			tooltip.x = mouseX - tooltip.width / 2;
			tooltip.y = mouseY - (tooltip.height + dist);
			break;
		case "down" :
			tooltip.x = mouseX - tooltip.width / 2;
			tooltip.y = mouseY + (tooltip.height + dist);
			break;
		case "left" :
			tooltip.x = mouseX - tooltip.width - dist;
			tooltip.y = mouseY - (tooltip.height / 2);
			break;
		case "right" :
			tooltip.x = mouseX + dist;
			tooltip.y = mouseY - (tooltip.height / 2);
			break;
	}
}

Step 23: Hide Tooltip

This is a function that will remove the Tooltip when the mouse cursor is no longer within the target, in this case the button.

private function hideTooltip(e:MouseEvent):void
{
	/* Checks if the timer is already executed, if not, it means the mouse just passed through the button, but didn't stayed */

	if (timer.currentCount == 1)
	{
		removeChild(tooltip);
	}

	timer.reset(); //Resets the timer
}

Step 24: Listeners

This is a function to add the listeners at a time, executed in the Main function.

private function addListeners():void
{
	/* "button" is the instance name of our target */

	button.addEventListener(MouseEvent.MOUSE_OVER, startTooltipCounter);
	button.addEventListener(MouseEvent.MOUSE_OUT, hideTooltip);
}

Step 25: Document Class

Go back to the Fla and in the Properties Panel, Class textfield add "classes.Main". This will link the Main class as the Document Class.

Test your Tooltip!

Conclusion

You have created a highly customizable Tooltip in ActionScript 3 Classes, now it’s time to see the customization part. The following are just a few examples of how many possibilities you have:

Thanks for reading!

Related Posts

Add Comment

Discussion 31 Comments

  1. Alexander says:

    Great post, thanks!

  2. Diego SA says:

    Hmmm, this is beautiful! Loved the font you used to write the tooltip content! What is the font’s name?

  3. Erick says:

    You are a hard worker Che. Keep up the good work, and it will pay off in the future!

  4. Great!! Simple but effective.

  5. André says:

    Wow, it´s a very smart solution for tooltips, thanks for sharing this one!! it can be transformed into a component and used any time anywhere, thanks a lot!!

  6. Franky says:

    Well done sir, as usual!!!

    @popjunkyinc

  7. Waseem says:

    great tutorial , I will start looking at ActionScript
    Thanks

  8. plaaat says:

    been wanting to make something small and reusable like this for a while, thanks! will be trying it out later :)

  9. Kris says:

    Nce one … maby i’ll use it … who knows …

  10. Ben Entwisle says:

    ….on second thoughts, i like the effect but not the need for so much code in the main.as.
    Im going to re-jig it so that i only need to instantiate the class and then addChild.

    Also i think its more usable to use textfield.textWidth / Height so you don’t have to bother with knowing the pixel dimensions of the text string.
    Will post and link to the .as file when im done if anyone says they are interested.

    Ben

  11. earthflyer says:

    Nice tutorial Carlos

    Like the way to explain some of these sections, I have a better understaning how AS3 is working in your tutorial.

    earthflyer

  12. guest says:

    I get this error:

    1046: Type was not found or was not a compile-time constant: MovieClip.

  13. Gustavo Caetano says:

    I want to target MCs inside another MC.

    I already tried to put

    this.a_mc.b_mc.addEventListener(MouseEvent.MOUSE_OVER, startTooltipCounter);

    or

    a_mc.b_mc.addEventListener(MouseEvent.MOUSE_OVER, startTooltipCounter);

    but it won’t work.

    What am I doing wrong?

  14. Shane says:

    Hey, i got this error, tried changing it to a different font but did not make a difference…what can i do to remedy the situation –

    1046: Type was not found or was not a compile-time constant: Harmony.

  15. Interesting and useful tutorial. Thanks for sharing this!

  16. Maynframe says:

    dont work with buttons,
    5000: The class ‘classes.Main’ must subclass ‘flash.display.SimpleButton’ since it is linked to a library symbol of that type.

  17. Diego says:

    Hello!

    How i insert an “STOP ();” ?????????

  18. Hi Friends,
    thks for share it is a great work :

    @Ben Entwisle :
    you’re right it is better to use textWidth propretie, in the tooltip Class I edited that part to have a sizable text :


    textfield.text = txt;

    if (textfield.textWidth > w )
    {
    w = textfield.textWidth + 10;
    textfield.width = w;
    }
    else textfield.width = w;

    /* Create tooltip */
    ….

    Another point it is the parent for the tooltip, I’m using somes mask so my tooltip are cuts some time, so I prefered to add it in my stage and use stage.mouseX :


    case “up” :
    tooltip.x = stage.mouseX – tooltip.width / 2;
    tooltip.y = stage.mouseY – (tooltip.height + dist);
    break;

    stage.addChild(tooltip);

    and remove it ofcourse : stage.removeChild(tooltip);

    realy nice work thks

    muy buen trabajo Carlos Salud !

  19. Roy says:

    I have more then one button how can I add more tooltips?

  20. Anne says:

    I’ve also run into some issues with using more than one button. Any suggestions?

  21. Reck says:

    can I add more tooltips to more button ?

  22. Vasjen Katro says:

    Nice one! but i would say you cand o this in jquery easier than here!

  23. Adarsh Kumar Khare says:

    I tried whatever you posted, but it did not work. I was asking for compiled movie clip. If I convert the button into compiled clip, it starts working.

    Please let me whether I am doing wrong or you are missing something.

  24. Navid says:

    thanks for your sharing, but how can I use this tooptip for more buttons.
    for example I have 5 buttons in stage, and I want to add different tooltips to them. what should I do?

  25. navid says:

    I want to use Unicode to write in my own language. but it’s not working. Is there any way to write in another language?
    1.using unicode
    2.Right To Left

    how can I change RTL ot LTR ?

  26. felisan says:

    This tutorial is quite nice, but also lead way for some obvious questions..
    As Ben Entwisle and Reda MAkhchan both mention, the tooltip can dynamically change size (both vertically and horizontally) by adding these lines of code:

    if (textfield.textWidth > w ) {
    w = textfield.textWidth + 10;
    textfield.width = w;
    } else {
    textfield.width = w;
    }

    if (textfield.textHeight > h ) {
    h = textfield.textHeight + 6;
    textfield.height = h;
    } else {
    textfield.height = h;
    }

    after this line of code: textfield.text = txt; in the Tooltip.as file.

    So far so good.
    But when having created the tooltip, it makes no sense, that the tooltip cannot adjust size and text depending on which button it interacts with.

    Anyone with a solution to this?
    Or just an idea on how to extend this class to suit these obvious needs.. I’d be happy to give it a go, then..

Add a Comment