Documentation

CSS/offset

From jQuery JavaScript Library

Jump to: navigation, search

« Back to CSS

offset( )

Get the current offset of the first matched element relative to the document.
The returned object contains two Integer properties, top and left. The method works only with visible elements.
Examples:

Access the offset of the second paragraph:

var p = $("p:last");
var offset = p.offset();
p.html( "left: " + offset.left + ", top: " + offset.top );

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.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>

Click to see the offset.

    $("*", document.body).click(function (e) {
      var offset = $(this).offset();
      e.stopPropagation();
      $("#result").text(this.tagName + " coords ( " + offset.left + ", " +
                                      offset.top + " )");
    });

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.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>

NameType