CodingNic

Drag and Drop

Reorder the Task Array

Drag and Drop 9 min read

Reorder the Task Array

Now use the drop position to change the order of the tasks array.

Add drag-over handling so the browser allows a drop:

javascript
taskList.addEventListener("dragover", (event) => {
  event.preventDefault();
});

Then add the drop handler:

javascript
taskList.addEventListener("drop", (event) => {
  event.preventDefault();

  const target = event.target.closest(".task-row");

  if (!target || !draggedTaskId) {
    return;
  }

  const targetTaskId = target.dataset.id;

  if (targetTaskId === draggedTaskId) {
    return;
  }

  const fromIndex = tasks.findIndex((task) => task.id === draggedTaskId);
  const toIndex = tasks.findIndex((task) => task.id === targetTaskId);

  if (fromIndex === -1 || toIndex === -1) {
    return;
  }

  const [movedTask] = tasks.splice(fromIndex, 1);
  tasks.splice(toIndex, 0, movedTask);

  renderTasks();
});

This keeps the data array as the source of truth. The DOM is rendered again from the new order.

Checkpoint

Create at least three tasks and drag one above or below another. Confirm that the list order changes and remains correct after another task action causes a re-render.