Get Off My Lawn
Get Off My Lawn

Reputation: 36351

Get item offset from the top of page

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.

Upvotes: 23

Views: 38448

Answers (2)

Dmitry Shashurov
Dmitry Shashurov

Reputation: 1724

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

Upvotes: 2

Jack
Jack

Reputation: 9548

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.

Upvotes: 64

Related Questions