jQuery UI Droppable and Sortable - dropping in the correct sort location

AaronS picture AaronS · Nov 1, 2013 · Viewed 24.4k times · Source

I'm working on a project where I'm dragging elements from a 3rd party jQuery control to a jQuery sortable, using a combination of droppable and sortable.

This works perfectly fine, except the item being added is always added to the bottom of the sortable list, and you must then move it to the correct location as a separate step.

Is it possible to have the item added to the location where you dropped it in the list?

You can see this behavior in the jQuery shopping card droppable demo from here. Here is a jsfiddle of the same code. As you add items from the products to your cart at the bottom, it always adds at the bottom, even if you drop it near the top.

Here's the jQuery code:

     $(function () {
     $("#catalog").accordion();
     $("#catalog li").draggable({
         appendTo: "body",
         helper: "clone"
     });
     $("#cart ol").droppable({
         activeClass: "ui-state-default",
         hoverClass: "ui-state-hover",
         accept: ":not(.ui-sortable-helper)",
         drop: function (event, ui) {
             $(this).find(".placeholder").remove();
             $("<li></li>").text(ui.draggable.text()).appendTo(this);
         }
     }).sortable({
         items: "li:not(.placeholder)",
         sort: function () {
             $(this).removeClass("ui-state-default");
         }
     });
 });

Answer

Udit Bhardwaj picture Udit Bhardwaj · Nov 15, 2013

use droppable's drop event's callback to compare the current top offset position of the draggable helper with the top offset of every element already present or previously added in the droppable

drop: function (event, ui) {

if($(this).find(".placeholder").length>0)  //add first element when cart is empty
{
    $(this).find(".placeholder").remove();
    $("<li></li>").text(ui.draggable.text()).appendTo(this);
}

else
{

    var i=0; //used as flag to find out if element added or not

    $(this).children('li').each(function()
    {
        if($(this).offset().top>=ui.offset.top)  //compare
       {
          $("<li></li>").text(ui.draggable.text()).insertBefore($(this));
          i=1;   
          return false; //break loop
       }
    })

    if(i!=1) //if element dropped at the end of cart
    {
        $("<li></li>").text(ui.draggable.text()).appendTo(this);
    }

}

} 

DEMO WITH CODE

FULL SCREEN DEMO