Menu

Create a Nice, Lightweight JavaScript Tooltip

Editor’s note: This tutorial was written by Michael Leigeber, a web designer and .NET developer who runs the Leigeber Web Development Blog – a blog that’s setting the blogging community buzzing with his beautiful, lightweight JavaScript solutions.

Tooltip - demo

View the JavaScript Tooltip demonstration.

Introduction

To begin, create the 3 files needed for this tutorial (index.html, style.css and script.js) and include the stylesheet and the script from index.html. To make things easy the starter files are available by clicking here.

The most important things to remember when writing JavaScript are to keep the code simple and to script logically. The first thing that needs to be established is precisely what you would like the script to accomplish. Based on the desired functionality it then helps to create a diagram or flow description for any complex script before you get into the code. Doing so can help streamline the logic and keep the script clean.

What we are trying to accomplish…

Create a lightweight script that fades a tooltip with rounded corners in relation to the cursor position.

How does the script need to flow…

  1. Setup the namespace and global variables.
  2. Create a function to display the tooltip that takes two variables, the string to display and an optional width integer.
  3. When the function is called build the tooltip markup if it does not exist and register an onmousemove listener to position the tooltip. Insert the tooltip content into the tooltip and call a function to incrementally fade the tooltip to the target opacity.
  4. On the mouseout event of a “hotspot” reference a function that calls the fade function to incrementally hide the tooltip.

Let’s begin by setting up the JavaScript file. We want to create a namespace to encapsulate the functionality of our script. By doing so, we virtually eliminate the possibility of a conflict with some other script or framework.

var tooltip(){
	return{};
}();

Next, we need to add any variables we want to include on the global level of the namespace. By setting these variables globally we can access them in any of the child functions and quickly change them without sorting through the code.

 var id = 'tt';
 var top = 3;
 var left = 3;
 var maxw = 300;
 var speed = 10;
 var timer = 20;
 var endalpha = 95;
 var alpha = 0;
 var tt,t,c,b,h;
 var ie = document.all ? true : false;

We need to determine how we want the tooltip to look so we can figure out how to build out the elements to add to the DOM… a rectangle with rounded corners on the top and right corners only. To accomplish this we need a wrapper div and then three nested divs. We can style the divs with the CSS. The markup should look something like this once generated.

<div id="tt">
	<div id="tttop"> </div>
	<div id="ttcont"> </div>
	<div id="ttbot"> </div>
</div>

The first function we will name ‘show’ and it will be accessible by calling tooltip.show(). It will need to take two parameters… the content string and an optional width integer. To begin, it will need to check and see if the tooltip has been added to the DOM yet. If it does not exist the divs need to be built and added to the body. Either way the innerHTML of the contentdiv will need to be set to the content parameter, the height and width set and the fade function set to a timer.

show:function(v,w){
if(tt == null){
 tt  = document.createElement('div');
 tt.setAttribute('id',id);
 t  = document.createElement('div');
 t.setAttribute('id',id  + 'top');
 c  = document.createElement('div');
 c.setAttribute('id',id  + 'cont');
 b  = document.createElement('div');
 b.setAttribute('id',id  + 'bot');
 tt.appendChild(t);
 tt.appendChild(c);
 tt.appendChild(b);
 document.body.appendChild(tt);
 tt.style.opacity  = 0;
 tt.style.filter  = 'alpha(opacity=0)';
 document.onmousemove  = this.pos;
}
tt.style.display  = 'block';
c.innerHTML =  v;
tt.style.width  = w ? w + 'px' : 'auto';

if(!w  && ie){
 t.style.display  = 'none';
 b.style.display  = 'none';
 tt.style.width  = tt.offsetWidth;
 t.style.display  = 'block';
 b.style.display  = 'block';
}

if(tt.offsetWidth  > maxw){tt.style.width = maxw + 'px'}

h =  parseInt(tt.offsetHeight) + top;
clearInterval(tt.timer);
tt.timer =  setInterval(function(){tooltip.fade(1)},timer);
},

The next function we need is the position function that will set the top and left values of the tooltip as the cursor moves. First we calculate the position based on the browser and then we set the values taking into consideration the global offset variables.

pos:function(e){
 var u = ie ? event.clientY + document.documentElement.scrollTop : e.pageY;
 var l = ie ? event.clientX + document.documentElement.scrollLeft : e.pageX;
 tt.style.top = (u - height) + 'px';
 tt.style.left = (l + left) + 'px';
}, 

Next we need to create a function that will fade the tooltip from its current opacity to the target opacity based on the direction variable that is passed to it.

fade:function(d){
 var a = alpha;
 if((a !=  endalpha && d == 1) || (a != 0 && d == -1)){
   var  i = speed;
   if(endalpha  - a < speed && d == 1){
      i  = endalpha - a;
   } else  if(alpha < speed && d == -1){
      i  = a;
  }
  alpha  = a + (i * d);
  tt.style.opacity  = alpha * .01;
  tt.style.filter  = 'alpha(opacity=' + alpha + ')';
   }else{
     clearInterval(tt.timer);
     if(d  == -1){
     tt.style.display  = 'none';
  }
 }
},

Finally the function to hide the tooltip onmouseout.

hide:function(){
	clearInterval(tt.timer);
	tt.timer = setInterval(function(){tooltip.fade(-1)},timer);
}

That completes the JavaScript. We are left with a 2kb script that is compatible with IE6, IE7, Firefox, Opera and Safari.

Here is the full script

