From 55eb541f5c2ed87b4351330d34356e52f622c055 Mon Sep 17 00:00:00 2001 From: Chalarangelo Date: Tue, 5 Jan 2021 22:41:09 +0200 Subject: [PATCH] Add getVerticalOffset --- snippets/getVerticalOffset.md | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 snippets/getVerticalOffset.md diff --git a/snippets/getVerticalOffset.md b/snippets/getVerticalOffset.md new file mode 100644 index 000000000..33f2e36a9 --- /dev/null +++ b/snippets/getVerticalOffset.md @@ -0,0 +1,25 @@ +--- +title: getVerticalOffset +tags: browser,beginner +--- + +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. + +```js +const getVerticalOffset = el => { + let offset = el.offsetTop, + _el = el; + while (_el.offsetParent) { + _el = _el.offsetParent; + offset += _el.offsetTop; + } + return offset; +}; +``` + +```js +getVerticalOffset('.my-element'); // 120 +```