Create a Simple CSS + Javascript Tooltip with jQuery

Create a Simple CSS + Javascript Tooltip with jQuery


Create a Simple CSS + Javascript Tooltip with jQuery

It's always a joy to understand how things work. Well, at least I do. Alright, this time, I want to share with you all, how to create a simple jQuery tooltip. In this website, I'm using a script I grabed it online, and it uses onmouseover and onmouseout. It's really messy and annoying me. So, it's jQuery comes to rescue. The way it works is fairly simple, I use the Anchor tag REL and TITLE attributes to identify a tooltip and its content.

By the way, if you are having problems looking for a good iPage Web Host, you can use this website to guide you: Web Hosting Review

Getting the mouse X and Y axis

First of all, I did a search with google, and I found this little script from this blog, very useful information. It shows me the idea how to retrieve the X and Y Axis coordinate.

$(document).ready(function()
 {
  $().mousemove(function(e)
   {
    $('p').html("X Axis : " + e.pageX + " | Y Axis " + e.pageY);
  });
});

 

Detect the Anchor element

I wrote a simple selector to select only Anchor tag with REL set to tooltip, I'm using the same approach in the Navigation List menu + jQuery Animate Effect tutorial. It's very straight forward and easy.

	$('a[rel=tooltip]').mouseover(function() {
		......
	});
As a result, anchor tags that support this simple jQuery tooltip should look like this
	<a rel="tooltip" title="Testing of tooltip">sentences</a>

 

Trick to hide the TITLE Attribute's Tooltip in browser

Okay, there is one major issue we need to sort it out - The native tooltip in Mozilla browsers. If you're using TITLE attribute in Anchor tag, on mouse over, a small yellow tooltip will appear, we want to avoid that. So, a simple solution, on mouse over, we will grab the value in the TITLE attribute, then, remove its value. While on mouse out, we'll put it back on. : ) simple and easy. You'll able to see this in the final code.

 

 

CSS

Finally, the CSS. I try to make the tooltip easy to reskin, you can customize the tooltip in this section. The structure of tooltip it made up with 3 sections - header, body and footer. It will be very easy for you to create your own skin.

#tooltip {
	position:absolute;
	z-index:9999;
	color:#fff;
	font-size:10px;
	width:180px;	
}

#tooltip .tipHeader {
	height:8px;
	background:url(images/tipHeader.gif) no-repeat;
}

/* IE hack */
*html #tooltip .tipHeader {margin-bottom:-6px;}

#tooltip .tipBody {
	background-color:#000;
	padding:5px 5px 5px 15px;
}

#tooltip .tipFooter {
	height:8px;
	background:url(images/tipFooter.gif) no-repeat;
}

 

Final Product

Basically, that's it. Just combine al the techniques together, and you have just learned how to create a simple jQuery tooltip! You can look at the demo or download it and start playing with it.

Demonstration Download
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Simple JQuery Tooltips turtorial</title>

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">

$(document).ready(function() {

	//Select all anchor tag with rel set to tooltip
	$('a[rel=tooltip]').mouseover(function(e) {
		
		//Grab the title attribute's value and assign it to a variable
		var tip = $(this).attr('title');	
		
		//Remove the title attribute's to avoid the native tooltip from the browser
		$(this).attr('title','');
		
		//Append the tooltip template and its value
		$(this).append('<div id="tooltip"><div class="tipHeader"></div><div class="tipBody">' + tip + '</div><div class="tipFooter"></div></div>');		
		
		//Set the X and Y axis of the tooltip
		$('#tooltip').css('top', e.pageY + 10 );
		$('#tooltip').css('left', e.pageX + 20 );
		
		//Show the tooltip with faceIn effect
		$('#tooltip').fadeIn('500');
		$('#tooltip').fadeTo('10',0.8);
		
	}).mousemove(function(e) {
	
		//Keep changing the X and Y axis for the tooltip, thus, the tooltip move along with the mouse
		$('#tooltip').css('top', e.pageY + 10 );
		$('#tooltip').css('left', e.pageX + 20 );
		
	}).mouseout(function() {
	
		//Put back the title attribute's value
		$(this).attr('title',$('.tipBody').html());
	
		//Remove the appended tooltip template
		$(this).children('div#tooltip').remove();
		
	});

});

</script>

<style>
body {font-family:arial;font-size:12px;text-align:center;}
div#paragraph {width:300px;margin:0 auto;text-align:left}
a {color:#aaa;text-decoration:none;cursor:pointer;cursor:hand}
a:hover {color:#000;text-decoration:none;}

/* Tooltip */

#tooltip {
	position:absolute;
	z-index:9999;
	color:#fff;
	font-size:10px;
	width:180px;
	
}

#tooltip .tipHeader {
	height:8px;
	background:url(images/tipHeader.gif) no-repeat;
}

/* IE hack */
*html #tooltip .tipHeader {margin-bottom:-6px;}

#tooltip .tipBody {
	background-color:#000;
	padding:5px;
}

#tooltip .tipFooter {
	height:8px;
	background:url(images/tipFooter.gif) no-repeat;
}

</style>

</head>

<body>

<div id="paragraph">
A paragraph typically consists of a unifying main point, thought, or idea accompanied by supporting details. The non-fiction paragraph usually begins with the general and moves towards the more specific so as to advance an argument or point of view. Each <a rel="tooltip" title="A paragraph typically consists of a unifying main point, thought, or idea accompanied by <b>supporting details</b>">paragraph</a> builds on what came before and lays the ground for what comes next. Paragraphs generally range three to seven sentences all combined in a single paragraphed statement. In prose fiction successive details, for example; but it is just as common for the point of a prose paragraph to occur in the middle or the end. A paragraph can be as short as one word or run the length of multiple pages, and may consist of one or many <a rel="tooltip" title="Testing of Sentences">sentences</a>. When dialogue is being quoted in fiction, a new paragraph is used each time the person being quoted changed.
</div>

</body>
</html>

Author: Kevin Liew

Kevin Liew is a web designer and developer and keen on contributing to the web development industry. He loves frontend development and absolutely amazed by jQuery. Feel free to say hi to me, or follow @quenesswebblog on twitter.

Share the love

78 comments

George
Thu, 19th March 2009
Like it ... you need to fix it for IE6, also in Firefox if you have Google toolbar instaled with Translate/Enable word translation a small yellow tooltip is there. Reply
kevin Admin
Thu, 19th March 2009
Hi George, I have fixed the IE issue, will look into google toolbar later on... cheers Reply
Alexandre Broggio
Fri, 20th March 2009
Cool Reply
adam a
Fri, 20th March 2009
can you help me adjust the transparency effect of the tooltip? i cant seem to spot the code that is creating the effect. excuse my noobness please. Reply
adam a
Fri, 20th March 2009
nevermind found it. fadeTo() Reply
Andy D
Thu, 28th May 2009
Great read.... WOndered if you could offer advice? I'd like to have a sort of tool tip thing on an image, so that when the cursor is over the top of a particular part of the image, say a house, then there would be a tooltip window with a description of the property, and url or something else. Could this be done in this instance? Reply
hirakumar
Fri, 19th June 2009
Actually, I want to show tooltip while I focus on input text field . So, I change javascript into $('input[type=text]').focus(function(e) { ---} but does not show any tooltip , Even I set title and type attribute in" input" html tag. Is there any solution for this tool tip in input box Reply
buddy
Mon, 14th September 2009
I had to use:
$("html").append..
and $("html").children('div#tooltip').remove();
because usage of 'position:relative' container makes tooltip float away Reply
Fandi gala
Sun, 27th September 2009
Memang diperlukan konsep Reply
engin
Mon, 5th October 2009
Thanks for this tutorial! Reply
Robbiegod
Mon, 30th November 2009
When i add padding to style .tipBody, when i hover my link i am seeing a small dark rectangle (same width as the tooltip box and same color). Its like it is making two boxes appears. How can i get the other box to go away. I need padding in the tip too. Reply
Zander
Mon, 30th November 2009
I am using part of your code and am having a similar problem to buddy above. My main page container needs to have relative positioning, because of this, the tooltip is floating away. What is the way around this? Reply
Gilmar Lopes
Wed, 2nd December 2009
I put this script in my project but the internal div not show the tooltip! Reply
Will
Fri, 15th January 2010
It's Very Cool ! But i Have Other type of ToolTip, The ToolTip Ballons ! Reply
Gribby
Mon, 1st February 2010
Oh, guys! I found it, buddy absolutely correct says, that when positioning relative tip floats away at right-bottom corner, and solution is use $("html").append… but it still not work in IE! )) Correct is use $("body").append. Cheers Reply
anker
Sun, 18th September 2011
Thank you so much! Now I can finaly use this tooltip on my site Reply
Barry
Tue, 20th September 2011
or you can just live$(this).append... as it is, but prepand it with the line: $(this).css('position', 'relative'); Reply
Girish
Wed, 3rd February 2010
Hi,
Great work dude. I want to make some customization for that I need http://code.jquery.com/jquery-latest.js file. Can u please send it to my email id i.e. girishpalmah@gmail.com

Thanks Reply
Elijah
Tue, 15th June 2010
Thanks for your post! but not working in google chorme Reply
Pete
Fri, 12th November 2010
The demonstration looks cool. Is there a way to implement this to wordpress? The plugins I found are no cool. Reply
girl
Sat, 1st January 2011
Very cool. Thank you so much!!!1 Reply
Balazs Gyorfi
Sat, 29th January 2011
How can I put an EMBED video in this tooltip?

Thank you,
Balazs Reply
Kevin Liew Admin
Sun, 30th January 2011
hmm, embed video, I don't think you can, but you can try to put the html embed code in the title of A tag. Reply
fask
Thu, 17th February 2011
hello and thanks for sharing, but if I want to create a js file rather than enter the code before the closing tag of the head as you do? Reply
Kevin Liew Admin
Thu, 17th February 2011
Yes you can. You just have to take everything in between <script> .... </script> and put it in a js file. After that, link it with <script type="text/javascript" src="filename.js"></script> Reply
Damnjan
Fri, 25th March 2011
Very nice and useful script :) tnx Reply
dirk
Mon, 11th April 2011
It also runs with the img tag?
thanks Reply
shantanu
Mon, 18th April 2011
Hi Guys, i have problem with tooltip, can some help me ,

i want a tooltip on when i drag and select a paragraph text the tooltip comes in center of the selected text. please help me i am really fade up of this.

help! help! help! Reply
Kevin Liew Admin
Mon, 18th April 2011
Unfortunately, this tooltip script won't be able to do that. It would be kinda hard to make one as well, because you can't really detect the dimension and position of your selected text. Reply
venkat
Tue, 19th April 2011
how to implement it for select box items, means we can help to select the user one among the list items.( for each select item one specific properties will be given on mouse over.) How to implement it for that? Reply
Kevin Liew Admin
Wed, 20th April 2011
I dont think that effect can be done with the default select box. I guess you need a custom css based select box, and then apply the tooltips to each of the item. Reply
Jay
Fri, 6th May 2011
I've updated your coding for css3, It's a bit ugly, but, Cheers! no more images! :)

#tooltip .tipHeader {
height:8px;
-moz-border-radius-topleft: 75px;
border-top-left-radius: 75px;
-moz-border-radius-topright: 75px;
border-top-right-radius: 75px;
-moz-border-radius-bottomleft: 0px;
border-bottom-left-radius: 0px;
-moz-border-radius-bottomright: 0px;
border-bottom-right-radius: 0px;
background:#333;
}