var tooltip=function(){
 var id = 'tt';
 var top = 3;
 var left = 3;
 var maxw = 300;
 var speed = 10;
 var timer = 20;
 var endalpha = 95;
 var alpha = 0;
 var tt,t,c,b,h;
 var ie = document.all ? true : false;
 return{
  show:function(v,w){
   if(tt == null){
    tt = document.createElement('div');
    tt.setAttribute('id',id);
    t = document.createElement('div');
    t.setAttribute('id',id + 'top');
    c = document.createElement('div');
    c.setAttribute('id',id + 'cont');
    b = document.createElement('div');
    b.setAttribute('id',id + 'bot');
    tt.appendChild(t);
    tt.appendChild(c);
    tt.appendChild(b);
    document.body.appendChild(tt);
    tt.style.opacity = 0;
    tt.style.filter = 'alpha(opacity=0)';
    document.onmousemove = this.pos;
   }
   tt.style.display = 'block';
   c.innerHTML = v;
   tt.style.width = w ? w + 'px' : 'auto';
   if(!w && ie){
    t.style.display = 'none';
    b.style.display = 'none';
    tt.style.width = tt.offsetWidth;
    t.style.display = 'block';
    b.style.display = 'block';
   }
  if(tt.offsetWidth > maxw){tt.style.width = maxw + 'px'}
  h = parseInt(tt.offsetHeight) + top;
  clearInterval(tt.timer);
  tt.timer = setInterval(function(){tooltip.fade(1)},timer);
  },
  pos:function(e){
   var u = ie ? event.clientY + document.documentElement.scrollTop : e.pageY;
   var l = ie ? event.clientX + document.documentElement.scrollLeft : e.pageX;
   tt.style.top = (u - h) + 'px';
   tt.style.left = (l + left) + 'px';
  },
  fade:function(d){
   var a = alpha;
   if((a != endalpha && d == 1) || (a != 0 && d == -1)){
    var i = speed;
   if(endalpha - a < speed && d == 1){
    i = endalpha - a;
   }else if(alpha < speed && d == -1){
     i = a;
   }
   alpha = a + (i * d);
   tt.style.opacity = alpha * .01;
   tt.style.filter = 'alpha(opacity=' + alpha + ')';
  }else{
    clearInterval(tt.timer);
     if(d == -1){tt.style.display = 'none'}
  }
 },
 hide:function(){
  clearInterval(tt.timer);
   tt.timer = setInterval(function(){tooltip.fade(-1)},timer);
  }
 };
}();

Now on to the CSS for the tooltip which is completely customizable to match any interface.

#tt {
 position:absolute;
 display:block;
 background:url(images/tt_left.gif) top left no-repeat;
 }
 #tttop {
 display:block;
 height:5px;
 margin-left:5px;
 background:url(images/tt_top.gif) top right no-repeat;
 overflow:hidden;
 }
 #ttcont {
 display:block;
 padding:2px 12px 3px 7px;
 margin-left:5px;
 background:#666;
 color:#fff;
 }
#ttbot {
display:block;
height:5px; 
margin-left:5px;  
background:url(images/tt_bottom.gif) top right no-repeat; 
overflow:hidden;
}

To build and hide a tooltip call the script as below. The second parameter in the show function is optional, if not passed the width will automatically adjust to the content within the maxh limit.

onmouseover="tooltip.show('Testing  123 ', 200);"
onmouseout="tooltip.hide();"

If you run into any issues with this script or have any questions don’t hesitate to contact me at my blog's contact form.

Downloads

If you liked this tutorial, make sure to check out the Leigeber Web Development Blog. Stay up-to-date with his stuff by subscribing to his RSS feed.

This was published on Jun 4, 2008

202 Comments

very nice

This is great. I’d been looking for something similar. Thanks again for great posts.

Very nice, I do find myself wondering why though? Why “reinvent the wheel” when there’s already several premade libraries that do this for you. Mootools has a really nice, simple tooltip system built in to it already. All in all though… Good Job, keep up the good work.

Jacob Gube Jun 04 2008

@Sean: That’s an excellent comment, and a valid point – and one which many people are probably thinking of as well.

There are indeed a huge selection of frameworks and libraries available that does tool tips, but the key here is that it’s lightweight.

Let’s take for example, jQuery, which at its compressed state is around 30KB 16KB (for Gzip’ed + minified as of v 1.2.6). Including jQuery and a plugin (or your own script), just for tooltip functionality is quite excessive. If you’re to use jQuery for other things such as handling Ajax requests and events, creating complicated chained effects, and as the backbone of your web application’s end user interface, then the 30KB 16KB is nothing.

Additionally, though this tutorial provides a working, downloadable example of a tooltip script – it’s more a tutorial on JavaScript – to give you inspiration for your own scripts. Some of the concepts covered include working with opacity and alpha, conditionals for different web browsers, and how to write clean and logical code.

Hi Jacob! This is a great tooltip thank you for making this. I was wondering if it might be possible to add a delay for tooltips coming up?

Nice tut Jacob. Would it be possible to expand on this in a future post to describe how to make interactive tooltips (a la Netflix)?

Really nice script

thnks nice tut

Jacob Gube Jun 05 2008

@Mike: Thanks for the compliments, but this wonderful script was contributed by Michael Leigeber of the Leigeber Web Development Blog, so make sure to send him a shout-out.

To answer your question, you can tweak the script’s behavior by playing around with the variables such as speed, timer, alpha, etc. but to achieve your particular change, first look for the hide function, it should look like this:

 hide:function(){
  clearInterval(tt.timer);
   tt.timer = setInterval(function(){tooltip.fade(-1)},timer);
  }

in the last line: modify the timer to an integer… try something like 400, or 500. like this:

 hide:function(){
  clearInterval(tt.timer);
   tt.timer = setInterval(function(){tooltip.fade(-1)},400);
  }

once you’re satisfied, to keep your code clean, declare a variable on top, something like:

var hideDelay = 400;

and then change the value of:

tt.timer = setInterval(function(){tooltip.fade(-1)},timer);

to

tt.timer = setInterval(function(){tooltip.fade(-1)}, hideDelay);

Let me know if you encounter any trouble or need further help – feel free to shoot me an email.

@Ed: That’s a great suggestion! if I see enough requests, I may do a tutorial on a Netflix-style interactive tooltip using jQuery.

Has anyone else noticed that fox news has started to use this type of ad on their website on certain keywords. That seems so spamish on such a “mainstream” news site. Oh well, the old media is failing.

Real Estate Graphic Design Jun 12 2008

Love the fade in, beautiful work.

The visual effect is really great. Thanks.

Devanathan Chandran Jun 23 2008

This tooltip effect is really very good.
Thanks

Gustavo Arcila Jun 24 2008

Great Script, very simple and useful, perfect for people (like me) who hates frameworks (mootols, prototype, etc), resuming … Very good Job, Thank you

choi reyes Jul 10 2008

