How to get the position of an element relative to the document using jQuery

Topic: JavaScript / jQuery« Prev|Next »

Answer: Use the jQuery offset() method

Using the jQuery offset() method you can easily find the position of an element relative to the document. It is only applicable for the visible elements. That means, you can get the position of elements with visibility: hidden; but not with display: none;.

  • <!DOCTYPE html>
  • <html lang="en">
  • <head>
  • <meta charset="utf-8">
  • <title>jQuery Find Element's Position Relative to the Document</title>
  • <style type="text/css">
  •     #box{
  •         width:150px;
  •         height:100px;
  •         background: orange;
  •         margin: 150px 100px;
  •     }
  • </style>
  • <script type="text/javascript" src="http://code.jquery.com/jquery.js"></script>
  • <script type="text/javascript">
  •     $(document).ready(function() {
  •         $("button").click(function(){
  •             var offset = $("#box").offset();
  •             alert("Current position of the box is: (left: " + offset.left + ", top: " + offset.top + ")");
  •         });
  •     });
  • </script>
  • </head>
  • <body>
  •     <button type="button">Get Box Position</button>
  •     <p><strong>Note:</strong> Play with the value of margin property to see how the jQuery offest() method works.</p>
  •     <div id="box"></div>
  • </body>
  • </html>

Related FAQ

Here are some more FAQ related to this topic:

 
Close

Your Feedback:

 

We would love to hear from you! Please say something.