Search code examples
javascriptjqueryjquery-uijquery-ui-draggablejquery-ui-droppable

Detect unacceptable drag drop in jQuery-ui droppable


I'm using jQuery-ui draggable, droppable. My main container should only accept plugin-containers which also are droppables which accept plugins. Below is the code my code snippet:

$("#main").droppable({
                activeClass: "ui-state-default",
                hoverClass: "ui-state-hover",
                accept: ".plugin-container",
                drop: function( event, ui ) {
                    $( this ).find( ".placeholder" ).remove();
                    $("<div></div>").html(ui.draggable.html()).appendTo(this).droppable({ accept: '.plugin', drop: function (event, ui) { $('<div></div>').html(ui.draggable.html()).appendTo(this); } }).sortable();
                }

});

The problem is that when a plugin is dragged into the main container, I want to:

  1. Hightlight Plugin containers that plugin can be dropped
  2. If plugin is dropped in the main container show an error message

but the droppable over and drop methods only fire if the dragged item is acceptable and won't fire for unacceptable drags (in this case .plugin). what can I do here?

Here is the fiddle


Solution

  • I think I have found THE EXACT SOLUTION TO YOUR PROBLEM !!

    Check out this FIDDLE

    CODE:

    $("#main").droppable({
        activeClass: "ui-state-default",
        hoverClass: "ui-state-hover",
    
        //accept: ".plugin-container",
        drop: function( event, ui ) {
    
            if(ui.draggable.hasClass('plugin'))
            {
                alert('This element cannot be dropped here !');
                $(ui.draggable).draggable({ revert: true });
            }   
            else if(ui.draggable.hasClass('plugin-container'))
            {
                //console.log('context = ');
                //console.log(ui.draggable.context);
    
                $( this ).find( ".placeholder" ).remove();
                $("<div></div>").addClass('plugin-container')
                .html(ui.draggable.html())
                .appendTo(this)
                .droppable({ 
                    accept: '.plugin',
                    greedy:true,//this will prevent the parent droppables from receiving the droppable object
                    drop: function (event, ui) { 
                        $(ui.draggable).draggable({ revert: false });
                        $('<div></div>')
                        .addClass('plugin')
                        .html(ui.draggable.html())
                        .appendTo(this); 
                    } 
                }).sortable();
            }
        }
    
    });
    
    $(".menu div").draggable({
         appendTo: "body",
         helper: "clone"
    });