Search code examples
javascriptjqueryjquery-uijquery-ui-sortablecontainment

issues with .sortable function in J query


Here is a JSfiddle I'm working with.

I'm trying to create two lists from which I can move each item in and out between them and changes will update below inside the update function / sort status div area.

My first alert on line 3 works but when I call the click function on line 5 line 6 alert doesn't work. Overall I think my code may be missing something or a semi colon etc. is out of place. Please help and leave feedback, thanks.

$(document).ready(function() {
 alert(0);
 $(".shopping_list").onclick(function() {
    alert(1);
    $("#names #places").sortable({
         containment: 'parent', 
        tolerance: 'pointer',
        cursor: 'pointer', 
        revert: true, 
        opacity: 0.60,
        connectWith:"#names #places",
        update: function(event, ui) {
             content = $(this).text();
              $('#sort_status').text(content);
        }
    })

 });
});

Solution

  • Like grissom pointed out in his answer and comments,

    • Firstly you need to add jQuery-UI.
    • $("#names #places") searches for an element#places inside an element #names. To select both the elements, you need to comma separate them like $("#names , #places").
    • You should move the sortable initialization out of the click event.

    Other than that:

    • You need to remove containment: 'parent' otherwise you can't drag the item out of the current list (hence you can't move items between the lists, obviously)

      Demo

    • Unless you want the <h3> headers to be sortable (this is also invalid HTML) - you need to move them out of the <ul>

    Demo