Vertical offset of element

JavaScript, Browser · Jan 5, 2021

Finds 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;
};
getVerticalOffset('.my-element'); // 120

Written by Angelos Chalaris

I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.

If you want to keep in touch, follow me on GitHub or Twitter.

More like this

  • Array of element's siblings

    Returns an array containing all the siblings of the given element.

    JavaScript, Browser · Oct 19, 2020

  • Get element ancestors

    Returns all the ancestors of an element from the document root to the given element.

    JavaScript, Browser · Jan 5, 2021

  • Create HTML element

    Creates an element from a string (without appending it to the document). If the given string contains multiple elements, only the first one will be returned.

    JavaScript, Browser · Oct 19, 2020