CodingNic

Drag and Drop

Track the Dragged Task

Drag and Drop 7 min read

Track the Dragged Task

Add a variable near the top of script.js to remember which task is being moved:

javascript
let draggedTaskId = null;

Then add drag event handling to the task list:

javascript
taskList.addEventListener("dragstart", (event) => {
  const task = event.target.closest(".task-row");

  if (!task) {
    return;
  }

  draggedTaskId = task.dataset.id;
});

taskList.addEventListener("dragend", () => {
  draggedTaskId = null;
});

The task ID is all you need to identify the item being moved. Keep the task itself inside the tasks array rather than creating a second copy of the data.

Checkpoint

Start dragging a task and release it. The app should continue working normally, with no duplicate task data created.