A Starter Guide to Create a Reorderable Drag-and-drop List in JavaScript: Sortable.js for Beginners

Sortable.js is a powerful javascript library for creating reorderable drag-and-drop lists in web development. It is widely used in web page layout. In this tutorial, we will implement a reorderable drag-and-drop list with some steps using Sortable.js.

create a reorderable drag-and-drop lists using sortable.js

View reorderable list demo

We can reorder these items by pressing and dragging our mouse.

How to create a reorderable drag-and-drop list using Sortable.js?

1.Import Sortable.js

<script src="./Sortable.js"></script>

2.Create a div to show all list items

The id of this div is: list

<div id="list" class="list-group col">
    <div class="list-group-item">Item 1</div>
    <div class="list-group-item">Item 2</div>
    <div class="list-group-item">Item 3</div>
    <div class="list-group-item">Item 4</div>
    <div class="list-group-item">Item 5</div>
    <div class="list-group-item">Item 6</div>
</div>

3.Set the css style of each list item

<style type="text/css">
.list-group-item{ padding:15px; border:#CCCCCC solid 1px; text-align:left; margin-bottom:5px; width:250px; background:#00CCCC;}
</style>

4.Create a reorderable drag-and-drop list using Sortable.js

<script>
new Sortable(list, {
    animation: 150,
    // Element dragging ended
  onEnd: function (/**Event*/evt) {
    var itemEl = evt.item;  // dragged HTMLElement
    console.log(evt);
    evt.to;    // target list
    console.log(evt.to);
    evt.from;  // previous list
    console.log(evt.from);
    evt.oldIndex;  // element's old index within old parent
    evt.newIndex;  // element's new index within new parent
    evt.oldDraggableIndex; // element's old index within old parent, only counting draggable elements
    evt.newDraggableIndex; // element's new index within new parent, only counting draggable elements
    evt.clone // the clone element
    evt.pullMode;  // when item is in another sortable: `"clone"` if cloning, `true` if moving
  }
});
</script>

onEnd will bind an event on this reorderable drag-and-drop list. It will be executed when your mouse is dropped.

Leave a Reply

Your email address will not be published. Required fields are marked *