JSFiddle - React, Tailwind, and code Playground
HTML
<div id="targetElement">
<div class="positionDiv" id="position"><img src="http://searchengineland.com/figz/wp-content/seloads/2012/05/penguin.jpg"></div>
</div>
CSS
#targetElement {
width:400px;
height: 250px;
border:1px solid #333;
overflow:hidden;
}
.positionDiv {
width: 200px;
height: 150px;
position:relative;
}
.positionDiv img {
min-height: 150px;
max-width: 200px;
position:absolute;
}
JavaScript
var right = 0;
var bottom = 0;
var top = 0;
var left = 0;
adjustment = 0;
$( "img" ).draggable({
start: function ( event, ui ) {
bottom = $(this).parent().parent().height();
right = $(this).parent().parent().width();
},
drag: function( event, ui ) {
if(ui.position.top <= top-adjustment)
ui.position.top = top-adjustment;
if(ui.position.left <= left-adjustment)
ui.position.left = left-adjustment;
console.log(ui.position.left);
if(ui.position.left+$(this).width() >= right+adjustment)
ui.position.left = right-$(this).width()+adjustment;
if(ui.position.top+$(this).height() >= bottom+adjustment)
ui.position.top = bottom-$(this).height()+adjustment;
}
});