Developing a to-do list app
The user wants to create a to-do list app with features like drag-and-drop and localStorage, using HTML, JS, and CSS. It seems they’re looking for a single-page example with complete code snippets and minimal explanation.
I’ll need to focus on ensuring the code supports CRUD operations and drag reordering. Maybe I’ll go with vanilla JS and keep it simple, possibly using a single-column list for reordering. Let's draft out the HTML structure and functionality for adding, deleting, and toggling tasks!Implementing drag-and-drop functionality
I need to set up drag-and-drop functionality for the to-do list app. First, I'll reflect completed tasks with a 'completed' class. For drag-and-drop ordering, I'll define event listeners.
This includes handling drag start by setting dataTransfer with the ID and adding a 'dragging' class. When dragging over, I will compute the nearest element to figure out where to drop. After dropping, I'll need to update the order in the tasks array, serialize it, and save it to localStorage. Using incremental IDs via Date.now() will keep things simple!Detailing core functionality steps
I want to outline the core steps for the to-do list app script. First, I'll define STORAGE_KEY for localStorage and initialize an empty todos array.
Next, I'll create functions to save and load todos, ensuring that when I load them, I handle parsing correctly. For rendering, I'll clear the existing list and create new list items, attaching the required events to each one.
In createTodoElement(todo), I'll build the structure for each list item, setting it as draggable and adding event listeners for toggling completion, deleting items, and handling drag events. This structure will help keep things organized!Implementing dragover handling
For handling the dragover event, I'll attach a listener to the <ul> container. In this event, I'll use e.preventDefault() to allow dropping and determine where to reposition the dragging element.
I’ll identify the currently dragging element and find the correct position using getDragAfterElement. This function calculates where to place the dragged item based on mouse position. Once it’s dropped, I’ll update the order in the todos array by reading the DOM order. To ensure everything stays in sync, I’ll call syncOrderFromDOM whenever the drag ends!Building the to-do list application
For this to-do list app, I'll handle form submissions by preventing the default action. I'll create new todo objects with an ID and text, then push them to the todos array, save the updated list, and append the new element to the DOM. Supporting Enter key submissions could enhance usability.
The CSS will keep it simple with a bulletless list, highlighting dragging items.
I’ll organize code into three files: index.html, styles.css, and script.js to make it easy for the user to copy and paste.
I’ll ensure the drag-and-drop functionality is smooth across browsers and confirm that localStorage is used correctly. Let's make sure to provide a concise explanation on how to run the code! Here’s a complete, minimal to‑do list app with drag‑and‑drop reordering and localStorage persistence.
1. index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>To‑Do List with Drag & Drop</title>
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<div class="app">
<h1>To‑Do List</h1>
<form id="todo-form">
<input
id="todo-input"
type="text"
placeholder="Add a new task..."
autocomplete="off"
/>
<button type="submit">Add</button>
</form>
<ul id="todo-list"></ul>
</div>
<script src="script.js"></script>
</body>
</html>
2. styles.css
* {
box-sizing: border-box;
}
body {
margin: 0;
padding: 0;
font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
background: #f5f5f7;
display: flex;
justify-content: center;
align-items: flex-start;
min-height: 100vh;
}
.app {
margin-top: 40px;
background: #ffffff;
padding: 20px 24px 24px;
border-radius: 12px;
box-shadow: 0 16px 30px rgba(0, 0, 0, 0.08);
width: 360px;
max-width: 90vw;
}
h1 {
margin: 0 0 16px 0;
font-size: 24px;
}
#todo-form {
display: flex;
gap: 8px;
margin-bottom: 16px;
}
#todo-input {
flex: 1;
padding: 8px 10px;
font-size: 14px;
border-radius: 6px;
border: 1px solid #ccc;
outline: none;
}
#todo-input:focus {
border-color: #007bff;
box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.15);
}
#todo-form button {
padding: 8px 14px;
font-size: 14px;
border-radius: 6px;
border: none;
background: #007bff;
color: white;
cursor: pointer;
}
#todo-form button:hover {
background: #0062cc;
}
#todo-list {
list-style: none;
padding: 0;
margin: 0;
}
/* Individual todo item */
.todo-item {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
padding: 8px 10px;
margin-bottom: 6px;
border-radius: 6px;
background: #f8f9fa;
border: 1px solid #e1e4e8;
cursor: grab;
}
.todo-item:last-child {
margin-bottom: 0;
}
.todo-item.dragging {
opacity: 0.6;
background: #e9f3ff;
border-style: dashed;
}
.todo-left {
display: flex;
align-items: center;
gap: 8px;
flex: 1;
}
.todo-left span {
font-size: 14px;
word-break: break-word;
}
.todo-item.completed span {
text-decoration: line-through;
color: #999;
}
.todo-item input[type="checkbox"] {
cursor: pointer;
}
/* Delete button */
.delete-btn {
border: none;
background: transparent;
color: #d11a2a;
font-size: 16px;
cursor: pointer;
padding: 2px 6px;
border-radius: 4px;
}
.delete-btn:hover {
background: rgba(209, 26, 42, 0.08);
}
3. script.js
const STORAGE_KEY = "todo-list-v1";
const form = document.getElementById("todo-form");
const input = document.getElementById("todo-input");
const list = document.getElementById("todo-list");
let todos = [];
// --- Initialization ---
loadTodos();
renderTodos();
// --- Event listeners ---
form.addEventListener("submit", (e) => {
e.preventDefault();
const text = input.value.trim();
if (!text) return;
const newTodo = {
id: Date.now().toString(),
text,
completed: false
};
todos.push(newTodo);
saveTodos();
const li = createTodoElement(newTodo);
list.appendChild(li);
input.value = "";
input.focus();
});
list.addEventListener("dragover", (e) => {
e.preventDefault(); // allow drop
const afterElement = getDragAfterElement(list, e.clientY);
const dragging = document.querySelector(".dragging");
if (!dragging) return;
if (afterElement == null) {
list.appendChild(dragging);
} else {
list.insertBefore(dragging, afterElement);
}
});
list.addEventListener("drop", (e) => {
e.preventDefault();
syncOrderFromDOM();
});
// --- Core functions ---
function loadTodos() {
const stored = localStorage.getItem(STORAGE_KEY);
if (!stored) {
todos = [];
return;
}
try {
const parsed = JSON.parse(stored);
todos = Array.isArray(parsed) ? parsed : [];
} catch {
todos = [];
}
}
function saveTodos() {
localStorage.setItem(STORAGE_KEY, JSON.stringify(todos));
}
function renderTodos() {
list.innerHTML = "";
todos.forEach((todo) => {
const li = createTodoElement(todo);
list.appendChild(li);
});
}
function createTodoElement(todo) {
const li = document.createElement("li");
li.className = "todo-item";
li.draggable = true;
li.dataset.id = todo.id;
if (todo.completed) li.classList.add("completed");
// Left side: checkbox + text
const left = document.createElement("div");
left.className = "todo-left";
const checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.checked = todo.completed;
const span = document.createElement("span");
span.textContent = todo.text;
left.appendChild(checkbox);
left.appendChild(span);
// Delete button
const delBtn = document.createElement("button");
delBtn.className = "delete-btn";
delBtn.type = "button";
delBtn.textContent = "✕";
// Assemble
li.appendChild(left);
li.appendChild(delBtn);
// Checkbox logic
checkbox.addEventListener("change", () => {
todo.completed = checkbox.checked;
li.classList.toggle("completed", todo.completed);
saveTodos();
});
// Delete logic
delBtn.addEventListener("click", () => {
todos = todos.filter((t) => t.id !== todo.id);
saveTodos();
li.remove();
});
// Drag & drop logic
li.addEventListener("dragstart", (e) => {
li.classList.add("dragging");
// Some browsers require dataTransfer to be set
e.dataTransfer.effectAllowed = "move";
e.dataTransfer.setData("text/plain", todo.id);
});
li.addEventListener("dragend", () => {
li.classList.remove("dragging");
syncOrderFromDOM();
});
return li;
}
// Compute where to insert the dragged element
function getDragAfterElement(container, y) {
const draggableElements = [
...container.querySelectorAll(".todo-item:not(.dragging)")
];
return draggableElements.reduce(
(closest, child) => {
const box = child.getBoundingClientRect();
const offset = y - box.top - box.height / 2;
// We want the element with the smallest negative offset
if (offset < 0 && offset > closest.offset) {
return { offset, element: child };
} else {
return closest;
}
},
{ offset: Number.NEGATIVE_INFINITY, element: null }
).element;
}
// Sync the in-memory array order with the DOM order
function syncOrderFromDOM() {
const idsInDom = [...list.children].map((li) => li.dataset.id);
const position = new Map(idsInDom.map((id, index) => [id, index]));
todos.sort(
(a, b) =>
(position.get(String(a.id)) ?? 0) - (position.get(String(b.id)) ?? 0)
);
saveTodos();
}
How to run
- Create three files in the same folder:
index.html, styles.css, and script.js.
- Paste each code block into the corresponding file.
- Open
index.html in a browser.
Tasks will be:
- Added via the input and “Add” button (or Enter).
- Markable as completed.
- Deletable via the “✕” button.
- Reorderable via drag‑and‑drop, with order and state saved in
localStorage.