Search code examples
jqueryjquery-uiclonedraggabledroppable

jQuery clone image, but only when dragged from outside container


I have 2 html elements,

1.<div class="drag">..example.jpg..</div> contains images that can be dragged/cloned/dropped.
2.<div class="drop-zone"></div> is the div they can be dropped into, retain dragging, but not be clone-able.

Demo: http://jsfiddle.net/rGUma/2/.

It's working BUT, I do not want the images that are dropped into .drop-zone to be cloned when dragged. The cloning should only be possible if they are dragged from outside the container. ( drag an image inside the box, then drag that image around and you see it continues to be cloned).

Is there a simple way to do this that I'm overlooking , or should the code above be completely redone using a different method?

Code reference:

$(document).ready(function($) {

    $(".drop-zone").droppable({
        accept: '.drag',
        drop: function(event, ui) {
            $(this).append($(ui.helper).clone());
            $(".drag").addClass("item");
            $(".item").removeClass("ui-draggable");
            $(".item").draggable({
                 containment: '.drop-zone'
            });
        }
    });
    $(".drag").draggable({
        helper: 'clone'
    });

});​

Solution

  • Basically, right now, the drop event occurs again and again, whether you're dragging images from outside or inside the container. The simplest solution is to check whether an image is already inside the container, and if so, do not add it to the container:

    jQuery(function($) {
    
        $('.drop-zone').droppable({
            accept: '.drag',
            drop: function(event, ui) {
                var $clone = ui.helper.clone();
                if (!$clone.is('.inside-drop-zone')) {
                    $(this).append($clone.addClass('inside-drop-zone').draggable({
                         containment: '.drop-zone'
                    }));
                }
            }
        });
    
        $('.drag').draggable({
            helper: 'clone'
        });
    
    });