Search code examples
javascriptjqueryjquery-uiinterfaceclone

jQuery UI: Drag and clone from original div, but keep clones


I have a div, which has jQuery UI Draggable applied. What I want to do, is click and drag that, and create a clone that is kept in the dom and not removed when dropped.

Think of a deck of cards, my box element is the deck, and I want to pull cards/divs off that deck and have them laying around my page, but they would be clones of the original div. I just want to make sure that you cannot create another clone of one of the cloned divs.

I have used the following, which didn't work like I wanted:

$(".box").draggable({ 
        axis: 'y',
        containment: 'html',
        start: function(event, ui) {
            $(this).clone().appendTo('body');
        }
});

I figured out my solution:

$(".box-clone").live('mouseover', function() {
    $(this).draggable({ 
        axis: 'y',
        containment: 'html'
    });
});
$(".box").draggable({ 
    axis: 'y',
    containment: 'html',
    helper: 'clone'
    stop: function(event, ui) {
        $(ui.helper).clone(true).removeClass('box ui-draggable ui-draggable-dragging').addClass('box-clone').appendTo('body');
    }
});

Solution

  • Here is what I finally did that worked:

    $(".box-clone").live('mouseover', function() {
        $(this).draggable({ 
            axis: 'y',
            containment: 'html'
        });
    });
    $(".box").draggable({ 
        axis: 'y',
        containment: 'html',
        helper: 'clone',
        stop: function(event, ui) {
            $(ui.helper).clone(true).removeClass('box ui-draggable ui-draggable-dragging').addClass('box-clone').appendTo('body');
        }
    });