How to find the position of an element relative to the parent, to scroll it

I have a div with a lot of elements inside it and overflow: scroll. Then I want to be able to scroll the nth element in the field of view. I gave him a violin, but I can’t find an expression to get the position of the element relative to the parent.

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

I tried both el.position().top, and el.offset().top, but they do not work.

Note: h / 2- this means that the element is located in the middle of the div.

+4
source share
2 answers

Well, it worked ... just needed 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});
+7

, offsetParent ( position ), offset() position():

cont.animate({scrollTop: cont.scrollTop() + (el.offset().top - cont.offset().top)});
+1

Source: https://habr.com/ru/post/1536191/


All Articles