Clone draggable after deletion in target area with jQuery UI

I want some images to fall in the target area as many times as possible. But the image only falls once. My jQuery UI code:

 $(function() {
    $( ".draggable img").draggable({ 
        revert: "invalid",
        appendTo: "#droppable",
        helper: "clone" 
    });
    $( "#droppable" ).droppable({
        activeClass: "ui-state-default",
        hoverClass: "ui-state-hover",
        drop: function( event, ui ) {
           $( this ).find( ".placeholder" ).remove();
           var image = $(".ui-draggable");
           $( "<img />" ).image.src.appendTo( this );
        }
    });
});

      

See a demo here: jsFiddle example

From the example you can see that the image falls in the div area only the first time . But I want the user to be able to drag and drop the same image as many times as they want in the target area.

So, for example, the user can drag the image 5 times and 5 images will be cloned in the target area. How can i do this?

+3


source to share


1 answer


You were almost there. You really need an attribute helper: "clone"

. The best way to do this is to create a new clone when the blob event is triggered with .clone () . Then just initialize it and you're done:
$(function() {
    $(".draggable img").draggable({ 
        revert: "invalid",
        helper: "clone" 
    });   
    $("#droppable").droppable({
        activeClass: "ui-state-default",
        hoverClass: "ui-state-hover",
        drop: function(event, ui) {
            var newClone = $(ui.helper).clone();
            $(this).after(newClone);
        }
    });
});

      



DEMO

As a comment, I highly recommend the above method, because it is better to make a clone in the drop

event droppable

, and then associate the event dragstop

with draggable

, This is because otherwise there will be too many clones made: my code ensures that no redundant clones. To see what I mean, open this jsFiddle (which is using the wrong method : cloning on dragstop) and try dropping the dragged outside of the selection. It happens that redundant clones will be added to the DOM. It is ineffective and ugly and should be avoided.

+3


source







All Articles