Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery UI - Droppable only accept one draggable

I'm making an app, that is using one droppable div and a few draggable divs. How can I make the droppable to not accept more than one draggable div? I Googled, but didn't find any workaround.


A workaround came up in mi mind. How can i check is there's dropped element in this droppable div? If it's busy then revert this draggable, which is trying to be dropped

like image 634
Emil Avramov Avatar asked Oct 16 '10 10:10

Emil Avramov


2 Answers

I spend many hours to figure it out and finally it works for me like this:

$( ".drop-zone" ).droppable({
    classes: {
        "ui-droppable-active": "ui-state-active",
        "ui-droppable-hover": "ui-state-hover"
    },
    accept: function( draggable ){
        if (!$(this).hasClass('dropped') || draggable.hasClass('dropped')){
            return true;
        }
        return false;
    },
    drop: function( event, ui ) {
        $(this).addClass('dropped');
        ui.draggable.addClass('dropped');
    },
    out: function( event, ui ){
        $(this).removeClass('dropped');
        ui.draggable.removeClass('dropped');
    }
});
like image 53
Than Ngo Hoai Avatar answered Oct 13 '22 18:10

Than Ngo Hoai


OK found a nice solution for this, essentially on 'drop' I set the droppable to only accept the item which has been dragged into it.

When you 'disable', the 'out' event that you need to re-initialize isn't available anymore, so instead I just switched the eligible items around.

Then it's possible for me to use the OUT event to re-accept all draggable items and because nothing else is accepted the OUT won't be triggered by other draggables:

$(".drop-zone").droppable({
    drop: function(event, ui) { 
        $(this).droppable('option', 'accept', ui.draggable);
    },
    out: function(event, ui){
        $(this).droppable('option', 'accept', '.drag-item');
        }   
    });
});
like image 38
Likwid_T Avatar answered Oct 13 '22 18:10

Likwid_T