Search code examples
javascriptprototypejs

How do I calculate the width between two elements?


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


Solution

  • 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];
    }