Home > OS >  Jquery sortable, connectWith, find receiving container
Jquery sortable, connectWith, find receiving container

Time:10-09

I am building a sortable where items can be dragged among day containers. The number of days will vary. When an item is dragged from one day to another, I am trying to get the container of the new day. I am trying to use the 'receive' event, but it is not being fired every time I move from one day container to another.

UPDATE: It seems to fire when I move one item (task) to the new container (day), but if I move that items back to where is was originally, it does not fire again. I need it to fire every time it is moved. Do I need to tell the sortable the new DOM somehow?

Here is my HTML:

    .day {
      margin: 10px 20px;
    }
    .task {
     margin: 5px 0;
     background-color: #CCC;
    }

    <div >
       <div  data-date="2022-10-04">
           <div >Day 1 </div>
           <div  data-id="1">Task 1</div>
           <div  data-id="2">Task 2</div>
           <div  data-id="3">Task 3</div>
       </div>
       <div  data-date="2022-10-05">
           <div >Day 2</div>
           <div  data-id="4">Task 4</div>
           <div  data-id="5">Task 5</div>
           <div  data-id="6">Task 6</div>
      </div>
   </div>

Here is my JS:

   $(".day").sortable({
      cancel: ".separator",
      connectWith: ".day",
      receive: function(e, ui) {
          console.log(ui);
          var id = $(this).find('div.task').data('id');
          var day = $(this).closest('div.day');
          var date = day.data('date');
          console.log('moved item '   id   ' to this date '   date); 
          /* this give orignal date */
      }
   }).disableSelection();

And here is my Fiddle.

https://jsfiddle.net/2t84ypa0/1/

Any help is GREATLY apreciated.

Thom

CodePudding user response:

Consider the following:

https://jsfiddle.net/Twisty/cezufojL/

JavaScript

$(".day").sortable({
  cancel: ".separator",
  connectWith: ".day",
  receive: function(e, ui) {
    var id = $(ui.item).data('id');
    var date = $(this).data('date');
    console.log('Item '   id   ' moved to date '   date); /* this give orignal date */
  }
}).disableSelection();

This makes use of ui.item to target the Item that was received. $(this) refers to the sortable that is receiving the item.

In my tests it works in both directions.

  • Related