views:

4759

answers:

2

Can someone show me how to get the .top & .left position of a div or span tag when one is not specified?

ie:

<span id='11a' style='top:55px;' onmouseover="GetPos(this);">stuff</span>
<span id='12a' onmouseover="GetPos(this);">stuff</span>

In the above, if i do:

document.getElementById('11a').style.top

The the value of 55px is returned. However if i try that for span '12a', then nothing gets returned. I have a bunch of div/spans on a page that i cannot specify the top/left properties for, but i need to display a div directly under that element.

Thanks for lookin :-)

+6  A: 

This function will tell you the x,y position of the element relative to the page. Basically you have to loop up through all the element's parents and add their offsets together.

function getPos(el) {
    // yay readability
    for (var lx=0, ly=0;
         el != null;
         lx += el.offsetLeft, ly += el.offsetTop, el = el.offsetParent);
    return {x: lx,y: ly};
}

However, if you just wanted the x,y position of the element relative to its container, then all you need is:

var x = el.offsetLeft, y = el.offsetTop;

To put an element directly below this one, you'll also need to know its height. This is stored in the offsetHeight/offsetWidth property.

var yPositionOfNewElement = el.offsetTop + el.offsetHeight + someMargin;
nickf
A: 

If using jQuery (don't implement it only for this solution but) you can use the more succinct code.

left = $('.span').offset().left;
top = $('.span').offset().top;
alex