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

    Absolute Position of element inside scrollable div

    I have an element inside a <div> with overflow:auto

    I have been trying to find the absolute position of that element. The following code is what I have been using and does not work...

    Code:
    function ElemAbsPos(obj){
    	var x=0;
    	var y=0;
    	
    	while(obj){
    		y+=obj.offsetTop;
    		y-=obj.scrollTop;
    		x+=obj.offsetLeft;
    		x-=obj.scrollLeft;
    		obj=obj.offsetParent;
    	}
    	
    	return [x,y];
    }

  • #2
    Regular Coder
    Join Date
    Mar 2009
    Location
    Portland Oregon
    Posts
    690
    Thanks
    44
    Thanked 63 Times in 62 Posts

  • #3
    New to the CF scene
    Join Date
    Apr 2009
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Yes, I have just tried that. Since I am trying to find the position of the element as it is displayed globally (based on body element) on the page, that method does not work. It will give me the position as based upon its parent, without taking into account scrolling or any parent elements.

  • #4
    Regular Coder
    Join Date
    Mar 2009
    Location
    Portland Oregon
    Posts
    690
    Thanks
    44
    Thanked 63 Times in 62 Posts
    Quote Originally Posted by ma.mazmaz View Post
    Yes, I have just tried that. Since I am trying to find the position of the element as it is displayed globally (based on body element) on the page, that method does not work. It will give me the position as based upon its parent, without taking into account scrolling or any parent elements.
    use that on the parent element too. I guess I must not understand your problem

  • #5
    Banned
    Join Date
    Nov 2008
    Location
    not found
    Posts
    284
    Thanks
    0
    Thanked 53 Times in 51 Posts
    Quote Originally Posted by ma.mazmaz View Post
    Since I am trying to find the position of the element as it is displayed globally (based on body element) on the page,
    If by that you mean its current displacement from the top of the body element, does it make sense to subtract the scrollTop/Left of the body element? This isn't tested but may be worth a try:
    Code:
    function ElemAbsPos(obj){
    	var x=0;
    	var y=0;
    	
    	while(obj){
    		y += obj.offsetTop;
    		y -= obj.offsetParent ? obj.scrollTop : 0;
    		x += obj.offsetLeft;
    		x -= obj.offsetParent ? obj.scrollLeft : 0;
    		obj=obj.offsetParent;
    	}
    	
    	return [x,y];
    }


  •  

    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
    •