hi, i’m just wondering if your tooltip application apply the same functionality if the scroll of the screen enables.
Im trying on my application but it seems the tooltip stays in the upper portion of the screen if I scroll down.
Please Help. Need advice. Thanks.

Jacob Gube Jul 10 2008

@choi reyes: Got an live example we can check out to better see the issue?

thank you nice application

Stephen Jul 27 2008

This script is great! Like you said, there isn’t a lightweight choice if you only want a tooltip. The only question I have is how do you make t display underneath the cursor instead of above?

Excellent script, does exactly what it’s supposed to do. Nothing more, nothing less.

Simply, beautiful.

hey Jacob, love the script and the tutorial, very elegant and performs great! I’m just starting to stumble my way into the world of JS and played around with certain variables that I thought might achieve this unseccesfully, but…

how might I got about making it so that after initially opening the tooltip would remain static in that position until the cursor moved off the object? is that possible?

thanks, and either way I love it!

Very very nice script, thanks for the script…

couple o questions”: how come in IE it causes the windows timer-icon to flicker on and off as if it is loading something constantly as you move your mouse around the page? also is there a way to delay it one second, as in, dont have the tooltip unless some one rests their mouse over the desired text? Thanks!

Rebecca Aug 04 2008

Looks great! Is there a way to allow users to globally turn on and off the appearance of the tooltips?

Very nice, but maybe I found a bug in IE6: if you scroll the page when you are on a tooltip, the box won’t scroll with the page and it’ll stay far away from the cursor. This is not the case in FF.
You can see it here

very nice work.. but one question..

at the moment i think the “x-y 0 point” is at the bottom left..

what do i have to change to make the top left of the tooltip the 0-point?

greetings

sorry for asking, got it on my own.. simple mathematics :D

replaced

tt.style.top = (u – h) + ‘px';
tt.style.left = (l + left) + ‘px';

by that

tt.style.top = (u + top) + ‘px';
tt.style.left = (l + left) + ‘px';

if anyone else is interested.

ehcomunicacion Aug 18 2008

Very nice effect.

lamaster Aug 20 2008

Cool, but some buggy in ue6 :(

Karthik Murugan Aug 22 2008

Jacob,

I’ve got a live example that reveals the issues in IE while scrolling. Check it out at http://www.yemkay.com/share/tooltip/out.html. The tooltip remains in the upper portion even when we scroll down or right. It works well in Firefox though.

Thanks for a light weight tooltip function.

NickWong Aug 22 2008

Hello All,
I fixed this for IE6, so thought I would share.

To make it work in IE6, change the pos function as follows:

pos:function(e){
// For IE6 compatibity – nick 22/08/2008 11:32
var u = 0, l = 0;
if( typeof( window.pageYOffset ) == ‘number’ ) {
//Netscape compliant
u = window.pageYOffset;
l = window.pageXOffset;
} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
//DOM compliant
u = document.body.scrollTop;
l = document.body.scrollLeft;
} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
//IE6 standards compliant mode
u = document.documentElement.scrollTop;
l = document.documentElement.scrollLeft;
}

u = ie ? event.clientY + u : e.pageY;
l = ie ? event.clientX + l : e.pageX;
tt.style.top = (u – h) + ‘px';
tt.style.left = (l + left) + ‘px';
}

Cheers
Nick

this is very cool effect, great job.. keep up the good work!!!!

I’m sorry, but it seems to me that the solution proposed by NickWong doesn’t work at all.
I tried to do the change, but IE says “tooltip not defined”, and also in FF the tooltip disappears.
I noticed that there’s no comma at the end of the function(e) proposed, but adding it in unuseful.
Ah, and the scroll bug appears in IE7, too…

Maybe I found: simply, copying the code the apostrophe becomes high comma in ‘px’ and ‘number’.
After the substitution, everything works!

Hi,
I’m trying to use it
and I this problem.

The tooltip goes over the right page limit not flip horizontally if the px on the right are less the “tt” width.

Someone have found and solved this bug ?

Jacob-

Great small script. To Mike’s request, is it possible to build in a delay so the tooltip doesn’t appear immediately. I’d like to use this on a the main nav, per my client’s request (I convinced them to abbreviate names of business units in main navigation, but promised to have full names appear in tooltip form). Thanks.

Can you please help me on how can i insert a balloon image in the script to have a balloon tooltip that fades.

Michael,

Thanks for this great effect. It took me 5 mins to read, install and see it work. Excellent having the demo site.

The only thing I would change is having a selector for ‘body’ in your CSS. Most sites would already have their own. So I removed this, changed the relative reference for the images and voila it all worked perfectly.

By the way I am using Firefox 3 as my target browser

Thanks again

peet…

I have an answer and a question:

kevin asked a question at the end of July that I don’t believe was answered. The flickering is caused by the images referenced in the CSS not being present. If you remove the background statements from the CSS or add the images to your site, the flickering should go away.

Now my question:

Very nice tutorial & script. It plugged in very nicely to my application, however in my case I am trying to programmatically add the tooltip to certain images on my page via Javascript a la:

myImg.onmouseover=function() { tooltip.show(‘Solved by ‘+solver); };

where myImg is some image on my page (changes each time this line is called) and solver is a variable that I set to a potentially different value each time this code is executed (on a different image).

What I end up with is the same (last) value of solver on the tooltip for all images. I believe this is because solver is not being evaluated when I am setting the onmouseover function, but rather deferred until the mouseover actually occurs, at which time solver has taken on a new value.

I keep getting myself twisted up in knots because I can’t seem to get anything unique into that line of my code that is evaluated at that time. Any suggestions?

Thanks,
…Lance

Thank you for this great article and piece of code. Really simple and concise yet very good result!
A couple of suggestions:
a) place the main div at top of the page when creating it because if it is in a container with fixed size it will create a scroll bar briefly (until moved to place).
b) in slow computers (like mine) it shows in the position created before moved to place, so make it invisible until positioned.
The above can be achieved by css properties: top:0; left:0; display:none; or by code when creating it.
Thank you again for your time and effort.
kostas

matthew fedak Nov 03 2008

Thankyou this was really easy to follow, a lot simpler than scriptaculous or jquery examples.

