Duplicate jQuery Draggables

I am trying to create draggalbe elements that can be duplicated and dragged onto droppable. Well, after a little effort, go on to this work and do the resulting duplicate drag and drop. But the drop method does this so that if I drag a new clone more than once, it continues to clone itself. I understand why he does it, but I'm not too sure how to disable it. Only an item outside the popup should be duplicated. Once inside the box, the duplicate should also be able to move around, but not clone itself.

Example

Try dragging the little hedgehog onto the box (so far so good), then drag it several times inside the box several times to see the problem.

$(function() { $("#draggable1").draggable({ helper: 'clone', revert: "invalid" }); $("#panel1").droppable({ drop: function(event, ui) { $(this).append($(ui.helper).clone().draggable()); } }); }); 
+4
source share
1 answer

You need a droppable method to detect the difference between a discarded external hedgehog and one of the discarded hedgehogs. This way you can make sure that the drop callback only clones the hedgehogs that have been reset from the outside.

Conveniently enough, you already have a way to detect this: <img> has an identifier outside the field, and there are no elements within the field in discarded <img> elements. So, all you have to do is figure out how to access the “source” dropable element inside the drop callback function.

According to droppable docs, ui.draggable is "the current drag and drop element, jQuery object", so you can get this id element in any of several ways. Here is one way:

 $("#draggable1").draggable({ helper: 'clone', revert: "invalid" }); $("#panel1").droppable({ drop: function(event, ui) { if (ui.draggable[0].id) { $(this).append($(ui.helper).clone().draggable()); } } }); 

Demo: http://jsfiddle.net/mattball/MJhcp/


Since ui.draggable is a full-blown jQuery object, it will also work to use any of the following, instead of ui.draggable[0].id :

  • ui.draggable.get(0).id
  • ui.draggable.attr('id')
  • ui.draggable.prop('id')
+5
source

All Articles