Get floating position

Browsers seem to not make the left and top properties of floating elements available through the DOM. So to get the real position on screen for an element, you have to sum up all the offsetLeft and offsetTop value of itself and all offsetParents.

For this I found a nice function at devshed.com. I modified it a bit and also made it more flexible:

function relative_to_absolute( object, stopper ) {
    this.X = 0;
    this.Y = 0;
    while (object.offsetParent && object!=stopper) {
        this.X += object.offsetLeft;
        this.Y += object.offsetTop;
        object = object.offsetParent;
    }
    return this;
}

If you need the position: fixed; style position, you can use the call:

newpos = relative_to_absolute( document.getElementById('myObj'), document.getElementsByTagName('body')[0] );

or use this somewhat simpler function:

function relative_to_fixed( object ) {
    this.X = 0;
    this.Y = 0;
    while (object.offsetParent && object!=document.getElementsByTagName('body')[0]) {
        this.X += object.offsetLeft;
        this.Y += object.offsetTop;
        object = object.offsetParent;
    }
    return this;
}

 
snippets/javascript/get-floating-position.txt · Last modified: 2009-07-24 13:20.07 by mbirth
 
Except where otherwise noted, content on this wiki is licensed under the following license:CC Attribution-Noncommercial-Share Alike 3.0 Unported
Recent changes RSS feed Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki Contents powered by Club-Mate Contents powered by BassDrive.com Labelled with ICRA