429

Is there a way of finding the absolute position of an element, i.e. relative to the start of the window, using jQuery?

1
  • If you need the position:absolute; value of the child, use JQuery's .position()
    – Avatar
    Mar 17, 2022 at 12:22

3 Answers 3

696

.offset() will return the offset position of an element as a simple object, eg:

var position = $(element).offset(); // position = { left: 42, top: 567 }

You can use this return value to position other elements at the same spot:

$(anotherElement).css(position)
8
  • 97
    I always forget this one, and find your post again when I google :p
    – Aren
    Jun 30, 2011 at 23:14
  • 16
    This does not always seem to return the absolute position due to differences in borders etc.
    – Tom
    Jul 5, 2011 at 12:07
  • 10
    I'm using chrome and the offset() does not return the proper top coordinate. It returns about 300 pixels more than the top coordinate of the element in the document instead. Why??
    – SoLoGHoST
    Apr 23, 2012 at 5:49
  • 1
    chrome, FF and IE are giving different results :( Apr 10, 2013 at 7:02
  • 3
    @Aren I always forget this one and find your comment amusing every time :)
    – Alex
    Sep 2, 2014 at 12:38
221

Note that $(element).offset() tells you the position of an element relative to the document. This works great in most circumstances, but in the case of position:fixed you can get unexpected results.

If your document is longer than the viewport and you have scrolled vertically toward the bottom of the document, then your position:fixed element's offset() value will be greater than the expected value by the amount you have scrolled.

If you are looking for a value relative to the viewport (window), rather than the document on a position:fixed element, you can subtract the document's scrollTop() value from the fixed element's offset().top value. Example: $("#el").offset().top - $(document).scrollTop()

If the position:fixed element's offset parent is the document, you want to read parseInt($.css('top')) instead.

2
  • 9
    I was looking exactly for this! For the noob like me: the value to be subtracted is $(document).scrollTop() Aug 20, 2014 at 14:56
  • 4
    Awesome! This should be the top answer! Dec 20, 2014 at 1:44
1

In case the element is not visible $(element).offset(); and $(element).position(); retun 0 for both top and left instead of the elements real value.

i had to use

parseInt($(element).css("top"))
parseInt($(element).css("left"))

to return the needed information. the element has position: absolute;.

Not the answer you're looking for? Browse other questions tagged or ask your own question.