Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I get the coordinates of a div with JQuery?

Tags:

jquery

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

like image 237
zsharp Avatar asked Jan 27 '10 04:01

zsharp


People also ask

How do I get text inside a div using jQuery?

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.

How do I target a specific element in jQuery?

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.

How do I set relative position in jQuery?

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.

What is offset () top in jQuery?

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.


3 Answers

jQuery('#id').offset()

Returns an object with top and left offsets.

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

like image 193
Koobz Avatar answered Nov 09 '22 13:11

Koobz


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

like image 43
guzart Avatar answered Nov 09 '22 13:11

guzart


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/

like image 34
bendewey Avatar answered Nov 09 '22 11:11

bendewey