Friday, September 18, 2009

JS Function to find exact position on a Element

function findPositionWithScrolling( oElement ) {
function getNextAncestor( oElement ) {
var actualStyle;
if( window.getComputedStyle ) {
actualStyle = getComputedStyle(oElement,null).position;
} else if( oElement.currentStyle ) {
actualStyle = oElement.currentStyle.position;
} else {
//fallback for browsers with low support - only reliable for inline styles
actualStyle = oElement.style.position;
}
if( actualStyle == 'absolute' actualStyle == 'fixed' ) {
//the offsetParent of a fixed position element is null so it will stop
return oElement.offsetParent;
}
return oElement.parentNode;
}
if( typeof( oElement.offsetParent ) != 'undefined' ) {
var originalElement = oElement;
for( var posX = 0, posY = 0; oElement; oElement = oElement.offsetParent ) {
posX += oElement.offsetLeft;
posY += oElement.offsetTop;
}
if( !originalElement.parentNode !originalElement.style typeof( originalElement.scrollTop ) == 'undefined' ) {
//older browsers cannot check element scrolling
return [ posX, posY ];
}
oElement = getNextAncestor(originalElement);
while( oElement && oElement != document.body && oElement != document.documentElement ) {
posX -= oElement.scrollLeft;
posY -= oElement.scrollTop;
oElement = getNextAncestor(oElement);
}
return [ posX, posY ];
} else {
return [ oElement.x, oElement.y ];
}
}
How To Use
<html>
<head>
<script>
var divObj=document.getElemeById('mydiv');
alert(findPositionWithScrolling(divOb'));
</script>
</head>
<body>
<div style="padding:20px;width:100px;height:100px">
<div style="padding:20px;width:5;height:5">

<div id="mydiv" style="padding:20px;width:20;height:2" >
</div>

</div>
</body>
</html>

No comments:

Post a Comment