Search code examples
jquery-ui-draggablejquery-ui-droppable

How can we append an ui.draggable to a target retaining the entire draggable element in its place?


Please see the snippet below. Thank you.

We want to retain the original draggable element to its place. So that we can use it to other droppable element.

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

$('.droppable').droppable({
  accept: '.draggable',
  drop: function(e, ui) {
    $(this).append(ui.draggable);
  }
});
<link href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet"/>

<div class="droppable" id="drop-one"></div>
<div class="droppable" id="drop-two"></div>
<div class="droppable"id="drop-three"></div>

<div id="draggables">
  <div class="draggable"></div>
</div>


<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>


Solution

  • You where close to the answer but made a mistake in the drop function.

    You writed:

    $(this).append(ui.draggable);
    

    But you have to use the clone function.

    $(ui.draggable).clone().appendTo(this);
    

    Code Snippet (i added colors to see whats happening)

        $(".draggable").draggable({cursor: "crosshair", revert: "invalid", helper: "clone", start: function(event, ui) {} });
    
        $('.droppable').droppable({
            accept: '.draggable',
            drop: function(e, ui) {
                //$(this).append(ui.draggable);
                $(ui.draggable).clone().appendTo(this);
            }
        });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <div id="draggables" style="padding-bottom: 25px;">
      <div class="draggable" style="width: 100px; height: 25px; text-align: center; background-color: red; color: aliceblue;">DRAG ME</div>
    </div>
    
    
        <div class="droppable" id="drop-one" style="float:left; background-color: antiquewhite; width: 200px; height: 200px;"></div>
        <div class="droppable" id="drop-two" style="overflow: hidden; background-color: aquamarine; width: 200px; height: 200px;"></div>