Ryan Ryan - 6 months ago 14
Javascript Question

How to get tooltips working in jQuery?

I'm a JQ noob. I am trying to get the

title
into a little tooltip, my finy fiddle is here:

http://jsfiddle.net/q52954vc/1/

I seem to also have some error in my jQuery code, but not sure where that is.
Here's the code:

$(document).ready(function () {

$('.hoverAble').hover(function(){

var tip = "RRR "+$(this).attr('title');

$('#myToolTip').html(tip).fadeIn();
//$('#tooltip').css({ top : $('#link').offset().top + 10 + 'px' });

}, function() {

$('#myToolTip').fadeOut();

}

});


Please help me get this working so that the tooltip appears next to the mouse pointer.

Answer

Updated your Fiddle again. Adjustments were to add CSS for the text:

.hoverAble
{
  display:inline;
}

so the div with the text has not 100% width as previously. I've added the jquery

    var tPos = $(this).width() + 20;
    $('#myToolTip').css({"left" : tPos});

before the tooltip fades in so the position of the tooltip is to the left of the div with the width of the div and added 20px as value for left.

Update: For the question in the comment if it's possible not to display the title on hover - just updated the Fiddle with the following adjustments: in case you don't need to have a title attribute on the <div> and only used it to store the copy for the tooltip, just change it to a data-attribute like data-title:

<div class="hoverAble" data-title="I am blah!">sdddd</div>

and adjust the copy for the tooltip to retrieve the value of the data-title attribute:

var tip = "RRR " + $(this).data('title');

In case you really need the title attribute on the <div>, it's possible to remove it on hover and add it again with the value of the data-title attribute when the tooltip faded out.

For reference: http://api.jquery.com/data/