2

How to get the real coordinates (top and left) in the screen in pure JavaScript?

Methods I found use recursion on parent elements to calculate the coordinates, but it seems that they do not cover all the webpage, like here, here and here

Community
  • 1
  • 1
ubugnu
  • 1,004
  • 2
  • 15
  • 30

1 Answers1

9

Since I browsed the net for a long time to find a solution which do not use any javascript library, and since all answers I found advise to use the jQuery method .offset(), I decided to copy this methode and make a small pure javascript offset() function that do the same thing:

function isWindow( obj ) {
    return obj != null && obj === obj.window;
}
function getWindow( elem ) {
    return isWindow( elem ) ? elem : elem.nodeType === 9 && elem.defaultView;
}
function offset( elem ) {

    var docElem, win,
        box = { top: 0, left: 0 },
        doc = elem && elem.ownerDocument;

    docElem = doc.documentElement;

    if ( typeof elem.getBoundingClientRect !== typeof undefined ) {
        box = elem.getBoundingClientRect();
    }
    win = getWindow( doc );
    return {
        top: box.top + win.pageYOffset - docElem.clientTop,
        left: box.left + win.pageXOffset - docElem.clientLeft
    };
};

You can try it here on this page (we'll take an element that is at the bottom of the page, the answer area, since it's there that other methods fail), run on the console:

offset(document.getElementById('wmd-input')).top == $('#wmd-input').offset().top

If you get true, this means that it works ;-)

ubugnu
  • 1,004
  • 2
  • 15
  • 30