jnolte jnolte - 1 year ago 95
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?


$(function() {
$(window).scroll(function() {
var h1 = $("h1");


<div id="cover">
<h1>hello sir</h1>

Answer Source

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