views:

276

answers:

2

HTML:

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

jQuery:

xOffset = $('#tooltip-1').height() + 10;
yOffset = -30 ;  
$("a[rel=tooltip-1]").hover(function(e){             
 this.t = this.attr("href");
 $("body").append("<p id='tooltip'>"+ this.t +"</p>");
 $("#tooltip")
  .css("top",(e.pageY - xOffset) + "px")
  .css("left",(e.pageX + yOffset) + "px")
  .fadeIn("fast");  
},
function(){
 this.t = "";
 $("#tooltip").remove();
}); 
$("a[rel=tooltip-1]").mousemove(function(e){
 $("#tooltip-1")
  .css("top",(e.pageY - xOffset) + "px")
  .css("left",(e.pageX + yOffset) + "px");
});

Two Issues:

  1. Tooltip div (#tooltip-1) doesn't hide on mouseout.
  2. Since the tooltip div will always have the same ID as REL, I'd like to modify the above jQuery so that it takes target DIV ID automatically.

Thanks in advance for your help.

+2  A: 
this.t = this.attr("href");

this is a DOM node, not a jQuery wrapper: there is no attr() method.

(I also don't see why you're writing to an expando t property on the node. You don't seem to use it anywhere else.)

$("body").append("<p id='tooltip'>"+ this.t +"</p>");

Try not to make HTML strings from plain text. Any & or < characters in t and your HTML is messed up. (This is an easy way to let cross-site-scripting security holes in.) Use text() to set plain text content in an element instead.

(Although, I'm not sure why you're writing the # attribute value into the tooltip. Are you trying to read the HTML of the tooltip div and copy it into the p? Why not just use the tooltip div itself?)

Tooltip div (#tooltip-1) doesn't hide on mouseout.

It doesn't hide/show at all, your script isn't touching it anywhere.

Since the tooltip div will always have the same ID as REL

How about putting this information in the href fragment, rather than abusing rel? Then the link actually points to the place it's going to pop up.

eg. something like:

<a href="#footnote1" class="tooltip">?</a>

<div id="footnote1" style="background: yellow; width: 10em;">
    Hello!
</div>

$('.tooltip').each(function() {
    var tip= $(this.hash);
    var dx= -30, dy= -tip.height()-10;
    tip.css('position', 'absolute');
    tip.hide();

    function position(e) {
        tip.css('left', e.pageX+dx+'px').css('top', e.pageY+dy+'px');
    }
    $(this).mousemove(position);

    $(this).hover(function(e) {
        position(e);
        tip.show('fast');
    }, function(e) {
        tip.hide('fast');
    });
});

(Or just use one of the many already-existing jQuery tooltip plugins.)

bobince
+2  A: 

Just to add to the accepted answer: there is a much better alternative to jQuery's tooltips called jQuery tools.

Check out the demo.

HeavyWave