JSFiddle - React, Tailwind, and code Playground
HTML
<script src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script>
<h1>How to restrict drag (disable) in the block?</h1>
<div id="block">
<div id="border">
<div id="drag" style="left:200px;">some text</div>
</div>
</div>
CSS
h1, #drag {
font: bold 1.0em arial, helvetica, tahoma, verdana, sans-serif;
margin: 10px 0px;
text-align: center;
}
#block {
border: 1px solid #DDD;
overflow: hidden;
width: 100%;
}
#border {
border: 1px solid red;
margin: 0px auto;
overflow: hidden;
width: 70%; /*important*/
height: 150px;
}
#drag {
background: #DDD;
cursor: default;
position: absolute;
top: 50px;
width: 54px;
height: 45px;
}
JavaScript
$(function() {
var x = 0,
setElementMove = 0,
getElementMove = $('#drag'),
boundary = $('#border');
getElementMove.mousedown(function(event) {
x = event.clientX + $(document.body).position().left - parseInt($(this).css('left'));
setElementMove = true;
if (typeof event.preventDefault != 'undefined') {
event.preventDefault();
return false;
}
});
getElementMove.ondragstart = function() {
return false;
};
$(document).mouseup(function() {
setElementMove = false;
});
$(document).mousemove(function(event) {
var eleft = event.clientX + $(document.body).position().left - x;
if (eleft > boundary.offset().left && (eleft + getElementMove.width() < boundary.offset().left + boundary.width() ) ) {
if (setElementMove) {
getElementMove.css('left', eleft + 'px');
}
}
});
});