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

making dynamically added DIVs be droppable?


I'm having a problem making a dynamically added div the target for my drag and drop operations If someone could examine this fiddle http://jsfiddle.net/dgobrien123/FvG2J/embedded/result/ and possibly assist me in finding my error.

In the document ready method, this is how the droppable is applied:

        $(".droppable").droppable({
            activeClass: 'dragactive',
            hoverClass: 'drophover',
            drop: function(event, ui) {                    
                alert( this.id );
                $(this).addClass('drophighlight').find('p').text( '' + ui.draggable.children("span").text() + '');
            }
        });  

Here is how the container is added:

    function addGroup() {
        counter = counter + 1;
        $("div#pcgroups").append("<div class='dropcontainer'><div class='droppable' id='GROUP" + counter + "'><p>PC GROUP #" + counter + "</p></div></div>");
        return counter;
    }  

Solution

  • The problem you are having is that you are applying the droppable before your elements are created. You can apply it as they are created in your addGroup() method:

    function addGroup() {
        counter = counter + 1;
        var x = $("<div class='dropcontainer'><div class='droppable' id='GROUP" + counter + "'><p>PC GROUP #" + counter + "</p></div></div>");
    
        $("div#pcgroups").append(x);
        x.droppable({
            activeClass: 'dragactive',
            hoverClass: 'drophover',
            drop: function(event, ui) {
                alert(this.id);
                $(this).addClass('drophighlight').find('p').text('' + ui.draggable.children("span").text() + '');
            }
        });
    }
    

    Updated Fiddle:

    http://jsfiddle.net/johnkoer/FvG2J/28/