JSFiddle - React, Tailwind, and code Playground
HTML
<div id="sortable" class="ui-state">
<div id="draggable1" class="ui-state-default">1</div>
<div id="draggable2" class="ui-state-default">2</div>
<div id="draggable3" class="ui-state-default">3</div>
<div id="draggable4" class="ui-state-default">4</div>
</div>
CSS
.ui-state-default {
height: 50px;
width: 100px;
float: left;
margin: 10px;
padding: 0;
list-style-type: none;
}
#sortable {
position: relative;
height: 500px;
width: 350px;
}
JavaScript
$(function() {
var oldIndex;
$("#sortable").sortable({
start: function(event, ui) {
oldIndex = ui.item.index();
},
stop: function(event, ui) {
var newIndex = ui.item.index();
var movingForward = newIndex > oldIndex;
var nextIndex = newIndex + (movingForward ? -1 : 1);
var items = $('#sortable > div');
// Find the element to move
var itemToMove = items.get(nextIndex);
if (itemToMove) {
// Find the element at the index where we want to move the itemToMove
var newLocation = $(items.get(oldIndex));
// Decide if it goes before or after
if (movingForward) {
$(itemToMove).insertBefore(newLocation);
} else {
$(itemToMove).insertAfter(newLocation);
}
}
}
});
$("#sortable").disableSelection();
});