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.
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.
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).
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.
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.
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});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With