I do see the need for this. I have to integrate this into the “Source” section of a CMS without stylesheet or js linking in the head. It has to happen in the content area. I’d rather use this standalone than with file import dependencies.

Thanks. Very nice looking.

It is nice indeed but using specific class and putting the actual javascript code (onmouseover & onmouseout) is not an ideal design. Visitors that view the website with their javascript disabled will not see the tooltip at all.

Is there anyway to change this to be positioned and styled at the bottom right of the mouse?

Michael Nov 20 2008

Very nice script. I discovered and fixed the scrolling problem before I realised there were these comments at the bottom and there was a fix already.

Anyway, there is a problem with and in IE6. IE7 and Firefox are fine. The pop-up div goes behind select dropdowns when it should be on top in IE6. Z-index does not solve the problem. I have searched the web and find iframe can be used as a fix and I am currently making the change. Has anyone done this already?

laurent Nov 21 2008

Hi, very nice script, thanks for this.
it works very well on ie6 7 , 8 ff 2, 3 for me :-)

i just want to put the font-size of the text inside the bullet bigger how could i do ? thanks take care

Laurent Paris France

Jacob Gube Nov 21 2008

I’ll update the article really soon with answers to your questions for everyone.

Janckos Nov 27 2008

Espero el articulo actualizado pronto =D
gracias!!!

this is perfect, thanks!

Jacob Gube

November 21st, 2008

I’ll update the article really soon with answers to your questions for everyone.

Please update…

Jacob Gube Jan 30 2009

@Ozgur: Wow, I’m sorry for neglecting this post. I’ll work through these questions and answer them soon. Did you need a particular question answered?

Garrett Feb 06 2009

Very nice, thanks a lot!

Nguyen Thuan Feb 11 2009

Hi Jacop, your script is very nice but have a small problem when load images and text. This is my fix:

In your css tooltip, replace:

#ttcont {
display:block;
padding:2px 12px 3px 7px;
margin-left:5px;
background:#666;
color:#fff;
}

with:

#ttcont {
float: left;
display:block;
padding:2px 12px 3px 7px;
margin-left:5px;
background:#666;
color:#fff;
}

You done! Sorry, my English is poor, but I’m thankyou very much for your nice script.

Jacob Gube Feb 12 2009

@Nguyen Thuan: Cool, so just add float: left;? Thanks for sharing. Great job!

Alan Reiley Feb 17 2009

Hi,

I would like to see Michaels problem, with the tooltips hiding under drop-downs in IE, answered. We are also encountering this issue as well.

Thanks,
Alan

Michaels Post:
“Very nice script. I discovered and fixed the scrolling problem before I realised there were these comments at the bottom and there was a fix already.

Anyway, there is a problem with and in IE6. IE7 and Firefox are fine. The pop-up div goes behind select dropdowns when it should be on top in IE6. Z-index does not solve the problem. I have searched the web and find iframe can be used as a fix and I am currently making the change. Has anyone done this already?”

Very nice,
I looked for something light like that.
Thank you.

Richard Feb 23 2009

I really like this tool tip but was wondering if it is possible to use HTML within the tooltip e.g. ?

Richard Feb 23 2009

I really like this tool tip but was wondering if it is possible to use HTML within the tooltip e.g. </br>

Very nice! I love the way it works! I’m just having a small issue with ie7. I’m using .png files for the images for the bubble and I can not get the images to display correctly on IE7. It is getting rid of the alpha channel and that is causing the images to look gray instead of white like they are supposed to. Any suggestions?

Thanks!

very nice script!!
one question though..

when I hover my mouse on the anchor tag I get this popup. but dont know why my cursor icon changes to ‘arrow’ icon instead of ‘hand’ icon as it is on the anchor tag.

Exactly what I needed. Clean and simple. Thank you very much!

Thanks a ton – this is exactly what I want – a clean and simple solution.

Really enjoyed your script. I have tweaked the CSS a little to use on my own site. Like others, I just don’t want to use frameworks. I want to keep things simple and understand most of the code on my site.

I am playing around with your script and Google Maps. I don’t like their balloon style infoWindows. Here is what I am playing with: http://www.bobbystuff.com/About_Me/mapped_photos.php

I am having problems when I click twice on a camera icon so I need to tweak the script.

And now my question. In the line

pos:function(e){

how does this function get a value for ‘e’. I see that pos is called as this.pos but where does the ‘e’ parm come from?

Thanks,
Bobby

Emanuel Mar 14 2009

Hey, nice script.
Added some delay to fade out:

Add this lines:

var delayTimer;

add the method delayHide:

delayHide: function( seconds )
{
tt.delayTimer = setInterval( function(){Tooltip.hide()}, seconds * 1000 );
}

And now we need this line in two places:
clearInterval(tt.delayTimer);

Copy it under the following line in the methods hide and show:
clearInterval(tt.timer);

And now in the HTML-Element do: onmouseout=”Tooltip.delayHide(.5);”

Caio C Iglesias Mar 16 2009

I’m getting black borders on the rounded corners in IE. Any tips?

My problem (operation aborted) still ongoing. Any updates ?

calPerformanceNet Apr 15 2009

I am getting a ‘tt.timer’ is null or not an object.
And now I am stuck.

Hello…
Thanks a lot .. its works great, and beautiful tool
Pretty Nice

:)

greatonkar Apr 17 2009

NOT WORKING IN IE7

NOT WORKING IN IE7

hello this is very helpful, big props to the developer who shared this with us. I noticed you can use BR and EM, but any attempt to put a link in the tooltip seems to break it, is there any way to insert a link into the tooltip??

arif

Izzuddin Noor May 26 2009

Fully working with IE6 IE7 Firefox Opera Google Chrome and Opera. I’ve tested it. Probably omkar and greatonkar u got not latest update. Ok here is the link to the three files u might download it saperately and test it on your localhost.

http://sandbox.leigeber.com/tooltip/ —->view source save as index.php or default.asp or index.html any kind u like.

http://sandbox.leigeber.com/tooltip/script.js —-> save it as script.js

http://sandbox.leigeber.com/tooltip/style.css —-> save it as style.css

put all these 3 files in one directory as well the images folder which you had downloaded earlier. Hopes this helps.

