How to find the element position relative to it's parent to scroll it visible

ariel picture ariel · Apr 12, 2014 · Viewed 8.5k times · Source

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.

Answer

ariel picture ariel · Apr 12, 2014

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});