Task Actions
18 min read
Start Drag and Drop
Start Drag and Drop
Now let the user move a task between columns.
First make generated cards draggable:
card.draggable = true;
When dragging starts, put the task ID into the browser’s dataTransfer object:
card.addEventListener("dragstart", (event) => {
event.dataTransfer.setData("text/plain", String(task.id));
});
Next, allow the column to receive a dragged item. A drop target must cancel the browser’s default dragover behavior:
column.addEventListener("dragover", (event) => {
event.preventDefault();
});
Handle the drop on the column:
document.querySelectorAll(".column").forEach((column) => {
// add the drag/drop listeners inside this callback
});
Inside that callback, handle the drop:
column.addEventListener("drop", (event) => {
event.preventDefault();
const id = Number(event.dataTransfer.getData("text/plain"));
const newStatus = column.dataset.status;
const task = tasks.find((item) => item.id === id);
if (!task) return;
task.status = newStatus;
renderTasks();
});
Select all three columns and attach the drag/drop listeners to each one:
Checkpoint
Drag a task from To Do to In Progress.
After dropping it, the card should appear in In Progress and the two affected counts should update.