Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting coordinates of objects in JS

So based on this question I asked, what's the most reliable way of getting position of objects that's crossbrowser? Thx

like image 554
user1019031 Avatar asked Aug 07 '26 15:08

user1019031


1 Answers

In general, assuming you have an element named elem, it's actually quite easy to get the X and Y coordinates of the top-left corners of an element, assuming you want these in document coordinates. In all browsers this is returned by the elem.offsetLeft and elem.offsetTop properties.

The only trick you have to be aware of is that if elem is absolutely positioned in another element, say a div with a left / top margin of 20px, these properties will return 0, as it only takes into account the current element and not the entire chain of elements. Luckily we can use a "chain-traversal" function to capture all of the margins of elements associated with a given element, tally them up to get the correct document coordinates.

As Sime Vidas mentioned, there is also JQuery's position() and offset() properties, in this case you would want the offset() properties.

You can also use the getBoundingClientRect() method, however this returns the coordinates of an element relative to its offsetParent and thus is not entirely reliable. Look at the following examples:

// getPosition function
function getPosition(elem){

    var dims = {offsetLeft:0, offsetTop:0};

    do {
        dims.offsetLeft += elem.offsetLeft;
        dims.offsetTop += elem.offsetTop;
    }

    while (elem = elem.offsetParent);

    return dims;
}

cont1.style.position = "absolute";
cont1.style.marginLeft = "10px";

cont2.style.position = "absolute";
cont2.style.marginLeft = "10px";

box.style.position = "absolute";
box.style.marginLeft = "10px";


console.log(getPosition(box).offsetLeft); // returns "30"
console.log(getPosition(box).offsetTop); // returns "0"

// or in JQuery
console.log($(box).offset().left) // also returns "30"
console.log($(box).offset().top) // also returns "0"

Also I suggest you read this.

like image 58
dkugappi Avatar answered Aug 10 '26 09:08

dkugappi