Search code examples
jqueryclonedraggabledroppable

Duplicating Jquery Draggables


I'm trying to create a draggalbe items that can be duplicated and dragged onto a droppable. Ok, after a little effort, go that working and made the resulting duplicate draggable. But the "drop" method is making it so that if I drag the new clone more than once, It continues to clone itself. I see why it's doing it, but I'm not too sure how to turn it off. Only the item outside the droppable box should be duplicatable. Once inside the box, the duplicate(s) should be able to move around too, but not clone itself.

Example

Try dragging the little hedgehog over to the box (So far, so good.), then drag and drop it inside the box a few times to see the problem.

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

Solution

  • You need a way for the droppable to detect the difference between the outside hedgehog being dropped, and one of the already-dropped hedgehogs being dropped. That way, you can make sure that the drop callback only clones hedgehogs that were dropped from outside of the box.

    Conveniently enough, you already have a way to detect this: the <img> outside of the box has an ID, while the dropped <img> elements inside the box do not. So all you need to do is figure out how to access the "source" of the dropped element inside of the drop callback function.

    As per the droppable docs, ui.draggable is the "current draggable element, a jQuery object," so you can get that element's id in any of a number of ways. Here's one way that works:

    $("#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, in lieu of ui.draggable[0].id:

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