Reorder table rows using drag and drop
July, 2021
Introduction
Sometimes we want to reorder table rows using drag and drop. There are a few plugins to do it but, can we achieve this using vanilla javascript? Here is an option:
Step 1: Define a table in HTML
<table>
<thead>
<tr>
<th>EMAIL</th>
</tr>
</thead>
<tbody>
<tr draggable='true' ondragstart='start()' ondragover='dragover()'>
<td>jhon@gmail.com</td>
</tr>
<tr draggable='true' ondragstart='start()' ondragover='dragover()'>
<td>marygirl@yahoo.com</td>
</tr>
<tr draggable='true' ondragstart='start()' ondragover='dragover()'>
<td>cha24@yahoo.com</td>
</tr>
</tbody>
</table>
Step 2: Define CSS classes
body{
color:white;
}
td,tr,th{
border:1px solid white;
border-collapse: collapse;
cursor:all-scroll;
}
table{
border-collapse: collapse;
-webkit-user-select: none; /* Safari */
-ms-user-select: none; /* IE 10+ and Edge */
user-select: none; /* Standard syntax */
}
👉 Notice that user-select is necessary for optimal working.
Step 3: Define the functions for drag and drop rows in javascript
var row;
function start(){
row = event.target;
}
function dragover(){
var e = event;
e.preventDefault();
let children= Array.from(e.target.parentNode.parentNode.children);
if(children.indexOf(e.target.parentNode)>children.indexOf(row))
e.target.parentNode.after(row);
else
e.target.parentNode.before(row);
}
Check a working demo for this code: