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

Move items between dynamic created lists


I have a menu where I can create dynamic blocks and put in some fields.

When I drag a field into on of the blocks, I also want them to be sortable across several blocks. But they are only sortable inside on block.

This is my HTML code:

<div class="draggable">

  <h2>Structure elements</h2>
  <div class="structure">
    <div class="item1 e1" data-class="e1">New block</div>
    <div class="item1 e2" data-class="e2">New headline</div>
  </div>

  <h2>Fields</h2>
  <div class="fields">
    <div class="item2">Date</div>
    <div class="item2">Time</div>
    <div class="item2">Text</div>
  </div>

</div>

<div class="sortable"></div>

That's the JS

$(".sortable").sortable({
  receive: function (event, ui) {
    var itemClass = $(ui.item).attr("data-class");
    $(".sortable ." + itemClass).css({
      height: "auto",
      width: "auto"
    });
  }
});

$(".structure .item1").draggable({
  connectToSortable: ".sortable",
  helper: "clone",
  revert: "invalid",

  stop: function (event, ui) {
    $(".sortable .item1").sortable({
      revert: false
    });
  }
});

$(".fields").sortable({
  connectWith: ".sortable .item1",
  items: "> .item2"
});

Do you have an idea how I could make fields, that are dragged to a cloned block, sort/drag to another block?

Fields shouldn't be cloned, each field is unique and can be used only once.

Here https://codepen.io/alphafrau/pen/PoQRmYm you find an example of my current code.


Solution

  • In this example, the elements are dragged across columns, so in your code just add connectWith: ".item1" in this part:

    stop: function (event, ui) {
      $(".sortable .item1").sortable({
        connectWith: ".item1",
        revert: false,
        stop: function () {
          console.log($(this));
        },
      });
    },