Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 733
Sagar Avatar asked Nov 29 '22 12:11

Sagar


1 Answers

Here is a little trick I did for any future seeker :) This code needs to be run only once and it's pretty much self-explanatory.

//The "on" event is assigned to the "document" element which is always available within the context
//Capture all the "mouseenter" event to any child element of "document" with a specific class (you can you any valid jQuery selector you like)
//any live and dynamic element with the class will become draggable (haven't tested on touchscreen devices)
$(document).on("mouseenter", '.someClass', function(e){
 var item = $(this); 
 //check if the item is already draggable
 if (!item.is('.ui-draggable')) {
         //make the item draggable
         item.draggable({
            .............
         });
  }
});

Cheers!

like image 121
alien45 Avatar answered Dec 23 '22 07:12

alien45