JQuery draggable() clone and then move

202 Views Asked by At

I want to drag a clone of an object with the classname "draggable" into a dropzone and then also be able to move the new object within the dropzone.

This is what I have done so far and it allmost works, but it also makes a clone when I move the object within the dropzone. How can I avoid this?

.draggable{
    width: 100px;
    height: 100px;
    background-color: lightblue;
}
#dropZone{
    width:300px;
    height:300px;
    background:yellow;
    position:relative;
}
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script>

<script>
$(document).ready(function(){
    $( ".draggable" ).draggable({
        helper:"clone"
    });

    $( "#dropZone" ).droppable({
        accept: '.draggable',
        drop: function(event, ui){
            var obj = ui.draggable.clone();
            $(this).append(obj);
            obj.draggable({disabled: false})
        }

    });

});
</script>    


<div id="dropZone" ></div>
<div class="draggable ui-widget-content">Drag me</div>

1

There are 1 best solutions below

0
4b0 On

Drop event occurs repeatedly, whether you're dragging elements from outside or inside the container. So check whether an droppable element is already inside the container, if so, do not add it to the container:

Example:

$(".draggable").draggable({
  helper: "clone"
});

$("#dropZone").droppable({
  accept: '.draggable',
  drop: function(event, ui) {
    var obj = ui.draggable.clone();
    if (!obj.is('.inside-drop-zone')) {
      $(this).append(obj.addClass('inside-drop-zone').draggable({
        containment: '#drop-zone'
      }));
    }
  }

});
.draggable {
  width: 100px;
  height: 100px;
  background-color: lightblue;
}

#dropZone {
  width: 300px;
  height: 300px;
  background: yellow;
  position: relative;
}
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script>

<div id="dropZone"></div>
<div class="draggable ui-widget-content">Drag me</div>