On 5/13/05, Karol Hosiawa
<hosiawak-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org> wrote:
[finding the absolute positiion of an arbitrary element]>
> <script>
> function show_result() {
> obj=document.getElementById(''result'');
> posX=findPosX(obj);
> posY=findPosY(obj);
> obj.style.position=''absolute''
> obj.style.top=posY;
> obj.style.left=posX;
What you want is:
obj.style.top = posY + "px";
CSS doesn''t understand cleanly a rule like
top: 10;
left: 11;
so you need to supply units
> function findPosX(obj)
> {
> var curleft = 0;
> if (obj.offsetParent)
> {
> while (obj.offsetParent)
> {
> curleft += obj.offsetLeft
> obj = obj.offsetParent;
> }
> }
> else if (obj.x)
> curleft += obj.x;
> return curleft;
> }
>
> function findPosY(obj)
> {
> var curtop = 0;
> if (obj.offsetParent)
> {
> while (obj.offsetParent)
> {
> curtop += obj.offsetTop
> obj = obj.offsetParent;
> }
> }
> else if (obj.y)
> curtop += obj.y;
> return curtop;
> }
This would be easier to understand and more efficient in most cases if
you returned an xy coordinate, rather than having separate functions.
You should also know that Safari (at least 1.2 and lower) follows IE
Mac in needing to add document margins to the returned XY. Here''s what
I use:
function getXY (obj) {
var xy = {x:0,y:0};
while (obj) {
xy.x += obj.offsetLeft;
xy.y += obj.offsetTop;
obj = obj.offsetParent;
}
if (navigator.userAgent.indexOf("Safari") != -1 &&
document.body.leftMargin) {
xy.x += document.body.leftMargin;
xy.y += document.body.topMargin;
}
return xy;
}
> The problem is that the above JS code doesn''t display an actual x
position
> when I use floats. (The element''s actual x position is 250px; but
it is floated
> next to some other element, so the findPosX shows 30px )
I''ve never done it, but I suspect that you want to find the upper
right position of the container element, figure the upper left of the
container based on width, then calculate out the position of the
contained element. Or something.
> - Do you know any other methods than absolute positioning for displaying
> live search results similar to Google Suggest ?
>
> The ideal would be to be able to place live search fields that
won''t
> push other element around when innerHTML is called without knowing
> their absolute position.
What I''ve been doing lately is place the element below the element I
want it to appear below, in the element hierarchy, position it
absolute, give it a high z-index, but not give it a left/top. Then the
left/top are calculated from the container. When you toggle display on
that element, it is correctly positioned....
e.g.:
<div style="float:left;"><img src="foo.gif"
/><div
style="position:absolute; z-index: 100; display:none">Hello,
world!</div></div>
One warning: IE6 wants a <br /> before the absolutely positioned
element, but that messes up Safari (at least as of 1.2 -- haven''t
tested yet under 1.3 or 2.0). That requires some custom coding.
Arien