Search code examples
javascriptjqueryjquery-uijquery-ui-sortablejquery-ui-droppable

jQuery sortable not working when dragging into parent div if empty


I have sortable divs with jQuery and i cannot get them back into the parent div if no existing elements are in there.

Example that works: https://jsfiddle.net/fchg7wb5/2/

But take all the elements outside of the black box (parent). Then try to drag the elements back into the parent box... it does not work (like this: https://jsfiddle.net/fchg7wb5/3/).

Here is the code:

<style>
.parent {
  padding: 10px;
  border: 1px solid black;
  background-color: #fff !important;
  min-height: 100px;
}

.drag-element {
  padding: 10px;
  background-color: #227b84;
  margin-bottom: 10px;
  color: #fff;
}
</style>

<div id="sortable">
  <div class="parent drag-element">
  </div>

  <div class="drag-element">Bob</div>
  <div class="drag-element">John</div>
  <div class="drag-element">Sally</div>
  <div class="drag-element">Mary</div>
</div>

<script>
    $("#sortable").sortable({
      items: ".drag-element",
      revert: true
    });
</script>

Solution

  • You have to have all lists defined and using connectWith

    Working Example: https://jsfiddle.net/Twisty/xqs9oyhg/

    JavaScript

    $("#sortable, .parent").sortable({
      items: ".drag-element",
      revert: true,
      connectWith: ".parent"
    });
    

    I would also advise making use of items and handles a lot better depending on how complex you anticipate the connected lists to be.

    Possible duplicate: jQuery UI nested sortable