views:

355

answers:

4

HTML:

<a href="#" rel="tooltip">Open Tooltip</a>
<div id="tooltip">Tooltip Content</div>

I checked out some tooltip plugins but my requirement is a really basic tooltip that shows a hidden div on hover. All plugins either have too many advanced options that I don't require and have already styled tooltips that might be difficult to modify.

I'd appreciate any help. Thanks.

+6  A: 

You can roll your own.

My suggestion is just to store the clientX and clientY properties of the mouse event object that is passed to the onmouseover event handler. Then set the CSS onscreen position ( left, top ) of the hidden div to those coordinates and you're golden. Make sure that the div's position CSS property is absolute

A quick untested example just to give you an idea:

$( '[rel="tooltip"]' ).hover( function(e) {
   var x = e.clientX;
   var y = e.clientY;
   _div.css( { top: y, left: x, position: 'absolute' } )
       .fadeIn();
}, function() {
    _div.fadeOut();
} );
Jacob Relkin
Works great, thanks. Just the positioning is incorrect; it opens at the bottom-right instead I want it at top-right. I guess I have to find the height of #tooltip and set it as top:-[height], no?
Nimbuz
Try `clientX` and `clientY` instead of `pageX` and `pageY`.
Jacob Relkin
A: 
$('a[rel=tooltip]').bind('mouseover',function(e){
  e=e?e:window.event;
  $('#tooltip').css({
    position:'absolute',
    top:e.pageY,
   left:e.pageX
  });
})
markcial
+2  A: 

Here's the code for a really simple CSS tooltip that I use:

CSS:

  .name a:hover {
background:#ffffff; 
text-decoration:none;
}

.name a.tooltip span {
display:none; 
padding:5px; 
margin-left:108px; 
width:100px;
}

.name a.tooltip:hover span {
display:inline; 
position:absolute; 
background:#ffffff; 
border:1px solid #cccccc; 
color:#000000;
top:5px;
left:-15px;
}

The top and left properties make it float above the text. Change this to position it where you like. Also, change display:inline; to display:block; if you want it to behave like a normal div for positioning.

HTML:

     <div class="name">
       Name 
        <a class="tooltip" href="#">
          Tooltip
             <span>
               Tooltip text here.
             </span>
        </a>.
     </div>
Kyle Sevenoaks
A: 

if you just wanna show the div on the mouse hover use:

$('a[rel="tooltip"]').hover(
   function(){ $('#tooltip').show() }, //or maybe use fadeIn() instead of .show() 
   function(){ $('#tooltip').hide() }
)

you can integrate markcial's solution in the functions to make the tooltip div appear next to your cursor.

would look like this

$('a[rel="tooltip"]').hover(
   function(e){ $('#tooltip').css({ position:'absolute', top:e.pageY, left:e.pageX }).show() }, //or maybe use fadeIn() instead of .show() 
   function(){ $('#tooltip').hide() }
)
meo