SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Enthusiast
    Join Date
    Nov 2004
    Location
    Ontario, Canada
    Posts
    54
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Getting the "left" position of a DIV inside a relatively-positioned parent

    It's proving to be quite impossible. At least, in my browser (Firefox 2.latest).

    I've got a bunch of elements on the page (LIs, not DIVs, actually) and all of them are set to position: relative. Some LIs nest other ULs and more relatively-positioned LIs. Here's my example page: http://temp.offtonedesign.com/offsetparent/

    If you click the borders of elements deeper and deeper in the list, you'll notice that the reported "left" position is only 20px further left than its parent. The only element returning a proper "left" is the outer-most LI. For some (annoying) reason, the offsetParent property of a relatively-positioned element is just... Wrong. Or maybe I'm wrong.

    Removing the ".relative { position: relative; }" rule from the stylesheet will fix this behaviour, but alas, the thing I'm building relies quite heavily on that position: relative rule.

    So, has anyone encountered this and worked around it? Thoughts?

  2. #2
    SitePoint Enthusiast
    Join Date
    Nov 2004
    Location
    Ontario, Canada
    Posts
    54
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    If you've still got ideas, let me know. But:

    I'm thinking/hoping that this is a bug. I've devised this workaround function, which I'm hoping isn't going to break when the page gets more complicated. Think I'm good, though...

    Code:
    function getRealCoords (obj)
    {
    	var x = 0;
    	var y = 0;
    
    	while (obj.offsetParent)
    	{
    		x  += obj.offsetLeft;
    		y  += obj.offsetTop;
    
    		if (obj.offsetParent.getStyle ('position') == 'relative')
    		{
    			x += obj.getStyle ('border-left-width').toInt ();
    			y += obj.getStyle ('border-top-width').toInt ();
    		}
    
    		obj = obj.offsetParent;
    	}
    
    	return {x: x, y: y};
    }
    This is using MooTools, but it's easy enough to mod to NOT use MooTools.


Bookmarks

Posting Permissions

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