Gregorio Di Stefano
Gregorio Di Stefano

Reputation: 1203

jQuery sortable on dynamic elements

I am having issues when adding a new sortable element dynamically to the DOM.

I setup my sortable the following way:

$(".lesson_field, #custom_words").sortable({
    connectWith: ".lesson_field, #custom_words",
});

}

But, when I add a new lesson_field class, it does not behave like a sortable element.

I tried destroying sortable, by using "destroy", and re-initalizing, but that does not work. I also tried using "refresh" and "refreshPosition"

Fiddle: http://jsfiddle.net/rz2mh8ec/6/ (press "Add" to reproduce issue)

Thanks

Upvotes: 1

Views: 1730

Answers (1)

Artur Filipiak
Artur Filipiak

Reputation: 9157

using .clone() on an element that has its own id attribute, You're duplicating this id what is not good practice.
Next thing is that sortable should be applied on the parent element.


EDIT

Seems that the problem is with clone(true).
It doest work when events handlers are not copied along with the element (.clone(false))

You have to destroy sortable before you attempt to clone(true):

var lessons = 2

function sort() {
    $(".lesson_field, #custom_words").sortable({
        connectWith: ".lesson_field, #custom_words",
    });
}

window.addanother = function () {
    // destroy sortable:
    $(".lesson_field, #custom_words").sortable("destroy");
    // then clone the element:
    var e = $("#lesson_1").first().clone(true)
    e.attr("id", "lesson_" + lessons)
    lessons++;
    e.insertAfter($("#lesson_1").last())
    sort();
}

sort();

JSFiddle JSFiddle

Upvotes: 3

Related Questions