December 30, 2024

The other day, I was trying to figure out how to find the absolute position of an element on a HTML page. And surprisingly, it was not immediately obvious. Also, I wanted it to work in IE and Mozilla.

Well, I found this page on How can I find location of an object in page? which gave me the critical hint.

I’ve created a page to show an example of how to get and set an element’s absolute position – Javascript Absolute Positioning Demo.

Here’s the code:

<html>
<head>
<title>Javascript Absolute Positioning Demo</title>
</head>
<script>
function moveIt() {
var follow = document.getElementById(‘follow’);
getPos(follow);

var me = document.getElementById(‘me’);
getPos(me);

me.x = follow.x;
me.y = follow.y;

setPos(me);

follow.x = Math.random() * 200 + 50;
follow.y = Math.random() * 200 + 50;

setPos(follow);
}

function getPos(el) {
if (document.getBoxObjectFor) {
var bo = document.getBoxObjectFor(el);
el.x = bo.x;
el.y = bo.y;
}
else {
var rect = el.getBoundingClientRect();
el.x = rect.left;
el.y = rect.top;
}
}

function setPos(el) {
if (document.getBoxObjectFor) {
el.style.left = el.x;
el.style.top = el.y;
}
else {
el.style.pixelLeft = el.x + document.documentElement.scrollTop;
el.style.pixelTop = el.y + document.documentElement.scrollLeft ;
}
}
</script>

</HEAD>
<BODY>
<div id=”follow” style=”position: absolute; left:10; top:50;”>
<p>Follow</p>
</div>
<div id=”me” style=”position: absolute; left:80; top:50;”>
<p>Me</p>
</div>

<form>
<input type=”button” onClick=”moveIt()” value=”Move It” />
</form>

</BODY>
</HTML>