jQuery animated tooltips

In this post I'm going to show you how to implement some basic animations on jQuery tooltips. First of all, all the tooltips we're about to create will be in the form of span elements, stylized by a CSS class called tooltip. Here's the relevant CSS code:

span.tooltip {
  
  display: block;
  width: 0px;
  padding: 0px;
  background: yellow;
  border: 1px solid orange;
  font-size: small;
  -moz-border-radius: 6px;
  border-radius: 6px;
  position: absolute;
  
}

Two things are important here: element's dimensions are zeroed so that we can play with this in order to animate our tooltips; we're using absolute positioning to put our tooltips just near the link they belong to. And here's the jQuery code:

$(document).ready(function() {
 
 
 $('p a').each(function() {
  
  var $a = $(this);
  var title = $a.attr('title');
  $a.removeAttr('title');
  
  var tooltip = $('<span class="tooltip"/>');
  
  tooltip.text(title);
  
  tooltip.appendTo('body').hide();
  
  $a.mouseover(function(e) {
   
   
   var top = e.pageY;
   var left = e.pageX;
   
   tooltip.css({
    
    
    display: 'block',
    top: top + 5,
    left: left + 5
    
    
   }).animate({
   
   
       width: '150px',
    padding: '5px'
   
   }, 'slow');
   
   
  });
  
  $a.mouseout(function() {
   
   tooltip.animate({
   
       width: '0px',
       padding: '0px',
       visibility: 'hide'
   
   }, 'slow');
   
  });
  
  
 });
 
 
});

We're using the animate() method on the mouseover and mouseout events. When a user hovers a link with his mouse, the tooltip is first positioned and then grows in dimensions. Finally, when the user moves his mouse away from the link, our tooltip shrinks and then disappears. You can see the final result here.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.