10

I have a div with lots of elements inside it, and overflow: scroll. Then i want to be able to scroll the nth element in view. I set a fiddle to it, but I can't find the expression to get the element position relative to the parent.

http://jsfiddle.net/bortao/NXcTK/

I tried both el.position().top and el.offset().top but they don't work.

Note: h / 2 is so the element is positioned in the middle of the div.

ariel
  • 15,620
  • 12
  • 61
  • 73
  • The problem is `cont.animate({scrollTop: (elementTop + h)});`. You want to subtract `h`, not add it. Looks like you may also want to add half the height of the element as well. So, `cont.animate({scrollTop: (elementTop - h)});`. P.S. `el.position().top` is correct in this case. – Bryan Downing Apr 11 '14 at 23:35
  • @BryanDowning i did this and now it works but only when the scroll bar is at the initial position. – ariel Apr 11 '14 at 23:38

2 Answers2

9

Ok got it... just had to add the current scrollTop() to it.

http://jsfiddle.net/bortao/NXcTK/1/

var cont = $("#container");
var el = $(cont[0].children[index]);
var h = cont.height() / 2;
var elementTop = el.position().top;
var pos = cont.scrollTop() + elementTop - h;
cont.animate({scrollTop: pos});
ariel
  • 15,620
  • 12
  • 61
  • 73
  • This answer assumes that the offsetParent of the div you're scrolling to is the div that's overflowing. See @dlauzon's answer for an answer that will always work. – Skeets Sep 25 '18 at 09:19
8

For a more stable solution that would work regardless of the offsetParent (which can change with the value of the position attribute), I would use offset() instead of position():

cont.animate({scrollTop: cont.scrollTop() + (el.offset().top - cont.offset().top)});
dlauzon
  • 1,241
  • 16
  • 23