Can I get div coordinates with jQuery?

the div position on the page changes. How can I get the y position from above?

+6
jquery
source share
3 answers

JQuery ('# Identifier'). Bias()

Returns an object with up and left offsets.

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

+10
source share

So you have options. position () or offset () .

position () It basically looks like you could use the left properties in the top CSS layer.

offset () Returns the distance from the document. It considers margins, gaskets and 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 the position values ​​match the CSS values, and the offset considers the position of the parent, the border of the parent element and the field ('p'), and padding.

http://jsfiddle.net/4wfa6/

http://docs.jquery.com/CSS

+3
source share

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

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

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

+2
source share

All Articles