Search code examples
javascriptsortablejs

Access the data-id of both the element dragged and the element replaced using SortableJS


I can access the id of the element dragged (see the code below) but not sure how to also grab the id of the element replaced.

the JS:

Sortable.create(selection, {
  handle: '.bars-move',
  animation: 150,

  onStart: function (/**Event*/evt) {
    var itemEl = evt.item;
    var data_id = itemEl.getAttribute("data-id");
    },
});

Any ideas please?


Solution

  • On onStart save the current list of ids, and on onEnd refer to this list using evt.newIndex.

    var originalList;
    
    var sortable = new Sortable(document.getElementById('items'), {
      onStart: function(evt) {
        originalList = [...document.querySelectorAll("#items > div")].map(el => el.id);
      },
    
      onEnd: function(evt) {
        console.log("Dragged id: " + evt.item.id + 
                " - Replaced id: " + originalList[evt.newIndex]);
      }
    });
    .list-group-item { font-size: 10px; padding: 1px 5px!important; width: 150px }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Sortable/1.10.1/Sortable.min.js"></script>
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
    
    <div id="items" class="list-group col">
      <div id="item1" class="list-group-item">Item 1</div>
      <div id="item2" class="list-group-item">Item 2</div>
      <div id="item3" class="list-group-item">Item 3</div>
      <div id="item4" class="list-group-item">Item 4</div>
      <div id="item5" class="list-group-item">Item 5</div>
      <div id="item6" class="list-group-item">Item 6</div>
    </div>