JavaScript function to get the position coordinates for a DOM element.
/**
* Gets the position coordinates for an element.
*
* @example
* var coordiantes = getElementPosition( document.getElementById('el') );
* >>> Object { x: 0, y: 0, width: 1350, height: 45 }
*
* @param {DOM.Element} element The DOM Element.
* @return {Object} An object containing the position coordinates for the passed
* DOM Element. Example: Object { x: 0, y: 0, width: 1350, height: 45 }.
*/
function getElementPosition(element) {
var result = {};
result.x = 0;
result.y = 0;
result.width = 0;
result.height = 0;
if (element.offsetParent) {
result.x = element.offsetLeft;
result.y = element.offsetTop;
var parent = element.offsetParent;
while (parent) {
result.x += parent.offsetLeft;
result.y += parent.offsetTop;
var parentTagName = parent.tagName.toLowerCase();
if (parentTagName != "table" &&
parentTagName != "body" &&
parentTagName != "html" &&
parentTagName != "div" &&
parent.clientTop &&
parent.clientLeft) {
result.x += parent.clientLeft;
result.y += parent.clientTop;
}
parent = parent.offsetParent;
}
} else if (element.left && element.top) {
result.x = element.left;
result.y = element.top;
} else {
if (element.x) {
result.x = element.x;
}
if (element.y) {
result.y = element.y;
}
}
if (element.offsetWidth && element.offsetHeight) {
result.width = element.offsetWidth;
result.height = element.offsetHeight;
} else if (element.style && element.style.pixelWidth && element.style.pixelHeight) {
result.width = element.style.pixelWidth;
result.height = element.style.pixelHeight;
}
return result;
}