Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery UI droppable on dynamically added element?

I'm having a problem with applying jQueryUI droppable to a dynamically created div.

$(".item").draggable({ helper: 'clone'});

$(".box").draggable({containment : '#area'});
$(".box").droppable({
    drop: function(event, ui) {
        if ($(ui.draggable).hasClass("area")){
            // call another function
        }else{
            $(this).append($(ui.draggable).clone().removeClass('item').addClass('area'));
            $('.area').draggable();
        }
    }
});

An .item is supposed to drop in .box. It works well until I call the second function (by clicking a button):

function add_box(){
    $("<div class='box'></div>").prependTo( "#area" );

    $(".box").droppable(); // i tried this (didn't work).

    $(".box").draggable(); // should be draggable as well
}
like image 893
Nabil Ali Avatar asked Mar 18 '26 23:03

Nabil Ali


1 Answers

When you're calling $(".box").droppable(); in add_box function, you're reapplying droppable to all .box items, but without the options, so you're losing your expected behavior.

You should apply it only to the newly created element, and you need to define your options as well. You could do something like this for example:

// define your options as an object
var droppableOptions = {
    drop: function(event, ui) {
        if ($(ui.draggable).hasClass("area")){
            // call another function
        } else {  
            $(this).append($(ui.draggable).clone().removeClass('item').addClass('area'));
            $('.area').draggable();
        }
    }
}

function add_box(){
    var newBox = $("<div class='box'></div>").prependTo( "#area" );

    // you apply droppable to your new box, with the options you need
    newBox.droppable(droppableOptions); 

    newBox.draggable(); // should be draggable as well
}
like image 168
Julien Grégoire Avatar answered Mar 21 '26 15:03

Julien Grégoire