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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With