How to Move a DIV Inside Another Parent DIV Using Mouse Events in jQuery
$(document).ready(function () {
var drag = null; var Top = null; var Left = null;
var O = $("#Outside").offset();
var outsideTop = O.top;
var outsideRight = O.left + $("#Outside").width();
var outsideBottom = O.top + $("#Outside").height();
var outsideLeft = O.left; var move;
$('#Box').mousedown(function (e) {
$("#Box").css({ "background-color": "violet" });
drag = $(e.target);
drag.css({ "cursor": "move" });
var box = $("#Box").offset();
Top = e.pageY - box.top;
Left = e.pageX - box.left;
});
$('body').on('mouseup', function (e) {
$("#Box").css({ "background-color": "skyblue", "cursor": "default" });
$('body').unbind('mousemove');
drag = null;
});
$(document).on('mousemove', function (e) {
if (drag) {
drag.css({ "background-color": "greenyellow" });
var cursorTop = e.pageY - Top;
var cursorLeft = e.pageX - Left;
var cursorRight = (e.pageX - Left) + $("#Box").width();
var cursorBottom = (e.pageY - Top) + $("#Box").height();
if (((cursorTop >= outsideTop) && (cursorTop <= outsideBottom)) && ((cursorLeft >= outsideLeft) && (cursorLeft <= outsideRight)))
if ((((cursorRight) >= outsideLeft) && ((cursorRight) <= outsideRight)) && ((cursorBottom >= outsideTop) && ((cursorBottom) <= outsideBottom))) {
drag.offset({
top: e.pageY - Top,
left: e.pageX - Left
});
}
}
}).on('mouseup', function () {
$('body').unbind('mousemove');
drag=null;
});
});
#Outside
{
height:500px;
width:1000px;
position:absolute;
background-color:navajowhite;
border:5px solid blue;
margin-left:120px;
margin-top:18px;
}
#Box
{
height:100px;
width:100px;
/*position:absolute;*/
background-color:lightskyblue;
border:4px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-3.0.0.min.js"></script>
<div id="Outside">
<div id="Box"></div>
</div>
While using Chrome browser to test the result, I encountered an issue where the mouseup event is not triggered if the mousemove event is too fast. I am seeking a solution to this problem.