Search code examples
jquerydraggablejquery-ui-draggable

How to make dynamically added list elements draggable in jquery?


Here is my code from http://jsfiddle.net/XUFUQ/1/

$(document).ready(function()
    {
        addElements();
    }
);

function addElements()
{
    $("#list1").empty().append(
        "<li id='item1' class='list1Items'>Item 1</li>"+
        "<li id='item2' class='list1Items'>Item 2</li>"+
        "<li id='item3' class='list1Items'>Item 3</li>"
    );
}

$(function() {
    // there's the gallery and the trash
    var $gallery = $( "#list1" ),
    $trash = $( "#list2" );

    // let the gallery items be draggable
    $( "li", $gallery ).draggable({
        cancel: "button", // these elements won't initiate dragging
        revert: "invalid", // when not dropped, the item will revert back to its initial position
        containment: "document",
        helper: "clone",
        cursor: "move"
    });

    // let the trash be droppable, accepting the gallery items
    $trash.droppable({
        accept: "#list1 > li",
        drop: function( event, ui ) {
            $("#list2").append(ui.draggable);
            addElements();
    }
    });


});

On document ready method I am appending some elements to list1, and then I am initializing draggable on that list so for first time I am able to drag list1 elements. On dropping in list2 I am calling addElements() function to clear and add some elements to list1. But I am unable to drag these added elements.

How can I make these elements draggable?


Solution

  • Here is an ugly version of what you need to do based on the update http://jsfiddle.net/XUFUQ/6/. Best to factor out the resuable code:

    // let the trash be droppable, accepting the gallery items
    $trash.droppable({
        accept: "#list1 > li",
        drop: function( event, ui ) {
            $("#list2").append(ui.draggable);
            addElements();
            $( "li", $gallery ).draggable({
                cancel: "button", // these elements won't initiate dragging
                revert: "invalid", // when not dropped, the item will revert back to its initial position
                containment: "document",
                helper: "clone",
                cursor: "move"
               })
            }
    });
    

    Basically calling draggable only connects to the elements that exist at the time it is run. This adds the various mouse handling events to each element. If you add elements it knows nothing about them, so you need to call draggable again on those.

    The other two answers both give examples of where you can add the draggable to ensure the elements are included, but that is a coding excercise.