How to Get Element Distance From Top with jQuery offset()

0 Shares
0
0
0
0
0
0
0

To calculate the distance from the top and save it into a variable you can use the following code:

$(document).ready(function(){
  var elementOffset = $('your-element').offset().top;
});

Another useful technique is to determine the current distance from the top for the element while the visitor is scrolling up/down the page. To do this you would have to catch the current page offset from the top first.

Here is the code:

$(document).ready(function(){
   $(window).bind('scroll', function() {
      var scrollTop = $(window).scrollTop();
      var elementOffset = $('your-element').offset().top;
      var currentElementOffset = (elementOffset - scrollTop);
   });
});