I have two divs in my page, div1 contains 3 droppable images (p1,p2,p3) and div2 contains 3 draggable images (g1,g2,g3): each gi can be dropped on any pi, it should stick to the top left corner of the droppable item. If it is not dropped on a pi, it should return to its original position. After being dropped on a pi, gi can be dragged again and dropped to another pi. However, each droppable can keep only one droggable at a time.
My code is:
<style>
#div1, #div2 {
position:relative;
width:500px;
height:500px;
border:3px solid black;
}
.drag,.drop,.over {
position:absolute;
width:30px;
height:30px;
}
.drop {
border:1px solid green;
}
.over {
border:1px solid gray;
}
</style>
<script>
$(document).ready(function () {
$(function() {
$('.drag').draggable({
cursor: 'move',
helper:'clone'
});
$('.drop').droppable({
over: function() {
$(this).removeClass('.drop').addClass('over');
},
out: function() {
$(this).removeClass('over').addClass('drop');
},
drop: function(ev, ui) {
var dropped = ui.draggable;
var droppedOn = $(this);
if ($(this).children().length > 0) return false;//each droppable just keep one draggable
$(dropped).detach().css({top: 0,left: 0}).appendTo(droppedOn);//stick to the left corner of droppable
//$(this).append($(ui.draggable).clone());
$(this).removeClass('over').addClass('drop');
}
});
});
$('body').append("<div id='div1'></div>");
$('body').append("<div id='div2'></div>");
$('#div1').append("<img id='p1'class='drop' style='width:50; height:50; top: 50px; left:50px;' src='images/1.jpg'></img>");
$('#div1').append("<img id='p2'class='drop' style='width:50; height:50; top:250px; left:50px;' src='images/2.jpg'></img>");
$('#div1').append("<img id='p3'class='drop' style='width:50; height:50; top:350px; left:50px;' src='images/3.jpg'></img>");
$('#div2').append("<img id='g1'class='drag' style='width:50; height:50; top: 50px; left:50px;' src='images/11.jpg'></img>");
$('#div2').append("<img id='g2'class='drag' style='width:50; height:50; top:250px; left:50px;' src='images/12.jpg'></img>");
$('#div2').append("<img id='g3'class='drag' style='width:50; height:50; top:350px; left:50px;' src='images/13.jpg'></img>");
});
</script>
My problem: when I drop a gi on a pi, the gi is disappeared (and therefore, I cannot drag and drop it on another item, It does not stick to the left corner of the corresponding pi). How can I prevent it from being disappeared? And stick it to droppable object?
(If I remove “$(dropped).detach().css({top: 0,left: 0}).appendTo(droppedOn);” and “helper:clone”, gi does not disappear after being dropped, but it can move freely.)