tooltip relative to mouse coordinates

tooltip

by Oliver Kelso

HTML

<div class="hover bar1">1</div>
<div class="hover bar2">2</div>
<div id="tooltip"><span>test</span></div>

CSS

.hover
{
  width: 40px;
  height: 80px;
  background: red;
  position: absolute;
  bottom: 200px;
  left: 200px;
  text-align: center;
  color: #fff;
  padding-top: 10px;
}

.bar2
{
  bottom: 200px;
  left: 250px;
  height: 100px;
}

#tooltip
{
  width: 200px;
  position: absolute;
  display:none;
  border: 1px solid blue;
  text-align: center;
}

span
{
  border: 1px green solid;
}

JavaScript

var mouseX;
var mouseY;
$(document).mousemove( function(e) {
   // mouse coordinates
   mouseX = e.pageX; 
   mouseY = e.pageY;

});  

// hover
$(".hover").mouseover(function(){
    // populate tooltip string
    $('#tooltip span').html(stringValue($(this)));
    
    // show tooltip
    $('#tooltip').stop(false, true).fadeIn(1);

    // position tooltip relative to mouse coordinates
    $(this).mousemove(function() {
      $('#tooltip').css({'top':mouseY - 100,'left':mouseX - 100});   
    }); 
 }).mouseout(function() {
  // hide tooltip
  $('#tooltip').stop(false, true).fadeOut('slow');
});

// perform check and return string
function stringValue(e) {
  if (e.hasClass('bar1')) {
    return 'Bar 1';
  }
  else if (e.hasClass('bar2')) {
    return 'Bar 2 longer string';
  }
}