Thank to the Author Michael Leigeber Keep up with good works. Thank Bro.

May i ask. Michael Leigeber why don’t you put credit in the script or copyright it. This content is valueble yo.

Hello there, the code is just great. However I have a small problem. When the stung shown in the tooltip has ” or ‘ in it, the script fails. How do I prevent this. I can not comment the ‘ or ‘ as they are already commented in the php var i have, and the output is:

onmouseover=”tooltip.show(”, 200);”

I mean
[code]onmouseover=”tooltip.show(‘$var’, 200);[/code]

Chester Jun 10 2009

Hello,

This is probably a really easy fix but can anyone tell me how to center the tooltip above the cursor instead of aligning it to the left edge? I’d really appreciate it! Thanks in advance.

ruudvan Jun 20 2009

hello…thanx for a really nice script.

There is a small issue that probably needs to be seen. When the text is near the corner boundary of the window or near some side boundary, the popup gets hidden behind the window boundary. Is there some way to make it change sides when near the window boundary. (like if it pops out of cursor’s left side when text is near windows right boundary and thus not get hidden by the boundary)

I’ve spent some time trying to figure out how to get the tooltip to display centered above the text (So the center of the tooltip is directly over the mouse).

So if anyone wants to know how it’s done, here is what you have to do:

1. Change “var left = 3;” to “var left = 0;”

2. Change “tt.style.width = w ? w + ‘px’ : ‘auto';” to “tt.style.width = ‘200px';” // Unfortunatly it doesn’t seem possible without having a fixed width.

3. Change “tt.style.left = (l – left) + ‘px';” to “tt.style.left = ((l – left) – 100) + ‘px';”

I realise these aren’t the worlds best instructions so I do apologize, however that should fix it.

*You could probablly get the tooltip to center its self above the mouse with a dynamic width; but I havn’t figured that out yet*

Hope that helps,

~ Chris

ruudvan Jun 22 2009

Hey…Needed some help. can we use this script in svg e.g. if i want a tooltip from a shape, say circle? please tell how.

Fr@ncky Jun 24 2009

Very nice,
but I have a Problem with tooltip text that contain a new line, like
onmouseover=”tooltip.show(‘Dein Syria per speciosam interpatet diffusa planitiem. hanc nobilitat Antiochia, mundo cognita civitas, cui non certaverit alia advecticiis ita adfluere copiis et internis, et Laodicia et Apamia itidemque Seleucia iam inde a primis auspiciis florentissimae.Alii nullo quaerente vultus severitate.
TEST’, 200);”

Any ideas to fix it?

Fr@nky,

remove the newline and add a to get a newline

That should be add a <br/>

ruudvan Jun 29 2009

hello again…
Can someone please help by telling what all changes are to be done so that this works in svg.

Hi, i tried customizing your code and implementing it in a form. This is the scenario in IE…

I have my form with few text fields, select boxes and other form elements. For the validation part, i tried highlighting the form elements with a red border around and applying the tooltip to show the error messages on mouseover of the same. When i do mouseover on the select box in an error state, it overlaps the tooltip sending it backwards. On mouseover, I tried appending the IFRAME dynamically in this case but not getting the desired output. It would be really appreciated, if you can help me out in this matter.

Absolutely the best. Thanks for the script. Easy to integrate!!

Vanessa Sep 11 2009

This is exactly what I was looking for. Thank you. I’m just having one issue that I can’t figure out how to fix. When I hover over the image the tooltip shows up behind it rather than in front of it. Can anyone please help me? The URL to the site is http://vanessajohodesigns.com/new_multimedia.html

The only image I have placed the tooltip coding is the first one on the right side. Thanks in advance.

Sebastien Sep 26 2009

Hi, I have a php table with my sql results in it. but only showing a couple of column . Would it be possible to onmouseover to show the full results of that mysql query?

tks

Seby

Just curious how to change the font inside the tooltip…

I’m getting a javascript error ‘tt.timer’ is null or not an object. What am I missing?

The only code I added to my actual table was the mouseover, mouseout, css link, and js link.

Thanks!

I resolved the tt.timer issue. All the files had to be in the same folder.

I am now having an issue with a large space being created before my text after I hover over something.

I would also like to find a way to move the tooltip so that it is evenly spaced (top to bottom) from where you hover instead of it being even with the bottom.

Thanks!

Great script!

Just to share a quick and easy way to pass quoted strings in the function call is with…

onmouseover=”tooltip.show(‘&amp;quot;my to pass&amp;quot;’, 200);”

hope that helps =)

Mehedi Hasan Oct 25 2009

WOW!!! Great ToolTips…. Thanks a lot…

Scott Elliott Oct 30 2009

What if you are trying to use the tooltip inside of a modal popup (ASP.NET)? It shows behind my popup instead of on top … ??

Scott Elliott Oct 30 2009

Nevermind … i just added z-index: 9999999; to #tt style

How do you detect the edge of the window to keep the tooltip within the window or display the tooltip to the left if the edge of the window is on the right?

I’m interested in coloring the text inside the tooltip — many different lines of text in one tooltip with varying colors. I can use simple tags to make the text bold or strong, as in your examples, but whenever I try to use in-line styles or anything else with an attribute (even if I make sure to use \’ instead of “) I always run into problems.

Thanks.

Sorry to double-post, but I figured out what I was doing incorrectly.

I’m writing a PHP program and was writing HTML within PHP echo statements. Due to the fact that the show function within the script is coded in Javascript, you have to “escape” any apostrophes that you use when you’re passing in an HTML formatting tag with an attribute (you can see this in the example page where an image is used in the tooltip). The syntax for that is \’ as opposed to simply ‘.

I couldn’t figure out why my code wasn’t working because I -was- using the escaping properly. My issue was that PHP -also- requires escaping because its echo strings are delineated by apostrophes as well. So when the Javascript read my HTML and say there was a line of code in there:

Hello;

the Javascript would take care of the escaping when it returned that line, leaving only the apostrophes without the forward slashes. However, I wanted those forward slashes to remain for PHP because I have to use escaping there as well. So, in effect, I had to double escape those characters:

Hello;

One forward slash for the first forward slash, and another for the apostrophe. When the Javascript interprets the \\\’ it leaves only \’ which is what I needed for the PHP.

