4

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;
    }  
Diodeus - James MacFarlane
  • 112,730
  • 33
  • 157
  • 176
David OBrien
  • 103
  • 2
  • 11
  • For future reference, including a fiddle is great, keep doing that. But also include the relevant code in the question so in case the the fiddle goes away this question still has meaningful content. – John Koerner Sep 19 '12 at 17:53

1 Answers1

6

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/

John Koerner
  • 37,428
  • 8
  • 84
  • 134