Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery UI Draggable/Sortable - Dynamically added items not draggable

I have a Draggable/Sortable set of lists that I am dynamically adding items to, but the trouble is, that once an item has been added, it's not possible to move them to the new lists. You can see the functionality here: http://jsfiddle.net/Y4T32/2/

Drag an item from the available list to one of the target lists, and you'll see that I mean. Now add a "callout" and try to drag the new item to one of the target columns.

I found another answer on here that works as I want, but have been unable to reproduce the results they got (and of course, can't find the answer now). Any insight into what I am doing wrong here?

like image 545
Aaron Wagner Avatar asked May 16 '12 20:05

Aaron Wagner


People also ask

Why is draggable not working?

You have one of these problems: Your jQuery or jQuery UI Javascript path files are wrong. Your jQuery UI does not include draggable. Your jQuery or jQuery UI Javascript files are corrupted.

What is jQuery draggable?

Draggable() Method This method allows the elements to be dragged with the help of mouse. Using jQuery UI, we can make the DOM(Document Object Model) elements to drag anywhere within the view port. This can be done by clicking on the draggable object by mouse and dragging it anywhere within the view port.


1 Answers

UPDATED ANSWER

You have to call .draggable() for each element that gets added. The jQuery selector that you use at initialization time only applies to elements that exist at the moment, not to the ones you will create.

Here's some JS that should work:

var draggable_opts = {
            connectToSortable: ".sph-callout-portlet",
            helper: "clone",
            opacity: 0.75,
            revert: 'invalid',
            stop: function(event, ui) {
                //alert(ui)
            }
        };

$(function() {
    $( ".sph-callout-portlet" ).sortable({
        opacity: 0.75,
        placeholder: "ui-state-highlight",
    }).disableSelection();

    $( "#sph-callout-portlet-avail li" ).draggable(draggable_opts);

    $(document).on("click",'#addNewCo',function(e){
        e.preventDefault();
        var newCo = $('<li>New Callout</li>').draggable(draggable_opts);
        $('#sph-callout-portlet-avail').append(newCo);
    });
});​

http://jsfiddle.net/SGevw/

like image 88
ubik Avatar answered Oct 23 '22 20:10

ubik