Search code examples
jqueryjquery-uijquery-ui-draggablejquery-ui-sortablejquery-ui-droppable

jQuery UI Droppable - clone the droppable element?


JSFiddle: https://jsfiddle.net/dy556efs/2/

The elements on the left side should be cloned when dropped over to the right side. Currently, they are completely moved over - and can't get the clone helper to work properly.

Could you point me in the right direction?

$(".social-msl-link-label").draggable({
    connectToSortable: ".social-msl-group-list",
    revert: "invalid",
    helper: "clone"
});

$(".social-msl-links-order li").droppable({
    accept : ".social-msl-link-label",
    tolerance: 'pointer',
    greedy : true,
    hoverClass: 'highlight',
    drop: function(ev, ui) {
        $(ui.draggable).detach().css({position : 'relative', top: 'auto',left: 'auto'}).appendTo(this);
    }
});

Solution

  • Based on the documentation for the helper property it seems like the element is only cloned while dragging it. In other words, you still have to manually clone the element before detaching/appending it. Use the .clone() method before detaching it:

    Updated Example

    $(".social-msl-links-order li").droppable({
      accept: ".social-msl-link-label",
      tolerance: 'pointer',
      greedy: true,
      hoverClass: 'highlight',
      drop: function(ev, ui) {
        $(ui.draggable).clone(true).detach().css({
          position: 'relative',
          top: 'auto',
          left: 'auto'
        }).appendTo(this);
      }
    });
    

    If you want to remove duplicates, you could iterate over the droppable elements and compare the text of the previously dropped element with the siblings. Inside of the drop callback:

    Updated Example

    // ...
    $(this).siblings().filter(function () {
      return $(this).text().trim() === $(ui.draggable).text().trim();
    }).empty();