We want people to be able to create a thumbnail version of an uploaded image by dragging the image around in a fixed size div. The image position will be saved in a database.
Using the following code the image is draggable and won’t position itself outside the containing div.
My problem is that the final x and final y positions are not coming up with the numbers we expect. If the image is positioned with the top left corner of the photo in the top left corner of the containing div we are expecting 0 and 0 for x and y. Right now x is showing 59 and y is 51. So the x and y are currently based off of the position on the page, not of the containing div.
I think this is an easy fix but it’s eluded me for several hours now.
$(document).ready(function() {
$("#drag").draggable({cursor: 'move',drag: function(){
var position = $(this).position();
var xPos = position.left;
var yPos = position.top;
$('#posX').text('x: ' + xPos);
$('#posY').text('y: ' + yPos);
},
stop: function(){
var finalPosition = $(this).position();
var finalxPos = finalPosition.left;
var finalyPos = finalPosition.top;
$('#finalX').text('Final X: ' + finalxPos);
$('#finalY').text('Final Y: ' + finalyPos);
}
}).bind('dragstop', function(e, ui) {
if (ui.position.top > 0) {
$(this).css('top', 0);
}
if (ui.position.left > 0) {
$(this).css('left', 0);
}
var bottom = -($(this).height() - $(this).parent().height()),
right = -($(this).width() - $(this).parent().width());
if (ui.position.top < bottom) {
$(this).css('top', bottom);
}
if (ui.position.left < right) {
$(this).css('left', right);
}
});
});
Here’s the HTML
<body>
<div id="container">
<div class="imageBox">
<img id="drag" src="images/chicago.jpg">
</div>
</div>
<ul>
<li id="posX"></li>
<li id="posY"></li>
<li id="finalX"></li>
<li id="finalY"></li>
</ul>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
<script src="js/imagePositioning.js"></script>
</body>
.offset() is relative to the page, not to the container. You want to use .position().
Here’s the relevant bit from the .offset() manual page: