jQuery: sticky tooltip

In the 13th Chapter of jQuery Cookbook, Nathan Smith presents an elegant solution to achieve the effect of sticky tooltips. In practice, this effect is achieved by adjusting the tooltip position on the screen while keeping track of mouse movements. The jQuery code is made up of three parts. First, the tooltip container is inserted into the page and hidden. Second, when a user moves his mouse over and out of a link, the tooltip itself is first revealed and then hidden again. Third, using the mousemove event, we get the coordinates of the mouse pointer and we perform some calculation using the body element dimensions and the tooltip dimensions as references. First, we need some styles for our tooltip:

#tooltip-wrapper {
 position: absolute;
 width: 158px;
 height: 88px;
 background: url(tip.png) no-repeat;
 line-height: 88px;
 text-align: center;
 display: none;
 font-size: small;
}

The tooltip is hidden by default and absolutely positioned. Then we can use jQuery (I've adapted the original code of Nathan for this example):

 var tooltipWrapper = '<div id="tooltip-wrapper"><div id="tooltip-inner"></div></div>';
  $('body').append(tooltipWrapper);
  
  var tooltipTitle;
  var tooltipInner = $('#tooltip-inner');
  
  $('a.tooltip').hover(function() {
  
  
    if($(this).attr('title')) {
    
      tooltipTitle = $(this).attr('title');
      $(this).attr('title', '');
    
    
    }
    
    tooltipInner.html(tooltipTitle);
    $('#tooltip-wrapper').show();
    
  
  
  
  }, function() {
  
  
    $('#tooltip-wrapper').hide();
    tooltipInner.html('');
    
    if(tooltipTitle) {
    
      $(this).attr('title', tooltipTitle);
    
    
    }
  
  
  }).mousemove(function(e) {
  
  
    var x = e.pageX;
    var y = e.pageY;
    
    var tx = $('#tooltip-wrapper').outerWidth();
    var ty = $('#tooltip-wrapper').outerHeight();
    
    var bodyX = $('body').outerWidth();
    var bodyY = $('body').outerHeight();
    
    $('#tooltip-wrapper').css({
      top: y + ty > bodyY ? y - ty : y,
      left: x + tx > bodyX ? x - tx - 10 : x + 15
    });
  
  
  
});

As you will see, the final effect is really sticky.

Demo

Live demo

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.