the postion of the div on the page varies. How can I get the y position from the top?
To get the value of div content in jQuery, use the text() method. The text( ) method gets the combined text contents of all matched elements. This method works for both on XML and XHTML documents.
In jQuery, the class and ID selectors are the same as in CSS. If you want to select elements with a certain class, use a dot ( . ) and the class name. If you want to select elements with a certain ID, use the hash symbol ( # ) and the ID name.
jQuery position() MethodThe position() method returns the position (relative to its parent element) of the first matched element. This method returns an object with 2 properties; the top and left positions in pixels.
The offset() method set or returns the offset coordinates for the selected elements, relative to the document. When used to return the offset: This method returns the offset coordinates of the FIRST matched element. It returns an object with 2 properties; the top and left positions in pixels.
jQuery('#id').offset()
Returns an object with top and left offsets.
http://api.jquery.com/offset/
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, paddings, 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 are the same as the CSS values, and offset considers the position of the parent, the border of the parent and the element's ('p') margin and padding.
http://jsfiddle.net/4wfa6/
http://docs.jquery.com/CSS
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With