When a drag element is added to the body, it is not inside the element #box
at all when dragged, so you need to subtract the position of the containing element, and in your case also the border, to get the correct values
$(function(){
var box = $('#box').offset(),
border = parseInt($('#box').css('border-width').replace(/\D/g,''), 10);
$( "#draggable" ).draggable({
containment: "#box",
drag: function(){
var offset = $(this).offset();
var xPos = offset.left - box.left - border;
var yPos = offset.top - box.top - border;
$('#posX').val('x: ' + xPos);
$('#posY').val('y: ' + yPos);
}
});
});
FIDDLE
adeneo
source
to share