...

View Full Version : Absolute Position of element inside scrollable div



ma.mazmaz
04-22-2009, 01:33 AM
I have an element inside a <div> with overflow:auto

I have been trying to find the absolute position of that element. The following code is what I have been using and does not work...


function ElemAbsPos(obj){
var x=0;
var y=0;

while(obj){
y+=obj.offsetTop;
y-=obj.scrollTop;
x+=obj.offsetLeft;
x-=obj.scrollLeft;
obj=obj.offsetParent;
}

return [x,y];
}

TinyScript
04-22-2009, 03:39 AM
have you tried getComputedStyle
https://developer.mozilla.org/En/DOM:window.getComputedStyle

ma.mazmaz
04-22-2009, 09:30 PM
Yes, I have just tried that. Since I am trying to find the position of the element as it is displayed globally (based on body element) on the page, that method does not work. It will give me the position as based upon its parent, without taking into account scrolling or any parent elements.

TinyScript
04-22-2009, 11:25 PM
Yes, I have just tried that. Since I am trying to find the position of the element as it is displayed globally (based on body element) on the page, that method does not work. It will give me the position as based upon its parent, without taking into account scrolling or any parent elements.

use that on the parent element too. I guess I must not understand your problem

randomuser773
04-24-2009, 11:49 PM
Since I am trying to find the position of the element as it is displayed globally (based on body element) on the page,If by that you mean its current displacement from the top of the body element, does it make sense to subtract the scrollTop/Left of the body element? This isn't tested but may be worth a try:
function ElemAbsPos(obj){
var x=0;
var y=0;

while(obj){
y += obj.offsetTop;
y -= obj.offsetParent ? obj.scrollTop : 0;
x += obj.offsetLeft;
x -= obj.offsetParent ? obj.scrollLeft : 0;
obj=obj.offsetParent;
}

return [x,y];
}



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum