How to get an element’s position and area
Among XHTML coders, a “clean solution” to a positioning problem is considered to be any solution that relies solely on CSS, without any interference from javascript. And, of course, these solutions prove to be more elegant, easier to maintain, and sometimes, quite impressive.
But clean solutions are hard to find when you have to deal with the stupidity of a certain browser. And when Microsoft’s faulty implementation of CSS standards ruins your day, Javascript comes to the rescue. In times like these, the methods presented below should provide valuable help.
Getting the position
The offsetLeft and offsetRight attributes of a DOM object contain its position - in pixels - relative to its offsetParent. So, in order to find the element’s position relative to the browser’s window, we must add the element’s offsets to his parent’s offsets and to his grandparent’s offsets, and so on, until we reach the first element on the page.
In javascript, that translates as:
Element.prototype.getPosition = function() {
var x = 0;
var y = 0;
obj = this;
if ( obj.offsetParent ) {
x = obj.offsetLeft;
y = obj.offsetTop;
while ( obj = obj.offsetParent ) {
x += obj.offsetLeft;
y += obj.offsetTop;
}
}
return { x:x, y:y };
}
This method returns a hashtable with the coordinates. Nifty
Getting the area of an element
To get the area of an element - and by area I mean the coordinates of the top left and bottom right corners - we need to find out his position and add to them the element’s offsetWidth and offsetHeight.
Element.prototype.getArea = function() {
var position = this.getPosition();
var area = new Object();
area.topLeftX = position.x;
area.topLeftY = position.y;
area.bottomRightX = position.x + this.offsetWidth;
area.bottomRightY = position.y + this.offsetHeight;
return area;
}
Is an element within a specified area?
Good question. Let’s find out:
Element.prototype.isInArea = function( area ) {
var elementsArea = this.getArea();
return ( elementsArea.topLeftX > area.topLeftX || elementsArea.bottomRightX < area.bottomRightX || elementsArea.topLeftY > area.topLeftY || elementsArea.bottomRightY < area.bottomRightY );
}
This method takes one parameter, an “area” object, like the one returned by the Element.getArea() method. This object is a hashtable containing the topLeftX, topLeftY, bottomRightX, bottomRightY coordinates of the desired area of the screen. If you’re as lazy as I am (I doubt that lazier beings exist), you can use this function to create such an object.
area = function( topLeftX, topLeftY, bottomRightX, bottomRightY ) {
var a = new Object;
a.topLeftX = topLeftX;
a.topLeftY = topLeftY;
a.bottomRightX = bottomRightX;
a.bottomRightY = bottomRightY;
return a;
}


This solution works in most cases, but fails when elements have scrolling, like divs with overflow auto. Here is a small fix:
http://siderite.blogspot.com/2007/…html