#tooltip .tipBody {
background-color:#000;
-moz-border-radius-topleft: 0px;
border-top-left-radius: 0px;
-moz-border-radius-topright: 0px;
border-top-right-radius: 0px;
-moz-border-radius-bottomleft: 0px;
border-bottom-left-radius: 0px;
-moz-border-radius-bottomright: 0px;
border-bottom-right-radius: 0px;
background:#333;
padding:5px;
}

#tooltip .tipFooter {
height:8px;
-moz-border-radius-topleft: 0px;
border-top-left-radius: 0px;
-moz-border-radius-topright: 0px;
border-top-right-radius: 0px;
-moz-border-radius-bottomleft: 75px;
border-bottom-left-radius: 75px;
-moz-border-radius-bottomright: 75px;
border-bottom-right-radius: 75px;
background:#333;
} Reply
fabio
Mon, 25th July 2011
great solution; even you can use just the .tipBody with more padding. Reply
sanjeeva
Wed, 8th June 2011
Thank you very much kevin. I've almost spend two days to find out a good jquery plug in to acheive a functionallity of a tool tip pop up. None of them worked form. your solution is simple and can be applied to any element. and no need to add any more js files. Simply superb man. I've applied this code to get tool tip for each element in my asp.net check list items.

Once again...Thank you so much. Reply
mukesh
Tue, 14th June 2011
very nice Reply
IIT Bakar
Wed, 29th June 2011
Thats something interesting. I am trying to implement this at the footer at my webstire <a href="http://iitbakar.com "> iitbakar </a> Reply
sAnToSh
Wed, 20th July 2011
Thanks Kevin, its very useful Reply
ashraf ali
Fri, 29th July 2011
hi
im not good with JavaScript
but i thine if the tool-tip can fetch it's content from external .html page it will be more useful
some thing like that >> http://www.javascriptkit.com/script/script2/ajaxtooltip.shtml
i hope u replay for this
thnx Reply
Kevin Liew Admin
Mon, 1st August 2011
This tutorial won't go that far. But there are plenty of tooltips plugins out there that support ajax feature. Reply
thomas
Tue, 13th September 2011
hi, really nice :)

but how can i change the function, to set more "anchors" to have a tooltip? e.g. [title] oder a.externallink and so on? Reply
Kevin Liew Admin
Wed, 14th September 2011
not sure if i read your question correctly, you can set more than one tooltips by putting rel="tooltip" in each anchor tag. Reply
NaCh
Mon, 31st October 2011
Hi..will it work if the tooltip is on the edge of a window? Like the close button will be on the top right corner and I think with this, the tooltip will be going out of the window. How can that be avoided? Reply
Luke
Thu, 3rd November 2011
I love this and it's pretty easy to use. The only issue for me is that all tooltips expand to the bottom-right. Is there a way to make them expand in the opposite direction, to the left and top of the highlighted anchor? Reply
Kevin Liew Admin
Mon, 7th November 2011
Yes you can. But you will need to create four options: top, left, right, bottom, eg:

<a href="xxx" rel="right">Float right</a>

You need to make the script to grab REL, then pass it to a ifelse statement for different position value.

