ToolTips with jQuery

Sometimes, some additional information in a text can be quite useful. To do this in a website, you can use a fancy tooltip that appears, when hovering a certain word with the mouse. This post will demonstrate, how this can be done, using the great jQuery toolkit.
HTML Part
First, we have to specify the keyword and the respective help text. We use a span to wrap the keyword and add a CSS class. The help text will be carried in the title attribute:
<span class="keyword"
title="jQuery is a JavaScript library that
simplifies how to traverse HTML,
handle events, perform animations,
and add AJAX">
<em>jQuery</em></span>.
JavaScript Part: The structure
Within the DOM ready function, which is called after the DOM tree of tyour website is fully loaded, we place our code. First we need event listener for hovering the keyword. We need both to detect hover and unhover.
$(document).ready(function(){
$('.keyword').hover(
function(e){...},
function(){...}
});
Hover
Now we have a closer look at the first inner function from above. We get the help text from the span element and build a div element that wil be working as the help text holder. Eventually, we add some effects.
function(e){
if(this.title){
//to avoid the normal title text
this.tip = this.title;
this.title = "";
//getting the position of the target keyword
var mywidth = $(this).width();
var myheight = $(this).height();
var position = $(this).position();
$(this).addClass('hoverDiv');
$(this).append('
<div class="tooltip">
<div class="innerTip">'+this.tip+'</div>
<div class="arrow" style="display:none">
</div></div>
');
//now comes the effect part
$(".tooltip").css({
top: position.top,left: position.left
});
$(".tooltip").show().css({
opacity:0
})
$(".tooltip").animate({
opacity:.9,
top: position.top-$(".tooltip").height()
},250,function(){
$(".arrow").slideDown();
});
}
}
Unhover
Now we have to define the unhover part. First, we remove the hoverDiv class and then we remove the tooltip div and its children, if any.
function() {
$(this).removeClass('hoverDiv');
$('.tooltip').children().remove();
$('.tooltip').remove();
}
CSS Part
At last, we need the CSS to style our tooltip
.tooltip, .tooltip .arrow{
width:180px;
}
.tooltip {
position:absolute;display:none;
}
.tooltip .arrow{
background-image:url(feature-arrow.gif);
background-repeat: no-repeat;
background-position: 20px top;height:16px;
}
.innerTip {
color:#ffffff;
background-color:#ff7200;
padding:10px;
white-space:normal;
}




