Files
30-seconds-of-code/snippets/getVerticalOffset.md
Isabelle Viktoria Maciohsek 8bf67754ce Make expertise a field
2022-03-01 20:21:45 +02:00

646 B

title, tags, expertise, firstSeen, lastUpdated
title tags expertise firstSeen lastUpdated
Vertical offset of element browser beginner 2021-01-05T22:41:09+02:00 2021-01-05T22:41:09+02:00

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