//Set the X and Y axis of the tooltip
$('#tooltip').css('top', e.pageY + 10 );
$('#tooltip').css('left', e.pageX + 20 );
Reply
geppo
Tue, 22nd November 2011
can you post any exemple? Reply
Milos
Tue, 8th November 2011
this $('#tooltip').fadeIn('500'); not work.... Reply
Rajesh Saran
Wed, 18th January 2012
use this:- $('#tooltip').fadeIn(5000); Reply
gubs*
Thu, 10th November 2011
Hi...I tried using this code but it seems that it's not working with IE7...any advice? Thanks. Reply
fstab
Fri, 2nd December 2011
hey, i cant run this tooltip over any input field, its ignorin input selector etc. any solution pls? thank you Reply
gwledig
Mon, 9th January 2012
I found you don't really need to use Rel you can just use $('a[title]').mouseover(function(e) {
which picks up any links with title tags. I also got over the limitation to hyperlinks e.g. to set a tooltip on an image or whatever using <a href="#"><img src="test.png" /></a>
However, whilst the script runs OK it does seem to run intermitently for me, some tooltips some up as undefined, then you refresh the page and they work, it seems a random bug. Has anyone else seen this behaviour, maybe something to do with the script being processed too fast? Reply
AM
Fri, 10th February 2012
Now this is nowhere near the best solution for this, but what I did was just add a "switch($(this).attr('id')){}" line whilst add a ID to each item you want a tooltip for and setting the var tip to whatever the text needs to be. i.e.:
var tip;
switch($(this).attr('id'))
{
case 'dts':
tip = "<strong>Date</strong><br />Specifies a date to search on. It automatically sets itself to today's date."
break;
case 'tms':
tip = "<strong>Start & End Time</strong><br />If you wish to see only a portion of a day, select the parameters which meet your criteria.<br />"
+ "If it is left blank, it will search thorugh the entire day."
break;
case 'therows':
tip = "<strong>Rows Per Page</strong><br />Specifies the number of rows returned per page. The user can navigate between pages to view all results.<br />"
+ "If left blank, it will show all results.";
break;
} Reply
iTechColumn
Thu, 12th January 2012
Interesting stuff here :) Thanks.. Reply
Rob Admin
Wed, 18th January 2012
Nice tooltip, here is one I created myself as a jQuery plugin: http://www.websanova.com/plugins/websanova/tooltip Reply
Max Chadwick
Thu, 19th January 2012
This is a great and simple solution for creating customizable tool tips that I might just have to use in a project I'm working on. Just wanted to point out that the fade in effect doesn't work in your code because you haven't set display:none for #tooltip in your css. Otherwise, great code. Also cheers to Jay for posting an all CSS solution to adding rounded corners. Reply
guest
Sun, 5th February 2012
Quite impressive, the trouble a guy has to go through just to keep a little title attribute alive with onmouseover/onmouseout. Really really easy would be sth like this: onmouseover="this.title='Computers help to frustrate people'" onmouseout="this.title=''", wherest the onmouseover keeps the title-attribute active as long as the onmouseover occurs. It would make the title-attribute a lot more attractive in case you want to put more info in it. Long complicated scripts for simple attributes are over the edge for me. Sorry. Reply
AM
Fri, 10th February 2012
Bullseye! Nice.

I made a few changes though:
On IE, the box would flash on the left side of the screen, then get updated. This is because you don't set the X & Y when you first fade in. This does the trick:
Change:
$('#tooltip').fadeIn('500');
$('#tooltip').fadeTo('10',0.9);
To:
$('#tooltip').css('top', e.pageY + 10 );
$('#tooltip').css('left', e.pageX + 20 );
$('#tooltip').fadeIn('500');
$('#tooltip').fadeTo('10',0.9);
and bam.
Also look for the comment by me earlier. It "solves" the problem of the tooltip coming up as undefined. Reply
Dru
Mon, 13th February 2012
This is really great! :-) Thank you!!! It works magnificently! Reply
GeoAvila
Wed, 7th March 2012
the offset works better for me. thnx.

//Select all anchor tag with rel set to tooltip
$('a[rel=tooltip]').mouseover(function(e) {

//Grab the title attribute's value and assign it to a variable
var tip = $(this).attr('title');

//Remove the title attribute's to avoid the native tooltip from the browser
$(this).attr('title','');

//Append the tooltip template and its value
$(this).append('<div id="tooltip"><div class="tipHeader"></div><div class="tipBody">' + tip + '</div><div class="tipFooter"></div></div>');

//Show the tooltip with faceIn effect
$('#tooltip').fadeIn('500');
$('#tooltip').fadeTo('10',0.9);

}).mousemove(function(e) {

//Keep changing the X and Y axis for the tooltip, thus, the tooltip move along with the mouse
$('#tooltip').css('top', e.pageY - (parseInt(jQuery(this).offset().top)-25));
$('#tooltip').css('left', e.pageX - (parseInt(jQuery(this).offset().left)-25));

}).mouseout(function() {

//Put back the title attribute's value
$(this).attr('title',$('.tipBody').html());

//Remove the appended tooltip template
$(this).children('div#tooltip').remove();

});

