How to get absolute coordinates of element with absolute position (JavaScript, Browser)

Lev Balagurov picture Lev Balagurov · Jun 22, 2016 · Viewed 12.9k times · Source

I have some problems with getting coordinates of an element's center which is child of other element with absolute position too. Here you can see a screenshot with the order of elements.

To understand the problem better you can visit my repository at GitHub. index.html is in folder "/Resources"

So, I have some draggable windows (with interact.js) in some other draggable windows and I want to connect their centers by the lines-divs (they are drawn using div with some transformations).

I use this method to render the lines (maybe there are some problems here). I have tried to use jsPlumb for lines drawing, but I failed :(

There is getting points x and y.

// bottom right        
var x1 = offset1.left - margin1.left + size1.width/2 - (this.dom.getAttribute('data-x') || 0);
var y1 = offset1.top - margin1.top + size1.height/2 - (this.dom.getAttribute('data-y') || 0);
// top right
var x2 = offset2.left - margin2.left + size2.width/2 - (this.dom.getAttribute('data-x') || 0);
var y2 = offset2.top - margin2.top + size2.height/2 - (this.dom.getAttribute('data-y') || 0);

(this.dom.getAttribute('data-x') || 0) - that's for Interact.js.

function getMargins(elem) {
    var top = 0, left = 0;
    while (elem.parentNode) {
        top = top + parseFloat(window.getComputedStyle(elem).marginTop.replace('px', ''));
        left = left + parseFloat(window.getComputedStyle(elem).marginLeft.replace('px', ''));
        elem = elem.parentNode;
    }

    return { top: Math.round(top), left: Math.round(left) }
}

function getOffsetRect(elem) {
    // (1)
    var box = elem.getBoundingClientRect()

    // (2)
    var body = document.body
    var docElem = document.documentElement

    // (3)
    var scrollTop = window.pageYOffset || docElem.scrollTop || body.scrollTop
    var scrollLeft = window.pageXOffset || docElem.scrollLeft || body.scrollLeft

    // (4)
    var clientTop = docElem.clientTop || body.clientTop || 0
    var clientLeft = docElem.clientLeft || body.clientLeft || 0

    // (5)
    var top = box.top + scrollTop - clientTop
    var left = box.left + scrollLeft - clientLeft

    return { top: Math.round(top), left: Math.round(left) }
}

Can you help me with the getting center coordinates? Thanks in advance

Answer

Sayan J. Das picture Sayan J. Das · Nov 26, 2016

Try this.. Works best

 function getPos(el) {
     var rect=el.getBoundingClientRect();
     return {x:rect.left,y:rect.top};
 }

Use it like this:

 var coords = getPos(document.querySelector("el"));
 alert(coords.x);alert(coords.y);