Getting every offsetParent or the total offSetTop and total offSetLeft

2.8k views Asked by At

I want to get the total offSetTop and the total offSetLeft of a child element which have many level of parent element and may be adding up.

Is that any shorthand way, besides of adding one by one in manual ways?

3

There are 3 answers

0
AudioBubble On BEST ANSWER

using jQuery: $( node ).offset() then .top and .left

1
Micah Henning On

To provide an answer without jQuery:

var a = Element, b = 0, c = 0;
while (a) {
    b += a.offsetLeft;
    c += a.offsetTop;
    a = a.offsetParent;
}

Where Element is your Element node for which you need an offsetLeft and offsetTop.

0
Seph Reed On

https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect

If you need the bounding rectangle relative to the top-left corner of the document, just add the current scrolling position to the top and left properties (these can be obtained using window.scrollX and window.scrollY) to get a bounding rectangle which is independent from the current scrolling position.

let { left, top } = domNode.getBoundingClientRect();
left += window.scrollX;
top += window.scrollY;