jnolte jnolte - 5 months ago 14
jQuery Question

Detecting offset of an element on scroll in javascript / jQuery

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>

Answer

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:

$(window).scroll(function() {
  var $h1 = $("h1");
  var window_offset = $h1.offset().top - $(window).scrollTop();
});