Create a Simple CSS + Javascript Tooltip with jQuery

Written by Kevin Liew on 17 Mar 2009
198,050 Views • Tutorials

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>
Demo Download
Join the discussion

Comments will be moderated and rel="nofollow" will be added to all links. You can wrap your coding with [code][/code] to make use of built-in syntax highlighter.

78 comments
sanjeeva 13 years ago
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 13 years ago
very nice
Reply
IIT Bakar 13 years ago
Thats something interesting. I am trying to implement this at the footer at my webstire <a href="http://iitbakar.com "> iitbakar </a>
Reply
sAnToSh 13 years ago
Thanks Kevin, its very useful
Reply
ashraf ali 13 years ago
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 13 years ago
This tutorial won't go that far. But there are plenty of tooltips plugins out there that support ajax feature.
Reply
thomas 13 years ago
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 13 years ago
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 12 years ago
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 12 years ago
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 12 years ago
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 12 years ago
can you post any exemple?
Reply
Milos 12 years ago
this $('#tooltip').fadeIn('500'); not work....
Reply
Rajesh Saran 12 years ago
use this:- $('#tooltip').fadeIn(5000);
Reply
gubs* 12 years ago
Hi...I tried using this code but it seems that it's not working with IE7...any advice? Thanks.
Reply
fstab 12 years ago
hey, i cant run this tooltip over any input field, its ignorin input selector etc. any solution pls? thank you
Reply
gwledig 12 years ago
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 12 years ago
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 12 years ago
Interesting stuff here :) Thanks..
Reply