How to make a tooltip with CSS and jQuery

Posted on 17th of July 2009 by Ahmed Khusaam

Lets open this blog with this little neat trick shall we :)

“Tooltip” is one of those small yet effective at times things on a website. There is also a great plugin for jQuery at http://jquery.bassistance.de/tooltip/demo/ which does the work for you. But since its not that hard of a thing to make, i will try and demonstrate how to make one :)

I will display the text on the “title” attribute of links as the tooltip. First to grab that text

<script src="jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">// <![CDATA[
//document ready
$(function() {
//grabs the value in "title"
var thetext = $(this).attr("title");
});
// ]]></script>

Now for the magical mouse events

<script src="jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/jscript">// <![CDATA[
//document ready
$(function() {
//links as each
$("#links a").each(function() {
//grabs the value in "title"
var thetext = $(this).attr("title");

//when the mouse goes over the desired link
$(this).mouseover(function() {
//this will append to the tooltip div to the body with the text
$("body").append("
<div class='tooltip'>" + thetext + "</div>
");

//this removes the attr "title" from the link, when you keep your mouse over the link for a while it will display the title as it is the default behaviour of the browser, so lets remove it, it can get a bit annoying
$(this).removeAttr("title");

//when the mouse moves follow it
}).mousemove(function(e) {
//gets the mouse location and 20 to that value for doing this makes it look a bit better, but its your call here :)
var leftlocation = e.pageX - 20;
var toplocation = e.pageY + 20;

//update the css as the mouse moves
$(".tooltip").css({left: leftlocation + "px", top: toplocation + "px"});

//when the mouse goes away from the link, hide the tooltip
}).mouseout(function() {
$(".tooltip").fadeOut("slow").remove();

});
});
});
// ]]></script>

now for the css. There isn much css to this just the following couple of lines

.tooltip {
position:absolute; /* this is the really important one*/
width:200px; /* the width of your choice */
}

and ofcause more styling for the tooltip to better suit your layout and recommendation :)
hope this one helped you out, if i’ve made any mistake in the code or any feedback, please leave in the comments :)

DEMO

cheers :)

Tags: , , , , ,

Enjoyed this post? Please Share

comments / feedback

your comment