Ad

How To Make Drag And Drop List Make Copy Instead Of Moving The List Item

- 1 answer

I have two different divs, One is full with list item and another is blank. I can Drag the list items from left to right. I am using jQuery Sortable Bootstrap plugin.

FIDDLE

With this plugin if I drag One list from left to right List it self goes(moves) on the right side But my requirement is if I drag and Drop a COPY of list will goes on the right side. It should not move.

So if I say from my example: I Drag Item 5 to right side and a Copy of Item 5 will create and Left side remain as same.

I am not sure if it can be done with jQuery UI plugin but I don't want to use UI because I it is a very big file to have and I am already have so many. So any help about this or any other plugin will really help me because I am stuck here all day [Sorry for Bad English]

JS

var adjustment

$("ol.simple_with_animation").sortable({
  group: 'simple_with_animation',
  pullPlaceholder: false,
  // animation on drop
  onDrop: function  (item, targetContainer, _super) {
    var clonedItem = $('<li/>').css({height: 0})
    item.before(clonedItem)
    clonedItem.animate({'height': item.height()})

    item.animate(clonedItem.position(), function  () {
      clonedItem.detach()
      _super(item)
    })
  },

  // set item relative to cursor position
  onDragStart: function ($item, container, _super) {
    var offset = $item.offset(),
    pointer = container.rootGroup.pointer

    adjustment = {
      left: pointer.left - offset.left,
      top: pointer.top - offset.top
    }

    _super($item, container)
  },
  onDrag: function ($item, position) {
    $item.css({
      left: position.left - adjustment.left,
      top: position.top - adjustment.top
    })
  }
})
Ad

Answer

I wrapped the first element in another div, and also gave the gray box an id. I then clone the gray box using jQuery's .clone(true, true) on dragStart. The true, true parameters are important to clone the event listeners bound to the object. The Sortable library provides afterMove on which I remove the original gray div and append its clone.

afterMove: function ($placeholder, container, $closestItemOrContainer) {
  b.remove();
  a.appendTo(append);
  $("ol.simple_with_animation").sortable("destroy");
  e();
},

I call .sortable("destroy") on the objects so that their state can be refreshed on the recursive execution of the e() function.

Note that I've put the whole thing in a recursive function, e(), but you could implement this differently, using another event listener.

Here's the JSFiddle.

Ad
source: stackoverflow.com
Ad