Glenn Dayton
Glenn Dayton

Reputation: 1430

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();
    });
});

Upvotes: 0

Views: 226

Answers (3)

tomson
tomson

Reputation: 1

You should use delegate() method to make divs draggable when appends to key-rep.

Upvotes: 0

guy mograbi
guy mograbi

Reputation: 28598

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

Upvotes: 2

Sheridan Bulger
Sheridan Bulger

Reputation: 1214

When you .append() the markup for a new drag-key, it is just that.. a brand new element. It was not present at the time you created the selected $(".drag-key"), and made all elements matching that selector draggable. It doesn't contain the events or class associated with JQuery draggables. If you want to make your new drag-key draggable, you'll have to .draggable() the newly created element just like you did the original element(s).

Upvotes: 0

Related Questions