18

I am trying to get the top offset of a div, and I have the following code that gets run when the page gets scrolled:

var $elem = document.querySelector(selector);
var elemTop = $elem.offsetTop;
console.log(elemTop);

But when I scroll it always prints 0 to the console, even though the element is below the fold.

Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338

2 Answers2

56
var elmTop = $elem.getBoundingClientRect().top + window.scrollY;

element.getBoundingClientRect() gives the position within the viewport, and window.scrollY gives the distance from the top of the viewport to the top of the document.

Jack
  • 9,448
  • 3
  • 29
  • 33
  • An alternative would be to walk up the DOM using element.offsetParent, adding each node's offsetTop together to get the measurement. This is more complicated, but probably more efficient than calculating the values of getBoundingClientRect, which is something to be mindful of when executing anything onScroll. – Jack Dec 22 '15 at 18:58
1

Solution how to check if the scroll has reached a certain element:

    const getOffsetTop = function(element) {
        if (!element) return 0;
        return getOffsetTop(element.offsetParent) + element.offsetTop;
    };

    const $el = document.querySelector(".button");

    window.addEventListener("scroll", function() {
        console.log(window.scrollY + window.innerHeight > getOffsetTop($el));
    });
Dmitry Shashurov
  • 1,148
  • 13
  • 11