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

jQuery object not draggable when recreated


Please visit http://classrecon.com/invest/mockup.html for the example of my problem. To recreate the problem:

  1. Drag PULM into the "Has these targets..." field and drop.
  2. Delete the tag by hitting the X to the right of the tag.
  3. PROBLEM: Notice that when you try to drag <delete element's text> the element won't drag.

How can I make the new tag draggable? And how can I transfer the deleted tag's text to the new tag?

JS:

$(function(){
    $(".drag-key").draggable();
    $(".tag-collection").droppable({
        over: function(event, ui){
            $(this).css("background-color","rgba(0,191,255,.3)");
        },
        out: function(event, ui){
            $(this).css("background-color","white");
        },
        drop: function(event, ui){
            $("<div class='key'></div>").text( ui.draggable.text() ).appendTo( this ).append(" <span class='remove'>✘</span>");
            ui.draggable.remove();
        }
    });

    // I THINK THE PROBLEM IS HERE
    $(document).on('click', 'span.remove', function() {
        $(".key-rep").append("<div class=\"drag-key key\">&lt;removed element's text&gt;</div>");
        $(this).closest('.key').hide();
    });
});

Solution

  • you need to run the line $(".drag-key").draggable(); again at the end of $(document).on('click', 'span.remove', function() {

    It should look like this

    $(document).on('click', 'span.remove', function() {
            $(".key-rep").append("<div class=\"drag-key key\">&lt;removed element's text&gt;</div>");
            $(this).closest('.key').hide();
            $(".drag-key").draggable();
        });
    

    Here is a JSFiddle with the suggested fix

    JSFiddle