Easy jQuery Tooltip

Pretty basic post here. At work the other day, I needed a quick tooltip and didn’t want to install an over-burdened jQuery plugin, so I whipped this up. The usage is pretty basic, in that it uses the the “alt” attribute for the tooltip text. You can change the “x/y” variables to control the position offset from the mouse. Customize the styling in your own stylesheet. A sample is provided below.


var tooltips = { //tooltip to show Alt text
init:function(selector){
x = 10;
y = 10;

jQuery(selector).hover(function(e){
var tip = jQuery(this).attr('alt');
jQuery("body").append("

"+ tip +"

");
jQuery("#btooltip").css("top",(e.pageY - xOffset) + "px").css("left",(e.pageX + yOffset) + "px").fadeIn(250);

}, function(e){ jQuery('#btooltip').remove(); });

jQuery(selector).mousemove(function(e){

jQuery(selector).css("top",(e.pageY - xOffset) + "px").css("left",(e.pageX + yOffset) + "px");

});

}
}

jQuery(document).ready(function(){
//init tooltips
tooltips.init(jquerySelectorHere); //use any kind of normal jQuery selector.
});

You also need some simple styling. The only thing required is for display to be none for the fade-in to work. Here’s a sample.


#btooltip{
display:none;
background-color:#cc0000;
border:2px solid #000;
padding:5px;
}