Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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.

like image 725
ariel Avatar asked Apr 11 '14 23:04

ariel


People also ask

How do you get the scroll position element?

To get or set the scroll position of an element, you follow these steps: First, select the element using the selecting methods such as querySelector() . Second, access the scroll position of the element via the scrollLeft and scrollTop properties.

Which position get an element relative to scroll position in CSS?

An element with position: sticky; is positioned based on the user's scroll position. A sticky element toggles between relative and fixed , depending on the scroll position. It is positioned relative until a given offset position is met in the viewport - then it "sticks" in place (like position:fixed).

How do you know if an element is visible in scroll?

To know whether the element is fully visible in viewport, you will need to check whether top >= 0, and bottom is less than the screen height. In a similar way you can also check for partial visibility, top is less than screen height and bottom >= 0.

How do you get an element's top position relative to the browser's viewport?

We can use the getBoundingClientRect method to get an element's position relative to its viewport. We get the div with querySelector . Then we call getBoundingClientRect on it to get an object with the top and left properties. top has the position relative to the top of the viewport.


1 Answers

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});
like image 189
ariel Avatar answered Sep 21 '22 09:09

ariel