Draggable Table Rows
Enhance data management. This script allows users to physically grab a row in a table and drag it to a new position, ideal for "Priority" lists or task managers.
| # | Task | Action |
|---|---|---|
| 1 | Buy Groceries | |
| 2 | Walk the Dog | |
| 3 | Code Website | |
| 4 | Read a Book |
Click and drag rows to reorder them.
Copy the Script
<script>
const rows = document.querySelectorAll('.draggable');
let dragSrc = null;
rows.forEach(row => {
row.addEventListener('dragstart', function(e) {
dragSrc = this;
e.dataTransfer.effectAllowed = 'move';
});
row.addEventListener('dragover', function(e) {
if (e.preventDefault) e.preventDefault();
return false;
});
row.addEventListener('drop', function(e) {
if (dragSrc !== this) {
// Swap HTML content or insert node
let srcHTML = dragSrc.innerHTML;
dragSrc.innerHTML = this.innerHTML;
this.innerHTML = srcHTML;
}
return false;
});
});
</script>
Frequently Asked Questions
No. This script only changes the visual order on the client side. To save it, you would need to read the new order via JavaScript and send it to your server (AJAX).
Yes. The logic is identical whether you are using `` (table rows) or `` (list items).
Yes, as shown in the demo below, it works perfectly with Bootstrap table classes.