Search code examples
jqueryjquery-uijquery-ui-sortablejquery-ui-draggablejquery-ui-droppable

JQuery Draggable, Droppable, & Sortable with different items


I have the following JQuery setup to drag and drop items from a list into a different list:

// Set what items are draggable
$(".widgetListItems").draggable(
{
    cursor: "move",
    opacity: 0.5,
    scroll: false,
    revert: "invalid",
    connectToSortable: "#dropList",
    stop: function (event, ui) { if (deleteItem) { ui.helper.remove(); deleteItem = false; } }
});

// Set what items can have objects dropped into them.
$(".dropableArea").droppable(
{
    accept: ".widgetListItems",
    tolerance: "touch",
    drop: function (event, ui)
    {
        deleteItem = true;

        var item = $(ui.draggable).text();
        item = $.trim(item);

        switch (item)
        {
            case "Preventative Care":
                $(this).append($("#panelPreventative"));
                $("#panelPreventative").show(1000);
                break;
            case "Medical Claims":
                $(this).append($("#panelMedicalClaims"));
                $("#panelMedicalClaims").show(1000);
                break;
            case "Capitation":
                $(this).append($("#panelCapitation"));
                $("#panelCapitation").show(1000);
                break;
        }
    }
});

$(".dropableArea").sortable(
{
    cursor: "move",
    connectWith: ".dropableArea",
    update: function (event, ui)
    {
        $(ui.item).css("margin", "30px 0px");
    }
});

I have a <li> with class "widgetListItems" that the user can drag onto the screen. Next, the droppable is a <ul> with class "dropableArea". The experience that I want the user to have is once they drop the item into the list, the item they dropped is removed and a widget is displayed instead with class "loadedWidgetPanel". That is what I am doing in the "drop" event. I would also like this list the user can drop stuff into be sortable. With the code I have, the user can drop the item into the list, the widget is displayed, and they can sort the widgets once they are on the page.

What I am wondering, is if this list can be sorted so that when the user drops an element into the list, the widget gets inserted at the point of where the user dropped it, instead of being appended at the end. I know it is being appended because of what I am doing in the "drop" event, but I can't figure out a different way to insert a different item. Can someone help me out?


Solution

  • In your drop: function() {} this is the callback that gets fired when an item gets dropped, after you perform the logic you already have, you could add a call to a sort routine. Some examples of a quick and dirty jquery alphabetical sort.