views:

8475

answers:

3

When hovering over a span I would like to get the offsetLeft and offsetTop values so I can make something hover near it. When I do this I get 0 for both values.

What is a better way to tackle this? I am using jQuery.

Assume I am starting with (looped by server-side scripting):

<span onmouseover="hoverNearMe(this.offsetLeft,this.offsetTop);">some username</span><br />

FINAL THOUGHTS:
I'm giving the the answer rep out based on "code leverage"/DRY. The longer function you could use over and over in your own js library. The second short answer however is 100% correct too.

Thanks.

+3  A: 

I think you should be able to do this:

HTML

<span class="get-close-to">some username</span><br />

jQuery

jQuery('.get-close-to').hover(function() {
    var offset = jQuery(this).css('offset');
    alert( 'Left: ' + offset.left + '\nTop: ' + offset.top );
});
nickohrn
does this handle the whole "cumulative" offset thing?
tyndall
+1 for creativity.
tyndall
@Bruno - I think it should. It gets the offset relative to the document.
nickohrn
+8  A: 

$(this).offset().left and $(this).offset().top

svinto
A: 

Why do you need server-side scripting?

try this:

 var positionImg = function(e) {
  $(this).offset();
 var zoomCntnrPos = $(this).offset.top;
   if (zoomCntnrPos >= maxBottomVPos)
   {
     tPosX = e.pageX;
        tPosY = e.pageY +20;
    }
   else if (zoomCntnrPos <= maxTopVPos){
          tPosX = e.pageX;
        tPosY = e.pageY +40;
    }
   else
    {
     tPosX = e.pageX;
        tPosY = e.pageY -100;  
    }
  $zoomContainer.css({top: tPosY, left: tPosX});
 };
adardesign
So you never use server-side? PHP even? Can you explain your code? seems a little bloated.
tyndall
this is just part of the code. here you are positioning the hover via javaScript and position via the mousemove event event.pageX and event.pageY.
adardesign