ariel ariel - 1 year ago 40
jQuery Question

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

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.

I tried both
but they don't work.

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

Answer Source

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

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});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download