Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get position of element by JavaScript

I've seen dozens of scripts that can catch the x and y position of an element/object within the page. But I am always having trouble with catching the x and y when the webpage is using margins at the body, or other elements, absolute/relative elements, such like that.

Is there a solution which provides the exact position, no matter what margins or paddings are used?

like image 906
Johnny Avatar asked Nov 20 '09 10:11

Johnny


2 Answers

Getting the exact position is simply a matter of adding the offsetLefts and offsetTops recursively to the offsetParents:

function getPos(ele){
    var x=0;
    var y=0;
    while(true){
        x += ele.offsetLeft;
        y += ele.offsetTop;
        if(ele.offsetParent === null){
            break;
        }
        ele = ele.offsetParent;
    }
    return [x, y];
}

Btw, this solution would probably run twice faster than the other solution above since we only loop once.

like image 116
Pacerier Avatar answered Oct 14 '22 07:10

Pacerier


offsetParent and other offset functions are old... use the getBoundingClientRect function... use this:

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

now you can use it like this

<div style="margin:50px;padding:50px;" id="myEl">lol</div>
<script type="text/javascript">
    var coords = getAbsPosition( document.getElementById('myEl') );
    alert( coords.x );alert( coords.y );
</script>

Don't worry... no matter how much margin or position or padding the element has, it always works

like image 21
Sayan J. Das Avatar answered Oct 14 '22 08:10

Sayan J. Das