How to get the object's position(top,left) when the css style has position:relative?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • muiz123
    New Member
    • Jun 2010
    • 8

    #1

    How to get the object's position(top,left) when the css style has position:relative?

    I study http://www.javascripttoolbox.com/lib...tion/index.php source and its doesn't work fine for the following code: (I hope both IE and firefox are working well)

    Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN"
    "http://www.w3.org/TR/REC-html40/strict.dtd">
    <html>
    <head>
    <title>Test</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    <script type="text/javascript">
    /**
     * Copyright (c)2005-2009 Matt Kruse (javascripttoolbox.com)
     * 
     * Dual licensed under the MIT and GPL licenses. 
     * This basically means you can use this code however you want for
     * free, but don't claim to have written it yourself!
     * Donations always accepted: http://www.JavascriptToolbox.com/donate/
     * 
     * Please do not link to the .js files on javascripttoolbox.com from
     * your site. Copy the files locally to your server instead.
     * 
     */
    
    var Position = (function() {
      // Resolve a string identifier to an object
      // ========================================
      function resolveObject(s) {
        if (document.getElementById && document.getElementById(s)!=null) {
          return document.getElementById(s);
        }
        else if (document.all && document.all[s]!=null) {
          return document.all[s];
        }
        else if (document.anchors && document.anchors.length && document.anchors.length>0 && document.anchors[0].x) {
          for (var i=0; i<document.anchors.length; i++) {
            if (document.anchors[i].name==s) { 
              return document.anchors[i]
            }
          }
        }
      }
      
      var pos = {};
      pos.$VERSION = 1.0;
      
      // Set the position of an object
      // =============================
      pos.set = function(o,left,top) {
        if (typeof(o)=="string") {
          o = resolveObject(o);
        }
        if (o==null || !o.style) {
          return false;
        }
        
        // If the second parameter is an object, it is assumed to be the result of getPosition()
        if (typeof(left)=="object") {
          var pos = left;
          left = pos.left;
          top = pos.top;
        }
        
        o.style.left = left + "px";
        o.style.top = top + "px";
        return true;
      };
      
      // Retrieve the position and size of an object
      // ===========================================
      pos.get = function(o) {
        var fixBrowserQuirks = true;
          // If a string is passed in instead of an object ref, resolve it
        if (typeof(o)=="string") {
          o = resolveObject(o);
        }
        
        if (o==null) {
          return null;
        }
        
        var left = 0;
        var top = 0;
        var width = 0;
        var height = 0;
        var parentNode = null;
        var offsetParent = null;
      
        
        offsetParent = o.offsetParent;
        var originalObject = o;
        var el = o; // "el" will be nodes as we walk up, "o" will be saved for offsetParent references
        while (el.parentNode!=null) {
          el = el.parentNode;
          if (el.offsetParent==null) {
          }
          else {
            var considerScroll = true;
            /*
            In Opera, if parentNode of the first object is scrollable, then offsetLeft/offsetTop already 
            take its scroll position into account. If elements further up the chain are scrollable, their 
            scroll offsets still need to be added in. And for some reason, TR nodes have a scrolltop value
            which must be ignored.
            */
            if (fixBrowserQuirks && window.opera) {
              if (el==originalObject.parentNode || el.nodeName=="TR") {
                considerScroll = false;
              }
            }
            if (considerScroll) {
              if (el.scrollTop && el.scrollTop>0) {
                top -= el.scrollTop;
              }
              if (el.scrollLeft && el.scrollLeft>0) {
                left -= el.scrollLeft;
              }
            }
          }
          // If this node is also the offsetParent, add on the offsets and reset to the new offsetParent
          if (el == offsetParent) {
            left += o.offsetLeft;
            if (el.clientLeft && el.nodeName!="TABLE") { 
              left += el.clientLeft;
            }
            top += o.offsetTop;
            if (el.clientTop && el.nodeName!="TABLE") {
              top += el.clientTop;
            }
            o = el;
            if (o.offsetParent==null) {
              if (o.offsetLeft) {
                left += o.offsetLeft;
              }
              if (o.offsetTop) {
                top += o.offsetTop;
              }
            }
            offsetParent = o.offsetParent;
          }
        }
        
      
        if (originalObject.offsetWidth) {
          width = originalObject.offsetWidth;
        }
        if (originalObject.offsetHeight) {
          height = originalObject.offsetHeight;
        }
        
        return {'left':left, 'top':top, 'width':width, 'height':height
            };
      };
      
      // Retrieve the position of an object's center point
      // =================================================
      pos.getCenter = function(o) {
        var c = this.get(o);
        if (c==null) { return null; }
        c.left = c.left + (c.width/2);
        c.top = c.top + (c.height/2);
        return c;
      };
      
      return pos;
    })();
    
    
    </script>
    <style>
    #idText { border:1px red solid ; }
    
    #mainDiv {
    	position:relative ;
    	margin: 100px 0 0 50px;
    	border: 1px solid blue;
    	padding: 20px;
    }
    .marker {
    	position:absolute;
    	width:10px;
    	height:10px;
    	border:1px solid black;
    }
    
    #marker1 {
    	background-color:yellow;
    }
    #marker2 {
    	background-color:blue;
    }
    #marker3 {
    	background-color: #00FF00;
    }
    </style>
    <body>
    <div id="marker1" class="marker"></div>
    <div id="marker2" class="marker"></div>
    <div id="marker3" class="marker"></div>
    
    <div id="mainDiv">
    	########<div id="idText">a text</div>############
    	<br />
    	<table cellpadding="1" cellspacing="1" border="1"><tr>
    		<td onClick="getEditorPosition(this);">&nbsp;&nbsp;Cell1&nbsp;&nbsp;</td>
    		<td onClick="getEditorPosition(this);" >&nbsp;&nbsp;Cell2&nbsp&nbsp;</td>
    	</tr></table>
    </div>
    <script type="text/javascript">
    
    var pos=Position.get(document.getElementById('mainDiv' ));
    Position.set(document.getElementById('marker1'),pos);
    
    var pos=Position.get(document.getElementById('idText'));
    Position.set(document.getElementById('marker2'),pos);
    
    
    function getEditorPosition(cell) {
    	var pos=Position.get(cell);
    	Position.set(document.getElementById('marker3'),pos);
    }
    
    
    </script>
    </body>
    </html>
    Thanks in advanced!
  • johny10151981
    Top Contributor
    • Jan 2010
    • 1059

    #2
    You better Ask specifically what is your problem.

    Comment

    • muiz123
      New Member
      • Jun 2010
      • 8

      #3
      Originally posted by johny10151981
      You better Ask specifically what is your problem.
      To: johny10151981

      the problem is that I cannot get the really position if I set the css style position to relative.

      Comment

      • johny10151981
        Top Contributor
        • Jan 2010
        • 1059

        #4
        Use the function below
        Code:
        function getPosition(obj){
            var topValue= 0,leftValue= 0;
            while(obj){
        	leftValue+= obj.offsetLeft;
        	topValue+= obj.offsetTop;
        	obj= obj.offsetParent;
            }
            finalvalue = leftValue + "," + topValue;
            return finalvalue;
        }
        I got this small piece of code in some site but cant recall where.

        First off all you can get any objects offset position. offset position is related to its parents position.
        obj.offsetParen t return the parent of the current object
        Code:
        <div id=d1>
         <div id=d2>
         </div>
        </div>
        in this above example d2's parents is d1. Top most parent id main window page. and Window's offset parent is no one i.e. null.

        If anyof my above information is wrong please let me know.

        Best Regards
        johny

        Comment

        • muiz123
          New Member
          • Jun 2010
          • 8

          #5
          hi, johny, thanks for your reply!

          I use your function before, and it doesn't work in IE. You can test the following code:

          Code:
          <html>
          <head>
          <title>Test</title>
          <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
          <script type="text/javascript">
          function getPosition(obj){
          	var topValue = 0, leftValue = 0;
          	while(obj){
          		leftValue += obj.offsetLeft;
          		topValue += obj.offsetTop;
          		obj = obj.offsetParent;
          	}
          	return {left: leftValue, top: topValue};
          }
          function move(src, target) {
          	var position = getPosition(target);
          	src.style.top = position.top + "px";
          	src.style.left = position.left + "px";
          }
          </script>
          <style>
          #idText { border:1px red solid ; padding-left: 100px; }
          #mainDiv {
          	position: relative;
          	margin: 50px 0 0 200px;
          	border: 1px solid blue;
          	padding: 20px;
          }
          .marker {
          	position: absolute;
          	border:1px solid black;
          }
          #marker1 {
          	background-color:yellow;
          }
          #marker2 {
          	background-color:blue;
          }
          #marker3 {
          	background-color: #00FF00;
          }
          td {
          	width: 150px;
          	height: 70px;
          }
          </style>
          </head>
          <body>
          <div id="marker1" class="marker">1. moveToMainDiv</div>
          <div id="marker2" class="marker">2. moveToText</div><br />
          <div id="marker3" class="marker">3. moveToCell</div>
          <div id="mainDiv">
          	#### Main Div ####<div id="idText">a text</div>############
          	<br />
          	<table cellpadding="1" cellspacing="1" border="1"><tr>
          		<td onClick="getEditorPosition(this);">Cell1 - click me</td>
          		<td onClick="getEditorPosition(this);" >Cell2 - click me</td>
          	</tr></table>
          </div>
          
          <script type="text/javascript">
          
          var m1 = document.getElementById('marker1');
          var m2 = document.getElementById('marker2');
          var m3 = document.getElementById('marker3');
          var mainDiv = document.getElementById('mainDiv');
          var text = document.getElementById('idText');
          
          move(m1, mainDiv);
          move(m2, text);
          
          function getEditorPosition(cell) {
          	move(m3, cell);
          }
          
          
          </script>
          </body>
          </html>

          Comment

          • muiz123
            New Member
            • Jun 2010
            • 8

            #6
            I updated my test scripts:

            Code:
            <html>
                <head>
                    <title>Test</title>
                    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
                    <script type="text/javascript">
                        function getPosition(obj){
                            var topValue = 0, leftValue = 0;
                            while (obj) {
                                leftValue += obj.offsetLeft;
                                topValue += obj.offsetTop;
                                obj = obj.offsetParent;
                            }
                            return {
                                left: leftValue,
                                top: topValue
                            };
                        }
                    </script>
                    <style type="text/css">
                    	* {
                    		border: 0;
            				margin: 0;
            				padding: 0;
                    	}
            			#div1 {
            				padding: 50px;
            			}
                        #div2 {
                            position: relative;
                            margin: 20px;
                            padding: 50px;
            				background: red;
                        }
            			#div3 {
            				height: 50px;
            				width: 400px;
            				background: #ccc;
            				padding: 20px;
            			}
                        #cursor {
                            position: absolute;
                            background-color: yellow;
            				width: 50px;
            				z-index: 1000;
                        }
                    </style>
                </head>
                <body>
                	<div id="div1">
            	    	<div id="cursor">Cursor</div>
            	        <div id="div2">
            	            <br>div2<br><br>
            				<div id="div3" onClick="moveCursor(this);">div3 - cursor should be moved to here</div>
            	        </div>
            	        <script type="text/javascript">
            	            var cursor = document.getElementById('cursor');
            				var mainDiv = document.getElementById("div2");
            	           	move(cursor, mainDiv);
            				
            	            function moveCursor(cell){
            	                var position = getPosition(cell);
            	                cursor.style.top = position.top + "px";
            	                cursor.style.left = position.left + "px";
            	            }
            	        </script>
            		</div>
                </body>
            </html>

            Comment

            • johny10151981
              Top Contributor
              • Jan 2010
              • 1059

              #7
              does your updated script work?
              let me know, i am checking too

              Comment

              • johny10151981
                Top Contributor
                • Jan 2010
                • 1059

                #8
                Javascript cannot find you move function on line 58
                fix it. and test your javascript on firefox

                Comment

                • muiz123
                  New Member
                  • Jun 2010
                  • 8

                  #9
                  Hi, johny10151981.

                  The updated script doesn't work, but you can try the below one: I use a new method in this script: getBoundingClie ntRect, it seems working fine both firefox and IE. (BTY, the script I posted just now, it works in firefox, but not IE)

                  Code:
                  <html>
                      <head>
                          <title>Test</title>
                          <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
                          <script type="text/javascript">
                              function getPosition(obj){
                                  var topValue = 0, leftValue = 0;
                                  while (obj) {
                                      leftValue += obj.offsetLeft;
                                      topValue += obj.offsetTop;
                                      obj = obj.offsetParent;
                                  }
                                  return {
                                      left: leftValue,
                                      top: topValue
                                  };
                              }
                              
                              function getScroll(){
                                  var t, l, w, h;
                                  if (document.documentElement && document.documentElement.scrollTop) {
                                      t = document.documentElement.scrollTop;
                                      l = document.documentElement.scrollLeft;
                                      w = document.documentElement.scrollWidth;
                                      h = document.documentElement.scrollHeight;
                                  }
                                  else 
                                      if (document.body) {
                                          t = document.body.scrollTop;
                                          l = document.body.scrollLeft;
                                          w = document.body.scrollWidth;
                                          h = document.body.scrollHeight;
                                      }
                                  return {
                                      t: t,
                                      l: l,
                                      w: w,
                                      h: h
                                  };
                              }
                          </script>
                          <style type="text/css">
                              * {
                                  border: 0;
                                  margin: 0;
                                  padding: 0;
                              }
                              
                              #div1 {
                                  padding: 50px;
                              }
                              
                              #div2 {
                                  position: relative; /* this is for testing, if the position use offsetleft and offset right, this will cause bug */
                                  margin: 20px;
                                  padding: 50px;
                                  background: red;
                              }
                              
                              #div3 {
                                  height: 50px;
                                  width: 400px;
                                  background: #ccc;
                                  padding: 20px;
                              }
                              
                              #cursor {
                                  position: absolute;
                                  background-color: yellow;
                                  width: 50px;
                                  z-index: 1000;
                              }
                          </style>
                      </head>
                      <body>
                          <div id="div1">
                              <div id="cursor">
                                  Cursor
                              </div>
                              <div id="div2">
                                  <br>
                                  div2
                                  <br>
                                  <br>
                                  <div style="left: 50px; top: 100px; background: green; padding: 1500px  2em 0 1000px; ">
                                      <div id="div3" onClick="moveCursor(this);">
                                          div3 - cursor should be moved to here
                                      </div>
                                  </div>
                              </div>
                              <script type="text/javascript">
                                  var cursor = document.getElementById('cursor');
                                  var div2 = document.getElementById("div2");
                                  move(cursor, div2);
                                  
                                  function moveCursor(cell){
                                      //var p = getPosition(cell);
                                      //cursor.style.top = p.top + "px";
                                      //cursor.style.left = p.left + "px";
                  
                                      var s = getScroll();
                                      var bcr = cell.getBoundingClientRect();
                                      cursor.style.top = (bcr.top + s.t) + "px";
                                      cursor.style.left = bcr.left + "px";
                                  }
                              </script>
                          </div>
                      </body>
                  </html>

                  Comment

                  Working...