I want to know how to use JavaScript to get the distance of an element from the top of the page not the parent element.
var distanceTop = element.getBoundingClientRect().top;
For details vist a link:
https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect
This function returns distance from top of the page, even if your window is scrolled. It can be used in event listeners.
const getElementYOffset = (element) => {
const scrollOnWindow =
window.pageYOffset !== undefined
? window.pageYOffset
: (document.documentElement || document.body.parentNode || document.body)
.scrollTop;
const rect = element.getBoundingClientRect();
let distanceFromTopOfPage = rect.top;
if (scrollOnWindow !== 0) {
distanceFromTopOfPage = rect.top + scrollOnWindow;
}
return distanceFromTopOfPage;
};
scroll to element's top position;
var rect = element.getBoundingClientRect();
var offsetTop = window.pageYOffset + rect.top - rect.height;
var elDistanceToTop = window.pageYOffset + el.getBoundingClientRect().top
In my experience document.body.scrollTop
doesn't always return the current scroll position (for example if the scrolling actually happens on a different element).
Although it is quite an old discussion, but this works pretty well on chrome / firefox / safari
browsers:
window.addEventListener('scroll', function() {
var someDiv = document.getElementById('someDiv');
var distanceToTop = someDiv.getBoundingClientRect().top;
});
Check it out on JSFiddle
Using jQuery's offset() method:
$(element).offset().top
Example: http://jsfiddle.net/yZGSt/3/