Very confusing but it makes sense now and works like a charm.

– Mark

Mark,

how to use php variable in this js script?
thank you:)

@lidaof – Not sure what you’re asking here, sorry.

Madeline Dec 15 2009

Thank you very much for sharing this tool. It works great – even in ie6!

Katherine J. Dec 31 2009

Wonderful! Thanks for this useful and attractive tool.

Dear jacob,
can you pls provide me the solution for this problem.
this is really nice script but can’t work fine with IE6, 7.
the tooltip block will remains at top while scrolling the page and also the window timer is flicking randomly.
this script works fine in FF.
pls help me out of it

Cool script and also clean.

Arti Singh Mar 17 2010

Really its too good and easy to use thanks for this nice tip.

Sweet application works really well with PHP as well (having a slight problem echoing extremely long files though so if anyone can help this non java conversant person..) I like how i dont really have to know java to do this :-) Awesome script..

Vishal Lakhani Apr 03 2010

Great !! Thanx 4 sharing a lightweight ToolTip

WDonders Apr 14 2010

Nice script!
Note: the script.js file in starter.zip is an empty file of 0 bytes :-)

Steve Otto Apr 26 2010

I’m having an issue with the toolTip not showing in IE but it works fine in FF and Safari.

The issue is specific to my text with the tooltip being dynamically generated. I have a javascript file that parses through google calendar and creates the html.

For some reason, IE can’t add the tt div info to this dynamically generated html.

I believe that the JS code is not able to perform this function in IE on my dynamically generated code:

show:function(v,w){
if(tt == null){

Any ideas on how to fix this?

Otherwise everything works great.

(BTW – it’s supposed to show on the title of the Upcoming Events section in the lower left hand corner of the page).

Thank you, this is very great.

Hoque Md.Nazmul May 27 2010

Without using jQuery/prototypejs, this is really lightweight script and the effect is impressive.

Very nice tooltip…..loved it

Well done on the tooltips, they look really good.

Was wondering how is would be possible to add images to these tooltips without changing the code around too much?

Thanks

Jack Penny Jun 06 2010

For those looking for an Internet Explorer fix, I have came up with one. I’ve tested it on several resolutions, etc and it seems to work okay. I used IE8 to perform the test.

It’s quite simple, in script.js find:

tt.style.top = (u – h) + ‘px';

and replace this with:

if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)){
tt.style.top = ((u – h)+100) + ‘px';
} else {
tt.style.top = (u – h) + ‘px';
}

Hopefully this’ll work for you guys :)
Also, to the author: amazing script, thanks!

Jack Penny Jun 06 2010

Update: turns out my original fix was way off, I was looking at the wrong aspect.

Anyway, to fix it properly (fixed scrolling etc in IE) I gave the body tag an ID (e.g. ) then changed
document.documentElement.scrollTop to document.getElementById(“bodyId”).scrollTop

Would it be possible for someone to explain how to add a delay before the tooltip appears? The solution posted earlier does not work, and merely slows down the fade out. Thanks!

Artur Tondera Jun 10 2010

This is the best tooltip script available. I have tried many, but none other works so good as an addition to the map tags!
BIG THANKS!!!

OldFred Jun 12 2010

I’m working with ’em’s; When using ctrl-Mousewheel to change the size, the tooltip’s position doesn’t move proportionally to the change made, moving further away as more as I increase the size.
This happens only in IE (IE8), but works correctly with FF.

Any ideas how to prevent this ?

otherwise : Bravissimo!!!

Great work! Thanks.

Save me a lot of time. Thanks!

This is a great script, but I was wondering how do I trim it down further? I don’t need the graphics or their css references so I was able to clear out some code by ditching those. I can achieve the same effect using css3 in just the #tt style (I only lose the rounded corners in IE, since IE doesn’t yet support css3).

However, I don’t know JavaScript well enough to comfortably edit “script.js” to remove all references to the #tttop, #ttcont, & #ttbot styles. It would be great if someone was willing to post a clean, stripped down version of the code with the assumption that no graphics and only css3 is to be used.

Thanks!

Your script is superb!!!

good work

Okay I feel stupid, I am new to making websites, I see how this works as code, I am confused as to how to add this into the site where it display the tool tips themselves.

Also I saw someone post about interactive tool tips, if I can learn about these I would love to later go back and make them interactive if you ever do that.

“idiot”:

If you scroll up and click on the link where it says “View the JavaScript Tooltip demonstration.” and then right-click on the page and click “View Source”, your browser will show you the source code for the page and how it all works together. Take particular note that the style sheet code is being linked to in a separate file in the same directory. It is called “styles.css” and linked with the code:

link rel=”stylesheet” type=”text/css” href=”style.css”

Excellent work this just put the finishing touches on my image map.

very nice script… thanks

Vasu chandra Aug 05 2010

Hi jacob…,
great job man…but i have small problem…!
When i minimize the IE window and make mouse moveover the text field the tool tip is missing (actually it is displayed under the tool bar of IE). It is not visible for me. How to resolve this problem? When i used title tag for tool tip this issue is resolved..but i want to use your code..Please help me ASAP..

thanks

Vasu chandra Aug 05 2010

minimize in the sense making the IE window small..

I’m a beginner and I found easy to use.
Great job. Thank you !

hi, i’m just wondering if your tooltip application apply the same functionality if the scroll of the screen enables.
Im trying on my application but it seems the tooltip stays in the upper portion of the screen if I scroll down.
Please Help. Need advice. Thanks.

This is a very nice light weight script, really clean and Michaels blog has some more nice scripts. Thanks for share.

SatchmO Sep 02 2010

Having the same problems with IE scrolling.

Plus when I use the tooltip for two different images (in img map area), in case of one it works correctly, but for the second image it has really strange behavior. Sometimes it blinks other time it doesn’t appear at all.

I would be very grateful for any solution. Thx.

Fernando Silva Sep 22 2010

Man, thanks a lot. But I have a problem. In my page I’ve put some swfs and when I call the tootip it stays behind the swf movie. How can I fiz that?

