When using jquery-ui droppable, how can you remove an item from the droppable area after you have already dropped it?

leora picture leora · Nov 17, 2013 · Viewed 10k times · Source

I have a html page with some images that are dragggable and a set of divs that are droppable. It all works fine using the below code but I can't figure out how i can REMOVE AN ITEM from the droppable area after its been dropped. (lets say the user changes their mind . .)

I want some behavior that if you drag an item out of the droppable area that it gets removed from the droppable area. I expected this to be the behavior out of the box but apparently not.

$(".draggable").draggable({ cursor: "move", revert: "invalid", helper: "clone" });

$(".droppable").droppable({
    hoverClass: "ui-state-active",
            drop: function (ev, ui) {
                $(this).append($(ui.draggable).clone());
            }
});

Is there anyway to support the behavior so I can remove items from a droppable (do i need to make it a draggable as well? that would seem odd and overkill for such a simple and basic feature I think . .

Answer

apaul picture apaul · Nov 26, 2013

I would use droppable's out event to remove the draggables like so:

Working Example

$(".draggable").draggable({
    cursor: "move",
    revert: "invalid",
    helper: "clone"
});

$(".droppable").droppable({
    accept: '.draggable',
    hoverClass: "ui-state-active",
    drop: function (ev, ui) {
        if ($(ui.draggable).hasClass('new')) {
            $('.new').draggable({
                revert: true
            });
        } else {
            $(this).append($(ui.draggable).clone().draggable({
                helper: "original"
            }).addClass('new'));
        }
    },
    out: function (event, ui) {
        $(ui.draggable).fadeOut(1000, function () {
            $(this).remove();
        });
    }
});