JS Script Get Element Position With Scroll Support

25 בנובמבר 2008

Well,


I was looking on the web for JavaScript fuction that return any DOM element position and also consider browser scroll.


I finally came up with the solution and wanted to share it with you.


In order that the script will work you need reference to Prototype JavaScript Framework.


Well here is the JavaScript code:

function getDocumentWindow(doc) {     return (doc.parentWindow || doc.defaultView);

}


function getPosRelativeToWindow(element, topWindow, considerScrollOffset) {

    var l = 0, t = 0;    var pos, doc, w, lastWindow;

   topWindow = topWindow || top;

   while (element) {

       doc = element.ownerDocument;

      w =
this.getDocumentWindow(doc);

      lastWindow = (!w || w == topWindow);

     if (lastWindow)

         pos = Position.cumulativeOffset(element);


    else


         pos = Position.page(element);

    if (considerScrollOffset) {         var p = Position.realOffset(element);

        l -= p[0];


        t -= p[1];


    }


    l += pos[0];


    t += pos[1];

    if (lastWindow)         break;

    element = w.frameElement;


    }

    return [l, t];

}


 


Cheers,


Rotem

Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*