Skip to main content Skip to secondary navigation 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 );
If you liked this article, you might also like Ditching jQuery, my new beginner's guide to vanilla JavaScript. Pre-order it today and save 50%.
  • More articles on...
  • Code

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

Get Weekly Digests