papazeal
games • apps • anything
Svelte Reorder List
Svelte
Drag and reorder items easily in Svelte using native drag & drop. This
snippet provides a lightweight and reactive way to rearrange lists item.
Native drag & drop
Simple & lightweight
Smooth UX & UI
Demo
🍎 Apples
🍊 Oranges
🍉 Watermelons
🥝 Kiwis
[ "🍎 Apples", "🍊 Oranges", "🍉 Watermelons", "🥝 Kiwis" ]
Code
<script>
const fruits = $state(["🍎 Apples", "🍊 Oranges", "🍉 Watermelons", "🥝 Kiwis"]);
let dragFrom = $state(null);
let dragTo = $state(null);
function dragStart(e) {
dragFrom = e.currentTarget.getAttribute("index");
e.dataTransfer.effectAllowed = "move";
e.currentTarget.classList.add("!cursor-grabbing");
}
function dragOver(e) {
e.preventDefault();
if (dragFrom != e.currentTarget.getAttribute("index")) {
dragTo = e.currentTarget.getAttribute("index");
let [item] = fruits.splice(dragFrom, 1);
fruits.splice(dragTo, 0, item);
dragFrom = dragTo;
}
}
function dragEnd(e) {
dragFrom = null;
e.currentTarget.classList.remove("!cursor-grabbing");
}
</script>
<div class="grid shadow-lg rounded-lg mx-auto bg-white text-slate-900 overflow-hidden">
{#each fruits as fruit,index}
<div
class="px-4 py-2.5 border-b border-slate-200 cursor-grab"
class:bg-blue-50={dragFrom == index}
draggable="true"
index={index}
ondragstart={dragStart}
ondragover={dragOver}
ondragend={dragEnd}
>{fruit}</div>
{/each}
</div>
Hey, my name is Zeal. I built this website to share my works. Hope you
like them!
Last Update
2025-04-25