jQuery: difference between position() and offset()

The difference between the jQuery's position() and offset() methods concerns the way by which the top and left coordinates are calculated. The former always refers to the parent element's coordinates, while the latter may calculate such coordinates by taking into account the offset of the parent from the whole page when this element is positioned. If the parent element is not positioned, that is, if its CSS position is static, then both methods return the same results. Let' see an example.

We have the following structure:

<div id="container">
	<div id="test"></div>
</div>

With the following styles:

#container {
	width: 600px;
	height: 400px;
	background: #ccc;
	position: relative;
}

#test {
	width: 100px;
	height: 100px;
	background: #d34545;
	position: relative;
}

As you can see, both elements are relatively positioned. If we try to move the test element by taking its offsets first and then adding 50 pixels to these coordinates, you'll surely notice the difference:

$(function() {

  var test = $('#test', '#container');
  var triggerPosition = $('#position');
  var triggerOffset = $('#offset');
  
  triggerPosition.click(function(event) {
  
    test.css({top: 0, left: 0});
  
    var top = test.position().top;
    var left = test.position().left;
    
    test.animate({
      top: top + 50,
      left: left + 50
    }, 'slow');
    
    event.preventDefault();
  
  
  });
  
  triggerOffset.click(function(event) {
  
    test.css({top: 0, left: 0});
  
    var top = test.offset().top;
    var left = test.offset().left;
    
    test.animate({
      top: top + 50,
      left: left + 50
    }, 'slow');
    
    event.preventDefault();
  
  
  });



});

When we use the offset() method, the element is positioned at a greater distance than the distance obtained from the first animation. This happens because jQuery adds the offset of the parent element calculated from the whole page and then sum it up with our custom value. You can see the test below.

Test

Live test

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.