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

jQuery UI Droppable: how to drop the element where the mouse is released


I am using the Droppable method to make a container receive div elements.

This container is also sortable.

jsfiddle: http://jsfiddle.net/r5vrrcxv/2/

jQuery('#source').sortable();

jQuery('#receiver').sortable().droppable({
    drop: function( event, ui ) {
        $( "<div></div>" ).text( ui.draggable.text() ).appendTo( this );
    }
});

My problem: when I drag and drop elements into the receiver, the elements are always dropped at the bottom of the receiver.

What I am looking for: instead, as the elements in the receiver are sortable, I would like the elements dropped in the receiver to be positioned above or below the element where they are dropped nearby.

Is there a built-in event or method in Droppable or Sortable that would allow to do that?

Thank you for your help


Solution

  • I'm not sure you really need Droppable here. Check out the "connect-lists" demo on jQueryUI.

    This allows you to drag sortable elements from one list to another, in order. You connect the lists using the connectWith option in the sortable object:

    HTML:

    <div id="source" class="connectedSortable">
        <div>aaaaaaa</div>
        <div>bbbbbbb</div>
        <div>ccccccc</div>
    </div>
    
    
    <div id="receiver" class="connectedSortable">
        <div>gggggggg</div>
        <div>hhhhhhhh</div>
        <div>iiiiiiii</div>
    </div>
    

    jQuery:

    $( "#source, #receiver" ).sortable({
      connectWith: ".connectedSortable"
    }).disableSelection();
    

    If you want the relationship to be one-way (ie. you can't drag the elements back to the source after dropping them in the receiver), you just declare the sortables separately:

    $( "#source" ).sortable({
          connectWith: ".connectedSortable"
    }).disableSelection();
    
    $( "#receiver" ).sortable().disableSelection();
    

    Here's your updated fiddle: http://jsfiddle.net/r5vrrcxv/3/