Find position

See section 9G of the book. However, the script on this page is a newer version than the one in the book, and it's supposed to work better than the old one.

The test layer

On this page I give the necessary code to find out where an element is on the page. This script finds the real position, so if you resize the page and run the script again, it points to the correct new position of the element.

offset

In all browsers it's necessary to use the offsetTop and offsetLeft of the element. These properties give the coordinates relative to the offsetParent of the element.

The script moves up the tree of offsetParents and adds the offsetTop and offsetLeft of each. Eventually, regardless of the actual composition of the offsetParent tree, this leads to the real coordinates of the element on the screen.

See the W3C CSS Object Model Table for a further explanation and a test case.

Explanation

The script is very simple. Hand it the object whose position should be calculated and set the variables curleft and curtop to 0:

function findPos(obj) {
	var curleft = curtop = 0;

If the browser supports offsetParent we proceed.

	if (obj.offsetParent) {

Every time we find a new object, we add its offsetLeft and offsetTop to curleft and curtop.

	do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;

The tricky bit: return value of the = operator

Now we get to the tricky bit:

		} while (obj = obj.offsetParent);

No, this is not a syntax error. I don't want to use == to compare obj to obj.offsetParent (that doesn't make sense anyhow, since an element is never equal to its offsetParent).

Instead, I use the = assignment operator to change the value of obj to obj.offsetParent. I explain this trick in more detail in this blog post.

The simple bits

The loop continues until the object currently being investigated does not have an offsetParent any more. While the offsetParent is still there, it still adds the offsetLeft of the object to curleft, and the offsetTop to curtop.

Finally, when the while loop has quit, we return an array with the calculated coordinates to whichever script asked for it.

	return [curleft,curtop];
}