Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refresh list after adding an item with jQuery UI sortable plugin

Alright so I have a nested sortable list, each item is therefore both a container and a sortable element.

The problem I am facing is that, whenever I add a new element, I want jQuery to refresh its internal state with the new item. According to the documentation, one has to call the sortable method passing as parameter 'refresh', but still I can't make it work.

Sample code: http://jsfiddle.net/X5sBm/

JavaScript:

$(document).ready(function() {
    var list = $('#mycontainer ul').sortable({
        connectWith: '#mycontainer ul',
        placeholder: 'myplaceholder'
    });

    function addElement(text) {
        $('#mycontainer > ul').append('<li>' + text + '<ul></ul></li>');
        list.sortable('refresh');
    }

    addElement('yolo');
});

HTML:

<div id="mycontainer">
    <ul>
        <li>
            Some text
            <ul>
            </ul>
        </li>
        <li>
            Some text 2
            <ul>
            </ul>
        </li>
    </ul>
</div>

CSS:

#mycontainer > ul {
    display: block;
}

#mycontainer > ul ul {
    min-height: 10px;
    padding-left: 20px;
}

.myplaceholder {
    background-color: yellow;
}

Try to drag one pre existing item under the newly added one, you won't be able to do so even after the refresh.

like image 476
Warrior Avatar asked Mar 21 '14 13:03

Warrior


1 Answers

I found a cheap fix:

I call sortable again on the same tag reinitialising the Sortable plugin like so:

$('#mycontainer ul').sortable({
    connectWith: '#mycontainer ul',
    placeholder: 'myplaceholder'
});

and it works.

like image 99
Warrior Avatar answered Oct 22 '22 02:10

Warrior