tags:

views:

62

answers:

3

the postion of the div on the page varies. How can I get the y position from the top?

+6  A: 

jQuery('#id').offset()

Returns an object with top and left offsets.

http://api.jquery.com/offset/

Koobz
+1  A: 

You may also be interested in the position function which gets the position relative to an offset parent (vs offset which gets it relative to the document)

var position = $('#id').position();

http://api.jquery.com/position/

bendewey
+2  A: 

So you have to 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 but not paddings, nor borders.

   <style>
     .cont {
        position: absolute;
        top: 100px;
        left: 100px;
        border: solid 3px black;
     }
     p { 
        margin: 20px; 
        padding: 20px; 
        border: solid 2px black;
        position: absolute; 
        top: 20px; 
        left: 20px; 
     }
    </style>

    <div class="cont">
         <p>Hello World!</p>
    </div>

    $('p').position() => { top: 20, left: 20 }
    $('p').offset() => { top: 143, left : 143 }

Notice how position stays as the same values as the CSS values, and offset considers the position of the parent, the border of the parent and the element's ('p') margin.

http://docs.jquery.com/CSS

UberNeet