Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    CWG
    CWG is offline
    New to the CF scene
    Join Date
    May 2006
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Get the absolute position of elements in the DOM

    I have some div tags that I want to capture the xy coordinates using javascript. It seems that if I do not preset the absolute positioning values I cannot access them.

    For example I have a div tag nested in a table:

    <table>
    <tr>
    <td width="400">some other code</td>
    <td width="380">
    <div Id="DivId">div content</div>
    </td>
    </tr>
    </table>

    You will notice the positioning of the div tag is drive by the table it is nested in. The value of document.getElementById('DivId').style.left and document.getElementById('DivId').style.right is null. It sems I can only get these values of they are preset.

    If someone could enlighten me with the solution I would be greate appreciative.

  • #2
    Senior Coder
    Join Date
    Feb 2006
    Location
    USA
    Posts
    1,013
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Learn CSS. | SSI | PHP includes | X/HTML Validator | CSS validator | Dynamic Site Solutions
    Java != JavaScript && JScript != JavaScript
    Design/program for Firefox (and/or Opera), apply fixes for IE, not the other way around.

  • #3
    Kor
    Kor is offline
    Red Devil Mod Kor's Avatar
    Join Date
    Apr 2003
    Location
    Bucharest, ROMANIA
    Posts
    8,478
    Thanks
    58
    Thanked 379 Times in 375 Posts
    I should add that you must probably consider the scroll position as well...
    KOR
    Offshore programming
    -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*

  • #4
    Regular Coder
    Join Date
    Mar 2006
    Posts
    726
    Thanks
    35
    Thanked 132 Times in 123 Posts
    Code:
    function whereAmI(who,wch){
    	var L=0, R=0;
    	var pa=who;
    	while(pa.parentNode){
    		L+= ( pa.offsetLeft)? pa.offsetLeft: 0;
    		R+= (pa.offsetTop)?  pa.offsetTop: 0;	
    
    		if(pa==document.body || wch===false)break;
    		pa= pa.parentNode;
    		
    	}
    	var A=[L,R];
    	return(wch===1 || wch=== 2)?  A[wch]: A;
    }
    This returns the left and top coordinates of the element sent
    as the first argument. If the second argumentis a literal false,
    it returns the position relative to its parent, otherwise it returns the
    position relative to the body (includes the body offsets as well).

    You can send an integer (1 or 2) if you just want the
    first(left) or second(right) coordinate.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •