1

I am using jQuery offset().top to calculate a hyperlink's pixels from the top of the document window so that when hovered, a tooltip can appear above it.

By default, the tooltip's css has an absolute position of top 0 and left 0. When the link is hovered, it calculates it's position from the top of the document and uses that as the css top position for the tooltip.

The problem is that on some pages, offset is calculating the link's position perfectly, and on others, it is around 50 pixels too many. I can't figure out why.

$(".tiptrigger").mouseenter(function() { 
    var s_id = $(this).attr('id');
    var calc = $(this).offset().top; 
    $("#tip-"+s_id).css({"margin-top": calc+"px"});
});
MultiDev
  • 10,389
  • 24
  • 81
  • 148

2 Answers2

0

.offset() has this limitation:

Note: jQuery does not support getting the offset coordinates of hidden elements or accounting for borders, margins, or padding set on the body element.

So your jQuery is probably correct but if you have some padding/margin on your body, you will experience an incorrect offset. Either remove it or include it in your calculation:

var bodyOffset = $('body').css("margin-top") + $('body').css('padding-top') + $('body').css('border-top');
var calc = $(this).offset().top + bodyOffset; 
ediblecode
  • 11,701
  • 19
  • 68
  • 116
0

Instead of absolute try to use fixed for your popup element. Than offset().top should work if you don't have any unnecessary padding applied to body

If still inaccurate instead of .offset().top give a chance to https://developer.mozilla.org/en-US/docs/Web/API/element.getBoundingClientRect

Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313