Coordinates of a div

Discussion in 'JavaScript' started by enchance, Oct 8, 2007.

  1. #1
    Is it possible to get the coordinates of a div which was absolutely positioned in css? That way I could attach other divs under it like a normal div creating the illusion that it wasn't absolutely positioned.
     
    enchance, Oct 8, 2007 IP
  2. enchance

    enchance Peon

    Messages:
    109
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    I have soooooooo manyy replies! hehe
     
    enchance, Oct 9, 2007 IP
  3. ajsa52

    ajsa52 Well-Known Member

    Messages:
    3,426
    Likes Received:
    125
    Best Answers:
    0
    Trophy Points:
    160
    #3
    You can use functions findX() and findY() from the following example:

    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <head>
    
    <style type="text/css">
    #id1 { position: absolute; top: 46px; left: 80px; }
    </style>
    	
    <script type="text/javascript">
    
    function findY(obj) 
    {
    	var y = 0;
    	while (obj) 
    	{
    		y += obj.offsetTop; obj = obj.offsetParent;
    	}
    	return(y);
    }
    
    function findX(obj) 
    {
    	var x = 0;
    	while (obj) 
    	{
    		x += obj.offsetLeft;
    		obj = obj.offsetParent;
    	}
    	return(x);
    }
    
    function f_ini(obj) 
    {
    	ad1 = document.getElementById("id1");
    	x1 = findX(ad1); y1 = findY(ad1);
    	ad2 = document.getElementById("id2");
    	x2 = findX(ad2); y2 = findY(ad2);
    	ad3 = document.getElementById("id3");
    	x3 = findX(ad3); y3 = findY(ad3);
    	alert( "x1='" + x1 + "', y1='" + y1 +"'\n" +
    	       "x2='" + x2 + "', y2='" + y2 +"'\n" +
    	       "x3='" + x3 + "', y3='" + y3 +"'\n" );
    }
    
    
    </script>
    
    </head>
    <body onLoad="f_ini()">
      <div id="id1">
        Div1
        <div id="id2">Div2</div>
        <div id="id3">Div3</div>
      </div>
    </body>
    </html>
    
    Code (markup):
     
    ajsa52, Oct 12, 2007 IP
  4. enchance

    enchance Peon

    Messages:
    109
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Great, thanks!
     
    enchance, Oct 17, 2007 IP