Skip to main content Accessibility Feedback

Get distances to the top of the document with native JavaScript

Last week I added two new code snippets to my Ditching jQuery resource.

One is used to get your current position on a page from the top of the document. The other will get the distance of any element from the top of the document.

// Get current location's distance from the top of the page
var position = window.pageYOffset;

// Get an element's distance from the top of the page
var getElemDistance = function ( elem ) {
    var location = 0;
    if (elem.offsetParent) {
        do {
            location += elem.offsetTop;
            elem = elem.offsetParent;
        } while (elem);
    }
    return location >= 0 ? location : 0;
};
var elem = document.querySelector('#some-element');
var location = getElemDistance( elem );

🚀 Make 2018 the year you master JavaScript! My pocket guides and mini courses are short, focused, and made for beginners. You can do this!

Have any questions or comments about this post? Email me at chris@gomakethings.com or contact me on Twitter at @ChrisFerdinandi.

Get Daily Developer Tips