Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

absolute position of relativly positioned element

Status
Not open for further replies.

flourish

Programmer
Jun 11, 2001
4
US
I'm attempting to find the absolute x and y value of some page elements that are themselves relativly positioned. Is there some way to do this? I can use just about any type of element I need to. I just need to be able to place it in the normal flow of the document layout, and then get its x and y positions relative to the browser window using javascript.
Any help would be greatly appretiated.
 
in IE, the solution is simple:

elementobject.offsetTop and
elementobject.offsetLeft

If it is inside some element that defines its own coordinate space, you may need to use some sort of recursive function to get the proper x,y position, but this should work 99% of the time. jared@eae.net -
 
Even easier in NS - you've got .x and .y. To sum up:

if(document.all)
{
var myx = yourelement.offsetLeft;
var myy = yourelement.offsetTop;
}
else
{
var myx = yourelement.x;
var myy = yourelement.y;
}

If you find an easy way to locate yourself within a table I'd like to know - recursing up the doc isn't very nice.

S
 
It's the tables the element is nested in that's giving me the problems. I need a way to find the element's position relative to the page, not the table containing that element. When I write the javascript I wont know how many tables the element might be nested in. Is there some way to programmaticly climb up the document tree, getting the x and y value of every parent of a particular element?

I've run into this problem a few times. I don't understand why JavaScript doesn't have the functionality to simply return the absolute position of an element in relation to the window. It just never felt like a lot to ask.
 
you can try these:

function getTop(obj)
{
var tot = 0;

while(obj.parentNode)
{
tot += obj.clientTop + obj.offsetTop;
obj = obj.parentNode;
}

return tot;
}

function getLeft(obj)
{
var tot = 0;

while(obj.parentNode)
{
tot += obj.clientLeft + obj.offsetLeft;
obj = obj.parentNode;
}

return tot;
} jared@eae.net -
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top