3

jQuery position() returns

the current coordinates of the first element in the set of matched elements, relative to the offset parent.

So, scrolling the parent is not supposed to change the position, right?

The result I'm getting in this fiddle is that after scrolling the parent by 100px, the position().top of a child element changes by 100.

position().top before scroll 1880, after scroll 1780

Why?

harpo
  • 41,820
  • 13
  • 96
  • 131
  • Because `$debug.offsetParent()` is `$('html')`. – Blender Dec 19 '13 at 20:29
  • the position is relative to the parent element. The parent element in this case is the scrollable div #box. As you scroll closer to the anchored element, it is closer and closer to the top of the box, resulting in a smaller and smaller top position. – Kevin B Dec 19 '13 at 20:33
  • 1
    if you remove overflow, then it will not change. But it makes sense for it to change since the anchored element is getting closer to the top because the div is scrollable due to overflow – Huangism Dec 19 '13 at 20:35
  • That makes sense, I guess I just remember the behavior wrong. So how do I get its position irrespective of scrolling? I guess I'd need a wrapper element for that. – harpo Dec 19 '13 at 20:39
  • 1
    You can just add the parent element's scroll position to the result. – JJJ Dec 19 '13 at 20:41

1 Answers1

0

To answer the question in your comments, just add the box's scrollTop to the anchored element's position.

http://jsfiddle.net/5xqEL/17/

var $box = $('#box'),
    $anchored = $('#anchored'),
    $debug = $('#debug');

$debug.text('position().top before scroll ' + ($anchored.position().top + $box.scrollTop()));

$box.animate({
    scrollTop: 100
}).promise().then(function () {
    $debug.text($debug.text() + ', after scroll ' + ($anchored.position().top + $box.scrollTop()));
});
Nate
  • 4,718
  • 2
  • 25
  • 26