tjcss
tjcss

Reputation: 860

jQuery /CSS - get position of relative element, position tooltip accordingly

I have a map showing various locations which when hovered over will show a tooltip next to the cursor revealing information regarding that location.

The map is a background image of the main ul id="map", with each location being a li. The location is positioned by css using top and left.

The #map is positioned relative and the tooltips are positioned absolutely.

The markup I have is as follows:

<ul id="map">
<li><a href="#" class="harewood tip_trigger"><img src="images/marker.gif" width="12" height="12" alt="" /> <span class="tip"><img src="images/thumb.jpg" width="143" height="107" alt="" />Title<br />Click marker for details</span></a></li>

I can show and hide the .tip span using jQuery no problem, but I'd like to get the position of the parent .tip_trigger, and offset the tooltip from the cursor by, say, 10px.

How would I amend the jquery code below?

$(document).ready(function() {
//Tooltips
$(".tip_trigger").hover(function(){

var pos = $("#map").position();  
var width = $(".tip").width();

    tip = $(this).find('.tip');
    tip.show(); //Show tooltip
    tip.css({"left": (pos.left + width) + "px","top":pos.top + "px" });

}, function() {
    tip.hide(); //Hide tooltip
});
});

I've been messing with this for a while, have tried jquery documentation and just can't figure it out.

Upvotes: 4

Views: 5167

Answers (2)

tmaximini
tmaximini

Reputation: 8503

algiecas is right, I usually add an extra step with each

like this:

$(document).ready(function() {
//Tooltips
$(".tip_trigger").each(function () {
 $(this).hover(function(){

 // assuming you give the image the class marker
 var pos = $(this).find('marker').position();  

    tip = $(this).find('.tip');
    var width = tip.width();
    tip.show(); //Show tooltip
    tip.css({"left": (pos.left + width) + "px","top":pos.top + "px" });

 }, function() {
    tip.hide(); //Hide tooltip
 });


});
});

Upvotes: 2

algiecas
algiecas

Reputation: 2128

You should probably use the position of the .tip_trigger, not the whole #map

var pos = $(this).position(); 

Upvotes: 1

Related Questions