I’m also having troubles with scrolling. When I scroll down, the tooltip stays at the top of the page, and sort of goes out of wack from there. =(

Oh I forgot to add: It works perfectly in Firefox. I’m having issues in IE.

Also, I forgot to say, Thank You!:D I’m new to building websites and this has helped a lot.. so thanx =)

Iain Kay Sep 25 2010

This code is absolutely lovely. Just used it to implement a rollover tooltip for entries in a sidebar list that have to be truncated with …’s and it fits the task perfectly.

Smooth in all the PC and Mac browsers I’ve had the chance to test it on (That’s IE7/8/9, FireFox 2/3, Latest: Chrome, Safari).

All in all a very nice contribution, thank you for not only contributing the code but explaining how it works too.

Iain

Yeni Setiawan Sep 25 2010

Beautiful code, it really works!
Thanks mate ;)

Great script.
Thank you :)

Emiliano Oct 08 2010

Hi, there’s a way to use those scripts on a modalbox, I tried with z-index but doesn’t work, the tooltip it’s always behind the modalbox. Any ideas??
thanx

ComPorts Oct 14 2010

Great script!, anyone knows how to make the tooltip stay open although the mouse has been removed from the link? And adding a “x” to close the tooltip manually?

Very easy to use. Great script. Many thanks!

Hello Jacob, very nice and simple script, exactly what i was looking for. but let me ask a javascript question: for what serves the last line “} ()”. Why do you need this brackets?

Daniel F. Dec 17 2010

Same question of Martin, please explain that.

Chris M. Jan 10 2011

Has anyone found a solution to the tooltips displaying at the top of the page when scrolling down in IE? I would really hate to remove this script from my site because of a small bug like that :(

Very nice effect and lightweight. Thanks for sharing

Gibenco Jan 15 2011

I’m having a problem with the tooltip showing behind another div… how can i fix this so that the tooltip is always ontop of everything? thanks in advance

How can I remove the fade effect or at least decrease the fade duration? In IE the tooltip stays visible for too long but it seems fine in Chrome

is it possable to get this to have an auto position? i have a lot of info in mine and if the tip is used near the top of the page then the top part is pushed above the screen. same thing happens if the tip is used near the bottom of the page.

Very nice effect, easy to implement and very professional. Thanks for sharing!

Buddy R Feb 19 2011

There is a typo on line 30 of the js:

document.onmousemove = this.pos;

should be

document.onmousemover = this.pos;

The ‘r’ in onmouseover is missing.

Hello, what do I do to only get the tooltip without a link, it will simply appear only the declaration and are not linked to the glossary page

please help how can i remove the link i only whant the tooltip

Charlie Mar 02 2011

Chris, all you have to do is on you pages use the mouseover and mouseout. You dont need to have the text, you can even do it on pictures just be sure to include mouseover and mouseout. Example and make sure that you are linking the script to your site.
If anyone is looking for a deal on luggage or laptop cases, visit http://www.luggageone.com
-Thank you.

Alessandro colarossi Mar 04 2011

Awesome, this is exactly what I was looking for! Have a look at how I implemented it here: http://www.acolarossi.com

;)

Alessandro colarossi Mar 04 2011

Anybody find a solution to add clickable links in the tooltip?

This is really cool. You have put a lot of work into it.

Robiul Hoque Mar 12 2011

I wanted to use thumbnail image as tooltip instead of plain text, can anybody help?

Hi. What a great script. Thanks alot for that!. I am asking the same Hyster was asking: can it be positioned bottom right at the cursor? Its not visible near top. Otherwise, this is awesome and simple to use

Hi there

I implement it but it doesn’t show RUSSIAN characters – UTF8 …

what should I do for it to show russian characters.

Please help
Thank you

how I can display the tooltip which content has the special character ? example for the following text which I want to to display when mouse over?

it is chris’ dob so we all want to go, not today..test here

I try to use htmlencode but it won’t work

muasamvui Mar 26 2011

i thanks you very much ! i am finding such a nice tool for my e-commecer website!

i need tooltip with image

To handle the screen edges in the right and top I replaced the code:

tt.style.top = (u – h) + ‘px';
tt.style.left = (l + left) + ‘px';

replaced by:
if((u – h) <= 3){
tt.style.top = 3 + 'px';
}else{
tt.style.top = (u – h) + 'px';
}

if(screen.width – l <= 300){
tt.style.left = (l – tt.offsetWidth) + 'px';
}else{
tt.style.left = (l – left) + 'px';
}

Thanks,
Khalil.

Nice tooltip. And I wonder: can I use your code in my project?

Hello, Thank you for your good tooltip. But I wonder: can I use your code in my company’s commercial project ?

RaviMagod Apr 24 2011

Thanks for great script, even more for sharing it. I have tweaked it to delay showing the Tootip and automatically hide it after predetermined time.

1. Add variables after existing
var showDelay=1000;// show after delay of 1 second
var showFor=3000; // show for 3 seconds
2 Add pausecomp function after hide
pausecomp :function(millis){

/* Thanks Curtesy Sean McManus http://www.sean.co.uk/a/webdesign/javascriptdelay.shtm*/
var date = new Date();
var curDate = null;

do { curDate = new Date(); }
while(curDate-date < millis);
}
3. Add showdelay function
showdelay: function(v,w,t){
showFor= t ? t:showDelay;
this.pausecomp(showDelay);
this.show(v,w);
setTimeout ( "tooltip.hide();", showFor );},
4. Use onmouseover="tooltip.showdelay("Testing Delayed Dispaly",200,5000);. This will delay the tooltip for one second and hide it after 5 seconds.

thank you very much, i’ve read somewhere that it can be done using jquery, but this one is really “light weight”, exactly how i wanted, brilliant piece of code!

Is there a way to make the tip not follow the mouse pointer and come from a place relative to the hotspot?

Works fine in localhost. but not in live website.

used this code inside php while loop

RE: Buddy R February 19th, 2011

There is NOT a typo on line 30, document.onmousemove is correct.

It is NOT intended to be on mouse OVER, is IS on mouse MOVE!

RobertE Jun 27 2011

This is sooo much easier in Flex/Flash Builder…It cuase me to cry everytime I look at JS….

Very nice effect, easy to implement and very professional. Thanks for sharing!

