Saturday, June 20, 2009

Getting position of HTML component

What if we want to read position of a html control in Javascript?
Only time I tried this was to get a screenshot of a particular area in the page, I doubt whether there is any valid usecases.
Try using the below function in JS

function getPositionOfElement(elemID) {
var offsetTrail = document.getElementById(elemID);
var offsetLeft = 0;
var offsetTop = 0;
while (offsetTrail) {
offsetLeft += offsetTrail.offsetLeft;
offsetTop += offsetTrail.offsetTop;
offsetTrail = offsetTrail.offsetParent;
}
return { left: offsetLeft, top: offsetTop };
}
Possible usage
getPositionOfElementElement('div_id').left;
getElementPosition('div_id').left;
Dont forget to check the properties like
self.screen.height
self.screen.availHeight
self.screenTop

No comments:

Post a Comment