offsetParent

calendar March 6, 2010

Value: Object reference

Compatibility: WinIE4+, MacIE4+, NN6+, Moz1+, Safari1+

The offsetParent property returns a reference to the object that acts as a positioning context for the current element.Values for the offsetLeft and offsetTop are measured relative to the top-left corner of the offsetParent object.

The returned object is usually , but not always the next outermost block-level container. For most document elements the offsetParent object is the document.body object.

The property behaves predictably for positioned elements in most browsers.

Code:

<html>
 <head>
 <title>offsetParent Property</title>
 <script type="text/javascript">
 function setImagePosition()
 {
   var x = 0;
   var y = 0;
   var offsetPointer = document.getElementById("myCell");

   while(offsetPointer)
   {
     x += offsetPointer.offsetLeft;
     y += offsetPointer.offsetTop;
     offsetPointer = offsetPointer.offsetParent;
   }

   //correct for MacIE body margin factors
   if(navigator.userAgent.indexOf("Mac") != -1 &&
   typeof document.body.leftMargin != "undefined")
   {
     x += document.body.leftMargin;
     y += document.body.topMargin;
   }

   document.getElementById("myDiv").style.left = x + "px";
   document.getElementById("myDiv").style.top = y + "px";
   document.getElementById("myDiv").style.visibility = "visible";
 }       
 </script>
 </head>    
 <body onLoad="setImagePosition()">
 <h1>The offset property</h1>
 <p>After the document loads, the script positions a small image in the upper
 corner of the second table cell.</p>
 <table border="1" align="center">
 <tr>
 <td>First cell</td>
 <td id="myCell">Second cell</td>
 </tr>
 </table>
 <img src="image.png" id="myDiv" height="12" width="12"
 style="position:absolute;visibility:hidden;" />
 </body>
</html>
admin

Leave a Reply

You must be logged in to post a comment.