Hi, there’s a way to use those scripts on a modalbox, I tried with z-index but doesn’t work, the tooltip it’s always behind the modalbox. Any ideas??
thanx

Hi !

I had the scrolling issue on IE8 as well. I used Jack Penny’s fix but I can’t modify the body but you can get it using getElementsByTagName()

pos:function(e){
var body = document.getElementsByTagName(‘body’)[0];
var u = ie ? event.clientY + body.scrollTop : e.pageY;
var l = ie ? event.clientX + body.scrollLeft : e.pageX;

Hi.

First of all great script love it. Easy and very practical script.

Though i want to make a little change but cant get it right.
I want to keep the original dark grey balloon pop-up. Next to it i want the same balloon but in a different color, yellow.

Maybe i can explain it better this way.
Hover item 1 = Balloon grey: when i hover over this item the balloon should be with a grey background.

Hover item 2 = Balloon yellow: when i hover over this item the balloon should be with a yellow background.

I tried copy-ing the tooltip function and changing the id’s used in CSS. I do get to different balloons but the new copied function yellow balloon sticks to a static position.

Can someone understand this problem and know how to fix it?
Please help me out.

Brendan Aug 01 2011

I created a small fix for the tooltip hiding behind my gridview control.
In the Show function comment out the document body
and put in the two lines for t1 variable.
Adjust GridView2 name below to id of your control

var t1 = document.getElementById(“”)
t1.appendChild(tt);
// document.body.appendChild(tt);

Have Fun

PS: Great piece of code – A1
Ireland

Mohammed Hameed Aug 02 2011

Thanks a lot. It worked perfect.

Fantastic in Chrome and FireFox, but the IE issue is a problem. I have tried all the ‘fixes’ but they either make it disappear altogether or worsen the situation. Sadly I think I have to find another script, as IE seems to be used by more than 85% of my visitors.

Is there any limit for tooltip content lenght?
Script seems to be doesnt work when there approx. >= 300 symbols.
How may I fix this?

Sorry, in text were ” (raquo) symbols, that was the problem

Wow, excellent article thanks a lot :)

olof thiel Aug 18 2011

Hi there,
I am without exception working with images on my site ( I am an artist) so I wonder if it is possible to trigger the tooltip from an image instead from a text?
Eagerly looking forward to an answer
olof thiel
stockholm
sweden

Absolutely awesome!

Thank you :P

@olof thiel

Yes, just use the class object on the image instead of text span/div or link.

Go to http://www.britain2spain.co.uk/default.asp?PID=3&PropID=850 and hover over the icons above the photograp block – I have set mouse pointer to look as if it is a link [style=”cursor:pointer;”]. Same for currency flags to the right of price.

I still have an issue with placement in IE, but in FFox and Chrome it is beautiful!

If you get stuck, give me a ‘shout’

Nomad

soulfulfunk Aug 21 2011

hi, thanks for this… very simple to implement…

in case anyone’s wondering, you can update this dynamically using asp.net with this code:

Label1.Attributes.Add(“span class”, “hotspot”)
Label1.Attributes.Add(“onmouseover”, “tooltip.show(‘” & TextBox1.Text & “” & TextBox2.Text & “‘);”)
Label1.Attributes.Add(“onmouseout”, “tooltip.hide();”)

the only problem is if it’s too many character the script fails…. don’t know why… any ideas???

great script anyway…. thanks

soulfulfunk Aug 21 2011

hi, just to follow up on my last comment… it’s not too many characters, it’s if there’s an astrophe in the paragraph, it breaks the javascript code…. any ideas? thanks

Yes, put a \ before the apostrophe … eg:

Descripció de l\’immoble

Nomad

person287 Aug 26 2011

Just put a tooltip onto my website. Great script. Thanks

ice bat Aug 31 2011

ZOMG! amazing, thanks a lot

S.T.Prasad Sep 01 2011

Hi,
A great effort. Has anyone extended this to become a sticky note with a clickable hyperlink in it?
Thanks,
S.T.Prasad

gud…

Edvaldo Szymonek Sep 03 2011

Thanks you. It’s very nice!

This is great, thanks, especially the namespace stuff – hadn’t seen that before in JS, great encapsulation.

vishwaprakash Sep 09 2011

Its really great work done by you.
Its working in FF beautifully but its not working in IE please suggest…….!

thank you so much

Gregory Nozik Sep 11 2011

Great article.
I also created a tool tip component based on prototype
framework

Please visit http://gregnozik.blogspot.com/2011/09/tooltip-class-prototype.html

How to incorporate tooltip/onmouseover the drawChart function

var s= parseInt();

google.load(‘visualization’, ‘1’, {packages:[‘gauge’]});
google.setOnLoadCallback(drawChart);
function drawChart() {

var data = new google.visualization.DataTable();
data.addColumn(‘string’, ‘Label’);
data.addColumn(‘number’, ‘Value’);
data.addRows(4);
data.setValue(0, 0, ‘DAY’);
data.setValue(0, 1, 5);
var chart = new google.visualization.Gauge(document.getElementById(‘chart_div’));
var options = {width:400, height: 120,minorTicks: 5};
chart.draw(data, options);

Gauge meter

microchip Oct 08 2011

Hi,

Is it possible to position this tooltip below the link? If so, how?
Also, I’d like it to display on the left side instead of right. How to accomplish this?

Savio Sacco Oct 13 2011

Just used the the tool tip on my website. Exactly what I was after, a simple implementation that does not conflict with other stuff (like jQuery).

Hi, thanks so much for the tutorial, looks really nice. I made some changes and want to use it within our company’s software, but I wonder about the license. Is it public domain?
Thanks

Thanks for this. This JavaScript only solution is exactly what I’ve been looking for. It has yet to break for me even on very old browsers. I recommend this over jQuery alternatives which may cause conflicts.

Your code is nice but I doubt that it is useful for multiple pages because we would have to copy the static code to every page, unless you meant to provide this code as a reference for further expansion.

Masclatpete Sep 17 2013

Hi,
Just wanted to say a huge BIG thank-you to all you guys who have contributed. This script and its mods are simply fantastic and just what I’ve been searching for.
Thanks

This comment section is closed. Please contact us if you have important new information about this post.

Partners