I am looking looking to calculate the distance between an element and the top of the document window. On scroll I am able to get the initial value but it does not change. How can I find this value and what the number has changed to on scroll?
JS:
$(function() {
$(window).scroll(function() {
var h1 = $("h1");
console.log(h1.offset().top)
});
});
HTML:
<div id="cover">
<h1>hello sir</h1>
</div>
If you hate arithmetic (and extra function calls), this should do the trick:
This is exactly what getBoundingClientRect() was made for.
Compare the offset of the
<h1>
element to how far down the page the user has scrolled. The$(window).scrollTop()
function will get you the amount the user has scrolled down so:You can use this function to get the scroll offset of the window:
Then you can use the offsets in your function to determine the real position of your element:
Theoretically, this should work in all browsers, but, frankly, I didn't do too much testing.