• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
JavaScriptSource

JavaScriptSource

Search 5,000+ Free JavaScript Snippets

  • Home
  • Browse Snippets
    • Addon
    • Ajax
    • Buttons
    • Cookies
    • CSS
    • Featured
    • Forms
    • Games
    • Generators
    • Image Effects
    • Math Related
    • Miscellaneous
    • Multimedia
    • Navigation
    • Page Details
    • Passwords
    • Text Effects
    • Time & Date
    • User Details
Home / Page Details / Find the distance from a given element to the top of the document

Find the distance from a given element to the top of the document

Find the distance from a given element to the top of the document

Use getVerticalOffset to find the distance from a given element to the top of the document.

Use a while loop and HTMLElement.offsetParent to move up the offset parents of the given element.

Add HTMLElement.offsetTop for each element and return the result.

const getVerticalOffset = el => {
  let offset = el.offsetTop,
    _el = el;
  while (_el.offsetParent) {
    _el = _el.offsetParent;
    offset += _el.offsetTop;
  }
  return offset;
};

// Example
getVerticalOffset('.my-element'); // 120

Source

https://www.30secondsofcode.org/js/s/get-vertical-offset

Page Details

Related Snippets:

  • Hexadecimal Color Wheel
  • Notify when element size is changed
  • Get all URL parameters from a query string
  • Get the height of the viewport

Primary Sidebar

Popular Posts

Story Generator

IP Grabber – get a users IP address with JavaScript

Simple Calendar

Remove Ads

Astrological Calculator

Copyright © 2025 JavaScriptSource.com

  • About
  • Privacy Policy
  • FAQ
  • Jobs For Developers