3

I am using the $.position over the same selector and I am getting different results for the top value.

The problem might be in getting the position of the selector inside the scrolling div. That's why I am using $.position instead of $.offset, but it seems I am doing something wrong.

You can try it clicking multiple times on the the text "Get Position" at my fiddle: http://jsfiddle.net/FgftM/1/

Once the div has scrolled to look for the selector, clicking on the "Get Position" again shouldn't do anything because I am already on the selector position.

The resulting position values showed at the bottom.

To clarify the structure of the page, here's an sketch: enter image description here

Original fiddle: http://jsfiddle.net/BtZQE/16/

Alvaro
  • 40,778
  • 30
  • 164
  • 336

2 Answers2

2

I believe what you want to do is set position: relative on #content. That way the position is calculated in relation to the container instead of the overall page.

http://jsfiddle.net/FgftM/6/

EDIT: After some clarification, you still need the position: relative but you also need to add in the current scrollTop value:

http://jsfiddle.net/FgftM/8/

var top = dest.top + $('#content').scrollTop();
James Montagne
  • 77,516
  • 14
  • 110
  • 130
  • But still not solving my problem. It still showing 2 values (500 and 0) for the same selector. What I am looking for is just to stay in the selector If I am already on it. Everytime I click on the link I should be moved to the 2nd box, the red one. – Alvaro Jun 26 '13 at 16:47
  • @Steve Okay, updated answer. You just need to add in the current `scrollTop` to the element's current position within the container. – James Montagne Jun 26 '13 at 16:54
1

@James has a correct solution, but to provide additional clarification: position is relative to the offsetParent, which is not necessarily the element's immediate ancestor.

For the algorithm used to determine an element's offsetParent, see http://www.w3.org/TR/cssom-view/#offset-attributes

The relevant point here, as James pointed out, is that the offsetParent's position property must be something other than static, and if there is no such ancestor, the offsetParent will be the body element

Todd Gibson
  • 1,005
  • 7
  • 16