user2520217
user2520217

Reputation: 309

Jquery drag and drop on dynamically created div live

I have 2 DIV area on the page. The left hand side DIV will show the categorys Such as: 1.Team A 2.Team B 3.Team C . . .

<div id="source">
<div class="box" id="A">1.Team A</div>
<div class="box" id="B">2.Team B</div>
<div class="box" id="C">3.Team C</div>
</div>

The right hand side DIV will show the members in customized box layout by clicked the team Such as: Clicked Team A

<div id="dest">
<div class="memberbox" id="Amember">Peter</div>
<div class="memberbox" id="Bmember">Chris</div>
<div class="memberbox" id="Cmember">Rick</div>
</div>

The right hand side DIV is dynamically created by ajax. I cannot using the draggable and droppable function to drag the memberbox. How it is work?

$(".memberbox").draggable(
                        {
                            cursor: "move",
                            helper: 'clone',
                            appendTo: 'body',
                            zIndex: '999',
                            cursorAt: {top: 15, left: 15},
                            revert: true,
                            scroll: false,
                            addClasses:true,
                            drag: function(event, ui) {
                                this.style.borderColor = 'red';
                            },
                            stop: function(event, ui) {
                                this.style.borderColor = 'black';
                            }


                        }
                );
                $('#source').droppable({
                    activeClass: "active",
                    hoverClass: "hover",
                    drop: handleDropEvent
                });
                function handleDropEvent(event, ui) {
                      var draggable = ui.draggable;
                      console.log(draggable);
                    $(draggable).appendTo('#source');
                }

Upvotes: 0

Views: 2073

Answers (1)

Nis
Nis

Reputation: 1477

You have to call the $(".memberbox").draggable( ... ) function & $('#source').droppable(...) function AFTER you add the dynamic elements.

If you are defining them Before adding the elements, then it wont work.

Usually I have makeDraggable() function in which I define $(".memberbox").draggable( ... ) & $('#source').droppable(...) . This way, once, the dynamic elments are added, I call the makeDraggable() to initialize drag n drop.

Another advantage of this mechanism is that if you had to remove and add another set of elements, even then you can call the same function again and it will initialize drag n drop.

Upvotes: 2

Related Questions