Search code examples
javascriptdjangosortablejs

Capturing the dragged element and the replaced elements with SortableJS


How can I grab the dragged and the replaced elements when using Sortable JS ?

The JS:

var originalList;
var sortable = Sortable.create(selection, {
  handle: '.bars-move',
  animation: 150,

/// not sure what to write here 

});

the table:

<table>
  <tbody id="selection">
  {{ formset.management_form }}
  {% for form in formset %}
    {{form.id}}
    <tr id="{{form.instance.id}}">
      <td>
          <img src="{% static 'img/bars_icon.svg' %}" class="bars-move">
      </td>
      <td>{{form.name}}</td>
    </tr>
  {% endfor %}
  </tbody>
</table>

Thank you!


Solution

  • var originalArray;
    var sortable = Sortable.create(selection, {
      handle: '.bars-move',
      animation: 150,
    
      onStart: function (evt) {
        originalArray = sortable.toArray();
      },
    
      onEnd: function(evt) {
        var dragged_id = originalArray[evt.oldIndex];
        var replaced_id = originalArray[evt.newIndex];
      },
    
    });