How to get the div coordinates with JQuery?

How to get the div coordinates with JQuery and vanilla Javascript?

 
This is specially helpful if you are creating a mouse over porpup, or a custom tooltip and you have to account for the position of you div in the screen or maybe related to other elements, to avoid overlap visibility over other elements in the page, etc.
div coordinates

There are two ways of doing this, with .position() method and .offset() method

$('#elementID').offset()

Returns an object with top and left offsets. (http://api.jquery.com/offset/)

Actually there is two options:
position() or offset().

position() Basically similar to what you could use in the CSS top, left properties.

offset() Will return the distance relative to the document. This considers margins, paddings, and borders.

 

book

Book Tip

Speaking JavaScript: An In-Depth Guide for Programmers
Like it or not, JavaScript is everywhere these days—from browser to server to mobile—and now you, too, need to learn the language or dive deeper than you have. This concise book guides you into and through JavaScript, written by a veteran programmer who once found himself in the same position.

Amazon

 

Here is an example:

<style>
  .someClass{
        position: absolute;
        top:100px;
        left:100px;
        border: solid 3px black;
  }
  span {
     margin:20px;
     padding:20px;
     border: solid 2px black;
     position: absolute;
     top:20px;
     left:20px;
 }
</style>
<divclass="someClass"><span>Hello World!</span></div>
    $('span').position() => { top: 20, left: 20 }
    $('span').offset() => { top: 143, left : 143 }

You can also set the position() and the offset

<divclass="someClass"><span>Hello World!</span></div>
    $('span').position({ top: 20, left: 20 })
    $('span').offset({ top: 143, left : 143 })
 

 

How to achieve the same result with vanilla Javascript?

This function will tell you the div coordinates, (x,y position) of the element relative to the page. Basically you have to loop up through all the element’s parents and add their offsets together.

function getPosition(elem) {
    for (var lx=0, ly=0;
         elem != null;
         lx += elem.offsetLeft, ly += elem.offsetTop, elem = elem.offsetParent);
    return {x: lx,y: ly};
}

If you just wanted the x,y position of the element relative to its container, then all you need is:

var x = elem.offsetLeft;
var y = elem.offsetTop;

If you know other way to achieve the same result please feel free to share with us, you can live a comment in the blog or you can contact me @JoMendezdev on Twitter.