Reply
paolo
Fri, 23rd March 2012
Hi,
I'm trying to implement this on a multiple select, is this possible?
<select multiple id="select1">
<option>Option 1</option>
<option>Option 2</option>
<option >Option 3</option>
</select>

Thanks,
Paolo Reply
amko
Sat, 24th March 2012
Great plugin! I'm having an issue though. I have my link wrapped in a div with position:relative and it's moving the tooltip really far from the trigger point. Any suggestions? Reply
Kevin Liew Admin
Mon, 26th March 2012
Ok, i got what you mean, something i've overlooked. Try to change line 21 in the javascript:
$(this).append to $(body).append Reply
Michael Helwig
Tue, 8th May 2012
Thanks for the code. When modifying it according to your comment I also had to change line 43 from
$(this).children( ...
to
$(body).children( ...
to remove the tooltip properly on fade out. Reply
Shawn Christenson
Wed, 6th March 2013
I found an even better way around this, which was to replace $(this).append and $(this).children with $('#div_id_its_inside').append Reply
Webmaster, fr
Thu, 7th June 2012
Thanks. But it's not working with area maps.
$('map').mouseover(function(e) { = WORKING
$('area').mouseover(function(e) { = NOT WORKING

If anyone could help ?
Thanks Reply
Joya
Sun, 17th June 2012
It's cool. However it works abnormally in IE(competibility views) when you quickly move your mouse pointer over the anchor words back and forth. Reply
ramkumar
Thu, 12th July 2012
Not working in ie svg.
Reply
Ramesh
Tue, 21st August 2012
thanks,its very useful for me Reply
Jason S
Sun, 2nd September 2012
Thank you for sharing your code. I'm having a problem with the positioning however. My <a> is inside a table cell. I've tried making the cell and the table itself position: relative, but nothing works. The tooltip appears down and right of the anchor. What am I missing? Reply
Kevin Liew Admin
Mon, 3rd September 2012
You can try to adjust the position manually by adding margin to #tootip Reply
Jason S
Fri, 14th September 2012
I've added the following code to #tooltip: margin: -250px 0 0 -100px; and it's much closer to where it should be. The distance is still off between Firefox, IE7, and Chrome. Any other ideas? Reply
Kundan
Wed, 20th February 2013
thanks for sharing .it very useful to me. Reply
Michael
Fri, 5th April 2013
Is it possible to put a link or AJAX call in the tooltip script? I would like to use the tooltip to display data from a database. Thanks and great, great, script! I love the simplicity and ease of use. Reply
Kevin Admin
Fri, 5th April 2013
Hi Michael, unfortunately, no... but if you want something like that, you can use: http://craigsworks.com/projects/qtip2/ Reply
lukasaa
Tue, 16th July 2013
very helpful, I'm an absolute beginner in JavaScript, but it was comprehensive even for me! Very clear and brief coding. The comments in the code veeery useful as well!
Simply great!

Thanx a lot Reply
Mohd Navaid
Tue, 23rd July 2013
Hi,

Thanks for the script but I am having problem in IE, it seems $(this).append is not working in IE8.
Please help me with this.

Thanks in advance Reply
sabeel
Tue, 10th December 2013
Itn't working for me. Please help

'<a rel="tooltip" title="Testing odd"><img src=' + '"@Url.Content("~/Images/info.png")"' + 'id="imginfo_license" alt="" /></a> Reply
Dennis
Mon, 31st March 2014
Hey guys really superb sharing i would like your blog visit again. Reply
Akino
Wed, 23rd July 2014
It's amazing... simple e useful Reply

Leave a Comment

Please keep in mind that comments are moderated and rel="nofollow" is in use. You can use [code][/code] if you want to write codes. Don't spam us :) Thanks!

Advertisement