manu padmanabhan manu padmanabhan - 8 days ago 7
Javascript Question

Custom Drag & Drop not working perfectly

I want to drag a div and drop anywhere in its parent div . For dragging I use css style

draggable="true"


and for drop, I use 'mousemove' event X and Y values and use this values for div top and left .The code I used is



$(".drop").mousedown(function () {
$(this).mousemove(function (e) {
var k = e.clientX ;
var f = e.clientY;

$(".drop").text(k+ ", " + f);
$(".drop").css("top",f);
$(".drop").css("left",k);
});
}).mouseup(function () {

$(this).unbind('mousemove');


}).mouseout(function () {
$(this).unbind('mousemove');
});

.drop{
position: absolute;
left: 300;
top: 200; /* set these so Chrome doesn't return 'auto' from getComputedStyle */
width: 200px;
background: rgba(255,255,255,0.66);
border: 2px solid rgba(0,0,0,0.5);
border-radius: 4px; padding: 8px;
z-index: 3;
}
.gridPart{
padding: 20px;
background-color: #FFF;
border-radius: 5px;
margin: auto;
margin: 20px;
padding-right: 0px;
padding-bottom: 3px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="gridpart">

<div class="drop" draggable="true" ></div>
<div>





Now it's drag & drop if I drag with increasing left value. But if I drag with decreasing left value it's not dropping. And how I stop the drag if it reach the end of the main div(GridPart)?

Answer

I have fixed your code. All you did is quite good but you should have to use the mousemove event with $(document) element and not with the div. Since when you drag backwards, mouse movement is going out of the div and so its no longer dragging.

Also, as you used custom dragging, you don't need to use draggable="true".

$(".drop").mousedown(function () {
    $(document).mousemove(function (e) {
       var k = e.clientX;
        var  f = e.clientY;
    
         $(".drop").text(k+ ", " + f);
         $(".drop").css("top", f + 'px');
          $(".drop").css("left", k + 'px');
    }); 
 });

$(document).mouseup(function () {
    $(document).unbind('mousemove');        
});
.drop{
   position:  absolute;
    left: 300;
    top: 200; /* set these so Chrome doesn't return 'auto' from getComputedStyle */
    width: 200px; 
    background: rgba(255,255,255,0.66); 
    border: 2px  solid rgba(0,0,0,0.5); 
    border-radius: 4px; padding: 8px;
    z-index: 3;
}
.gridPart{
	padding: 20px;
    background-color: #FFF;
    border-radius: 5px;
    margin: auto;
    margin: 20px;
    padding-right: 0px;
    padding-bottom: 3px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="gridpart">
  
     <div class="drop" ></div>
  <div>