5

I need to calculate the width between two elements but I'm not sure how I would go about this. Say I have the following:

<ul id="foo">
    <li style="width:10px;"><a href="#">1</a></li>
    <li style="width:20px;"><a href="#">2</a></li>
    <li style="width:30px;"><a href="#">3</a></li>
</ul>

How would I calculate the distance between 1 and 3 (answer being 20px)? The width can be variable as can the number of list items? (I'm using the Prototype framework)

Thanks

Rob W
  • 341,306
  • 83
  • 791
  • 678
Rich
  • 209
  • 1
  • 4
  • 6

2 Answers2

7

If you mean the horizontal distance between two elements, you need the difference between the top right coord of the left element and the top left coord of the right element. The top right coord of an element is just the top left coord plus its width, as given in Pekka's answer.

To get the top left position an element, you can use the javascript method offsetLeft(). This returns the offset in the x dimension between an element and its parent. You iterate up the DOM tree adding successive offsetLeft's until you get to the document root. The resulting sum is your x position. The excellent Quirksmode shows you how to do this.

Edit: for completeness, I include example javascript to find an element's position:

function getNodePosition(node) {     
    var top = left = 0;
    while (node) {      
       if (node.tagName) {
           top = top + node.offsetTop;
           left = left + node.offsetLeft;       
           node = node.offsetParent;
       } else {
           node = node.parentNode;
       }
    } 
    return [top, left];
}
Richard H
  • 38,037
  • 37
  • 111
  • 138
  • Thanks guys, you've got me closer to solving this (my real world example is a lot more complex, but you've got me on the right track!) – Rich Dec 13 '09 at 15:18
2

If you mean the horizontal distance, I would say it's something like:

X position of element 2
minus 
x position of element 1 plus width of element 1

to get the width, use getWidth()

to get the position, positionedOffset() might be the right thing, I'm not 100% sure and it depends on your elements' positioning.

And a general caveat, if your elements have padding, it will depend on the browser (IE / FF) whether the padding is calculated into the width or not. This may also apply to the border. You will have to play around and see.

Zuul
  • 16,217
  • 6
  • 61
  • 88
Pekka
  • 442,112
  • 142
  • 972
  • 1,088