Saving and resetting order in sortablejs
Asked Answered
T

1

6

I am using sortablejs to make a drag+drop list. I want two buttons, one that outputs the current order of list elements, and another that just resets the current order back to its original state.

I found a couple resources about how to print the current order and to how reset it, but since I'm still somewhat new to javascript, I've been having trouble implementing them.

Currently, my alert just outputs [object HTMLUListElement] and I can't figure out the reset.

Code below. Any help would be appreciated!

//Initiate sortable list
Sortable.create(simpleList, {
  animation: 150});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<script src="https://raw.githack.com/SortableJS/Sortable/master/Sortable.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>

<!-- Simple List -->
<ul id="simpleList" class="list-group">
  <li data-id="i1" class="col-1">#1</li>
  <li data-id="i2" class="col-2">#2</li>
  <li data-id="i3" class="col-3">#3</li>
  <li data-id="i4" class="col-4">#4</li>
</ul>

<button type="button" onclick="alert($('#simpleList').toArray())">Current order!</button>
<button type="button" onclick="">Reset!</button>

</html>
Torpedo answered 24/8, 2020 at 22:2 Comment(0)
B
8

Your issue is in this line:

$('#simpleList').toArray()

The method .toArray() needs to be applied to the sortable instance.

var simpleList = document.getElementById('simpleList');

// create sortable and save instance
var sortable = Sortable.create(simpleList, {animation: 150});

// save initial order
var initialOrder = sortable.toArray();

document.getElementById('saveCurrOrder').addEventListener('click', function(e) { 
    // print current order
    var order = sortable.toArray();
    console.log(order);
});

document.getElementById('resetOrder').addEventListener('click', function(e) {
    // reset to initial order
    sortable.sort(initialOrder);
})
<script src="https://raw.githack.com/SortableJS/Sortable/master/Sortable.js"></script>


<ul id="simpleList" class="list-group">
    <li data-id="i1" class="col-1">#1</li>
    <li data-id="i2" class="col-2">#2</li>
    <li data-id="i3" class="col-3">#3</li>
    <li data-id="i4" class="col-4">#4</li>
</ul>

<button type="button" id="saveCurrOrder">Current order!</button>
<button type="button" id="resetOrder">Reset!</button>
Bewail answered 24/8, 2020 at 22:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.