Saturday, January 24, 2009

How to get the position of a control using Javascript?

Here is a handy functions to get the posisiton of a control using Javascript:

Usage:

alert(getElementPosition('txtName').top + ' ' + getElementPosition('txtName').left);

Function:
 function getElementPosition(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 };
}

We can get the current scroll position of the document using:
var scrolly = typeof window.pageYOffset != 'undefined' ? window.pageYOffset : document.documentElement.scrollTop;
var scrollx = typeof window.pageXOffset != 'undefined' ? window.pageXOffset : document.documentElement.scrollLeft;
Hope this helps you...

2 comments:

Anonymous said...

How do you invoke this in c# asp.net page? Tried it and it's not working. Would you be able to give a sample, please?

Pooja said...

not working properly

Post a Comment