Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript/jQuery - offsetLeft and offsetTop

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.

like image 989
BuddyJoe Avatar asked Nov 27 '22 23:11

BuddyJoe


2 Answers

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

like image 147
Svante Svenson Avatar answered Dec 10 '22 03:12

Svante Svenson


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 );
});
like image 35
nickohrn Avatar answered Dec 10 '22 02:12

nickohrn