Detecting offset of an element on scroll in javascript / jQuery

jeffreynolte picture jeffreynolte · Jun 23, 2011 · Viewed 70.9k times · Source

I am 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

MidnightLightning picture MidnightLightning · Jun 23, 2011

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();
});