To implement drag-and-drop sortable list of todo items in JavaScript, you can use the HTML5 drag and drop API. Here are the basic steps to create a sortable list:
<li>
).draggable
attribute to each todo item that should be draggable.dragstart
, dragenter
, dragover
, dragleave
, and drop
.Here is an example implementation:
137 chars6 lines
index.tsx1146 chars42 lines
In this code, we first get the todo list element and all the todo items using document.getElementById
and querySelectorAll
. Then we loop through the items and add event listeners for the dragstart
, dragenter
, dragover
, dragleave
, and drop
events.
In the dragstart
event handler, we set the draggedItem
variable to the current item being dragged and set the data transfer data to the outer HTML of the item.
In the dragenter
event handler, we change the opacity of the drop zone to indicate that it's a valid drop target.
In the dragover
event handler, we prevent the default dragover behavior to allow dropping.
In the dragleave
event handler, we reset the opacity of the drop zone.
In the drop
event handler, we prevent the default drop behavior, create a new todo item from the dragged item's outer HTML, replace the dropped item with the new item, and insert the dropped item before the dragged item. Finally, we reset the opacity of the dropped item.
gistlibby LogSnag