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 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Jun 2009
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    How Do I Get the Absolute Position of a DIV?

    Before you immediately give me an answer, let me describe fully what I'm trying to do, as it's not as simple as the title suggests.

    I need to get the absolute position of a DIV (top and left properties) relative to the viewport/screen.

    I've tried using .offsetTop and .offsetLeft, but these return the top and left properties relative to the DIV's immediate parent element, not the viewport (unless of course the DIV is top-level and not contained in any other DIVs).

    So, is there any way to retrieve the absolute position of a DIV relative to the viewport, even if that DIV is nested in other DIVs?

    Thanks for any help!

  • #2
    New Coder
    Join Date
    Nov 2008
    Posts
    59
    Thanks
    5
    Thanked 4 Times in 4 Posts
    Go through all the parents adding up all the positions, like so:

    Code:
    var el=document.getElementById('id');
    var cl=0,ct=0;
    if (el.offsetParent)
    {
    	do
    	{
    		cl+=el.offsetLeft;
    		ct+=el.offsetTop;
    	}
    	while(el=el.offsetParent);
    }
    Last edited by scrappy; 06-28-2009 at 07:00 PM.


  •  

    Tags for this Thread

    Posting Permissions

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