lunes, 10 de marzo de 2014

jquery get element position

Can I get the coordinates of a div with JQuery?

The answer is yes:

$('#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.


 <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>

    <div class="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
 

    <div class="someClass">
         <span>Hello World!</span>
    </div>

    $('span').position({ top: 20, left: 20 }) 
    $('span').offset({ top: 143, left : 143 })