Here is a very simple tooltip script I wrote a while back. There are tons of tooltip scripts out there, and most are much more complex than mine. I’ve decided to post it anyway, as perhaps it will come in handy for someone.
This simple tooltip script uses event targeting and pulls the tip from the title attribute of any element. The tooltip content is stored using the jQuery’s data api. This script works great for creating styled tooltips. It keeps the markup clean as it doesn’t add any new elements. It is not, however, the proper choice if any html is needed in the tooltip. For more robust tooltips, there are plenty of plugins available in the jQuery plugin repository.
Demo: http://jsfiddle.net/McWatt/PAUXv/
First, add the class “tooltip” and a “title” attribute with a value that contains your tooltip.
<a href="http://www.erikphipps.com" class="tooltip" title="Go to my home page!">Go to my homepage!</a>
Add the following javascript to a jQuery document ready function.
$('body').delegate('.tooltip', 'mouseover mouseout', function(event) {
//cache the event and title content
var $target = $(event.target),
tipTitle = $target.attr('title');
//if the title is not empty, fill the data with the title's content
if (tipTitle != '') {
$target.data('tipTitleData', tipTitle);
}
//empty title attribute so browser tooltip doesn't appear
$target.attr('title', '');
//build and show the tooltip on mouseover
if (event.type == 'mouseover') {
//stuff the tooltip html into a variable
var tipHtml = '<div class="tooltip-content"><p>' + $target.data('tipTitleData') + '</p></div>';
//append the tooltip html to body and position
$(tipHtml).appendTo('body').css({ left: event.pageX + 'px', top: (event.pageY + 12) + 'px' }).show();
}
//remove the tooltip on mouseout
if (event.type == 'mouseout') {
$('.tooltip-content').remove();
}
});
The only thing left, is to make it add some styling to make it presentable.
.tooltip{
cursor:pointer;
}
.tooltip:hover{
text-decoration:underline;
}
.tooltip-content{
position:absolute;
width:300px;
box-shadow:0 0 8px #888888;
border-radius: 2px;
background-color:White;
border:1px solid #333;
padding:12px;
display:none;
line-height:1.5;
}