Let's say I have an <li>
element inside a scrollable div and the scroll was set to show that element in the viewport.
I need to get the distance between that element and its scrollable parent, as shown in the picture above, but both element.getBoundingClientRect().top
and element.offsetTop
give me the wrong values. Can that be done?
I made a pen, to make things a little bit easier:
http://codepen.io/Darksoulsong/pen/LbYMex
A piece of my code:
document.addEventListener("DOMContentLoaded", function(event) {
var selectedEl = document.getElementById('consequatur-51');
var selectedElRect = selectedEl.getBoundingClientRect();
var sidebar = document.getElementById('sidebar');
sidebar.scrollTop = selectedEl.offsetTop - 60;
document.getElementById('offsetTop').innerText = selectedEl.offsetTop;
document.getElementById('rectTop').innerText = selectedElRect.top;
});
To get the distance from the top for an element with JavaScript, we get the sum of the window. pageYOffset property and the element's top value. const elDistanceToTop = window. pageYOffset + el.
You can use . offset() to get the offset compared to the document element and then use the scrollTop property of the window element to find how far down the page the user has scrolled: var scrollTop = $(window). scrollTop(), elementOffset = $('#my-element').
A child div can also be wider than its parent by utilizing different positioning such as absolute or fixed positioning. Different results can occur depending on the specified position of the parent div but as long as the element is either absolute/fixed or contains a specified width, it will grow outside the parent.
I found out how to make it work. Actually, @Dummy's answer gave me some important insights.
Basically, the formulae is:
childElementDistanceFromParentTop = actualChildElementDistancefromTop - parentElementDistanceFromTop
With these coordinates I can even tell if the element is visible in the viewport or not.
Updated pen: http://codepen.io/Darksoulsong/pen/rWawrZ
var parentTop = parentElem.getBoundingClientRect().top; // Initial parent's top distance from the top of the viewport;
var currentChildTop = childElement.getBoundingClientRect().top; // Initial child's top distance from the top of the viewport;
If you do var childParentDistance = Math.abs(parentTop - currentChildTop)
, you will get the initial distance between the child element and its parent. But as you scroll, you need to account for the scroll amount. Like this
var scrolledParentDistance= Math.abs(parentTop - parentElem.getBoundingClientRect().top);
and if you subtract scrolledParentDistance
from childParentDistance
, you will get the new distance between this child and its parent
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