getElementDimensions (JavaScript)
This function returns the dimensions of an element (left, right, top, bottom, width and height). You can pass on either a string (which gets the element by ID), or the element itself.
function getElementDimensions(el)
{
if(typeof(el) == "string")
{
el = document.getElementById(el);
}
if(!el || !el.offsetParent) return false;
var left = el.offsetLeft, top = el.offsetTop, width = el.offsetWidth, height = el.offsetHeight;
do
{
el = el.offsetParent, left+= el.offsetLeft, top+= el.offsetTop;
}
while (el.offsetParent);
return {"left" : left, "right" : left + width, "top" : top, "bottom" : top + height, "width" : width, "height" : height};
}
Example use:
var foo = document.getElementById("foo");
var fooDim = getElementDimensions(foo);
if(fooDim)
{
alert(fooDim.left);
}
var barDim = getElementDimensions("bar");
if(barDim)
{
alert(barDim.top);
}
Comments