Search code examples
javascriptjqueryjquery-uidrag-and-dropdraggable

how to make a div draggable and droppable


One thing left in my project was to make the two divs draggable and droppable simultaneously. Now I have the working code of divs that can be dragged and dropped but for example I can drag a div from target area and drop it on users area but I cant seem to figure out a way to drag those divs from users and assign to different users.

$(document).ready(function(){
    $(".dragable").draggable({
        cancel: "a.ui-icon",
        revert: true,
        helper: "clone",
        cursor: "move",
        revertDuration: 0
    });

    $('.droppable').droppable({
        accept: ".dragable",
        activeClass: "ui-state-highlight",
        drop: function( event, ui ) {
            // clone item to retain in original "list"
            var $item = ui.draggable.clone();
            $(this).addClass('has-drop').append($item);
        }
    });
});

http://jsfiddle.net/coder880/TpbZk/31/


Solution

  • The issue is because once the item is dragged/dropped it is then cloned. This clone does not have the draggable() plugin instantiated on it. You need to call draggable() on the $item again. Try this:

    var draggableOptions = {
        cancel: "a.ui-icon",
        revert: true,
        helper: "clone",
        cursor: "move",
        revertDuration: 0
    }
    
    $(".dragable").draggable(draggableOptions);
    
    $('.droppable').droppable({
        accept: ".dragable",
        activeClass: "ui-state-highlight",
        drop: function(event, ui) {
            var $item = ui.draggable.clone();
            $item.draggable(draggableOptions);
            $(this).addClass('has-drop').append($item);
        }
    });
    

    Updated fiddle

    it should only be cloned when its from target otherwise it should move it.

    To achieve this you need to remove the helper: 'clone' option in the cloned draggable element and maintain a flag on the element to determine whether it is a brand new clone or has been dragged previously and moved again. To do this you could use a class, something like this:

    $(".dragable").draggable({
        cancel: "a.ui-icon",
        revert: true,
        helper: "clone",
        cursor: "move",
        revertDuration: 0
    });
    
    $('.droppable').droppable({
        accept: ".dragable",
        activeClass: "ui-state-highlight",
        drop: function(event, ui) {
            var $item = $(ui.draggable)
            if (!$item.hasClass('clone')) {
                $item = $item.clone().addClass('clone');
                $item.draggable({
                    cancel: "a.ui-icon",
                    revert: true,
                    cursor: "move",
                    revertDuration: 0
                });
            }
            $(this).addClass('has-drop').append($item);
        }
    });
    

    Example fiddle