version added: 1.2
Get the current offset of the first matched element, in pixels, relative to the document.
The returned object contains two
Float
properties, top and left. Browsers usually round these values to the nearest integer pixel for actual positioning. The method works only with visible elements.
Examples
Example 1
Access the offset of the second paragraph:Example 1 - Full source:
<!DOCTYPE html> <html> <head> <script src="http://code.jquery.com/jquery-1.5.js"></script> <script> $(document).ready(function(){ var p = $("p:last"); var offset = p.offset(); p.html( "left: " + offset.left + ", top: " + offset.top ); }); </script> <style> p { margin-left:10px; } </style> </head> <body> <p>Hello</p><p>2nd Paragraph</p> </body> </html>
Example 2
Click to see the offset.Example 2 - Full source:
<!DOCTYPE html> <html> <head> <script src="http://code.jquery.com/jquery-1.5.js"></script> <script> $(document).ready(function(){ $("*", document.body).click(function (e) { var offset = $(this).offset(); e.stopPropagation(); $("#result").text(this.tagName + " coords ( " + offset.left + ", " + offset.top + " )"); }); }); </script> <style> p { margin-left:10px; color:blue; width:200px; cursor:pointer; } span { color:red; cursor:pointer; } div.abs { width:50px; height:50px; position:absolute; left:220px; top:35px; background-color:green; cursor:pointer; } </style> </head> <body> <div id="result">Click an element.</div> <p> This is the best way to <span>find</span> an offset. </p> <div class="abs"> </div> </body> </html>
Was this information helpful?

