Comprehending the Requirements
I'm now focusing on solidifying my grasp of the user's needs. The core components are coming into sharper focus – specifically, the need for drag-and-drop task reordering and local storage to preserve the to-do list across sessions. These are the foundational elements upon which the design must be built.
Planning the HTML Structure
I'm presently building the HTML scaffold. I've decided to proceed with an input field, add button, and a <ul> list to hold the to-do items. Utilizing <li> elements seems like the simplest and semantically appropriate approach for the drag-and-drop mechanism, allowing for easier manipulation within the JavaScript.
Formulating the JavaScript Logic
I'm now formulating the JavaScript logic. I've broken down the project into manageable steps, starting with HTML and CSS, then the basic JavaScript functionality, and finally, local storage integration. I'm leaning toward an array of data, not just the HTML, for easier drag-and-drop. Event listeners and DOM manipulation are next.
Mapping Out the Code
I'm presently building the JavaScript plan based on the design decisions. First, I'll select the DOM elements. Then, I'll need functions to add tasks, save the array to local storage, and load them at the beginning. It's time to set up the event listeners for the "add" button. Finally, the drag-and-drop mechanics need their events.
Constructing the Implementation Plan
\n\n
I'm now outlining a step-by-step implementation. I've broken down the design into HTML structure, CSS styling, basic JavaScript logic, local storage, and the drag-and-drop mechanics. I intend to build the list directly with DOM manipulation for simplicity, then save the HTML directly to local storage. This simplifies the JavaScript and makes it easier for beginners to grasp, as saving the HTML directly avoids the complexities of object/array serialization and deserialization initially.
Implementing Drag-and-Drop
I'm now implementing the drag-and-drop mechanism. The HTML5 Drag and Drop API, while verbose, is the appropriate method here. I'll need to listen to dragstart, dragover, and drop events. The DOM will be directly manipulated in order to save the list order. I've decided to save the list order to localStorage by iterating through the <ul> child nodes and saving them as an array.
Detailing Implementation Steps
I'm now detailing the steps, specifically how the HTML list items will be constructed, how the dragging class will function, and the plan to save the list order after a drag operation. This now involves directly saving the HTML elements to localStorage.
Here is a complete, fully functional To-Do List application. It is broken down into three standard files (index.html, style.css, script.js) for clarity.
Features included:
- Add Tasks: text input with support for the "Enter" key.
- Delete & Complete: Toggle specific tasks.
- Drag and Drop: Reorder tasks using the HTML5 Drag and Drop API.
- Local Storage: Tasks, their status (completed or not), and their specific order are saved automatically. Use the browser's refresh button to test this.
1. The Structure (HTML)
Save this as index.html.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Drag & Drop To-Do List</title>
<link rel="stylesheet" href="style.css">
<!-- Font Awesome for Icons -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
</head>
<body>
<div class="container">
<h1>My Tasks</h1>
<div class="input-group">
<input type="text" id="todo-input" placeholder="Add a new task...">
<button id="add-btn"><i class="fas fa-plus"></i></button>
</div>
<ul id="todo-list" class="todo-list">
<!-- Tasks will be injected here by JS -->
</ul>
<div class="stats">
<p id="pending-tasks">You have 0 pending tasks</p>
<button id="clear-btn">Clear All</button>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
2. The Styling (CSS)
Save this as style.css. This creates a modern card-style layout and handles the visual cues for dragging.
/* Reset & Basic Styling */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
body {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
.container {
background: #fff;
width: 100%;
max-width: 400px;
padding: 25px;
border-radius: 10px;
box-shadow: 0 15px 30px rgba(0,0,0,0.2);
}
h1 {
font-size: 1.5rem;
margin-bottom: 20px;
color: #333;
text-align: center;
}
/* Input Section */
.input-group {
display: flex;
gap: 10px;
margin-bottom: 20px;
}
input {
width: 100%;
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
outline: none;
}
input:focus {
border-color: #764ba2;
}
button#add-btn {
padding: 10px 15px;
border: none;
background: #764ba2;
color: white;
border-radius: 5px;
cursor: pointer;
transition: background 0.3s;
}
button#add-btn:hover {
background: #667eea;
}
/* List Styling */
ul {
list-style: none;
max-height: 300px;
overflow-y: auto;
}
li {
background: #f2f2f2;
margin-bottom: 8px;
padding: 10px 15px;
border-radius: 5px;
display: flex;
justify-content: space-between;
align-items: center;
cursor: grab; /* Indicates item can be moved */
transition: all 0.2s ease;
position: relative;
}
li:hover {
background: #e6e6e6;
}
li span {
flex-grow: 1;
margin-left: 10px;
word-break: break-all;
}
/* Completed Task Style */
li.completed {
opacity: 0.6;
text-decoration: line-through;
}
/* Drag and Drop Visual Classes */
li.dragging {
opacity: 0.5;
background: #ccc;
border: 2px dashed #764ba2;
}
/* Icons */
.action-btn {
background: none;
border: none;
cursor: pointer;
color: #555;
font-size: 1rem;
margin-left: 5px;
}
.delete-btn:hover {
color: #ff4d4d;
}
.check-btn:hover {
color: #2ecc71;
}
/* Footer Stats */
.stats {
margin-top: 20px;
display: flex;
justify-content: space-between;
align-items: center;
font-size: 0.9rem;
color: #666;
}
#clear-btn {
background: #ff4d4d;
color: white;
border: none;
padding: 5px 10px;
border-radius: 3px;
cursor: pointer;
}
3. The Logic (JavaScript)
Save this as script.js. This handles the DOM manipulation, the drag-sorting algorithm, and Local Storage interactions.
// Select Elements
const input = document.getElementById('todo-input');
const addBtn = document.getElementById('add-btn');
const list = document.getElementById('todo-list');
const clearBtn = document.getElementById('clear-btn');
const pendingText = document.getElementById('pending-tasks');
// 1. Load Data on Startup
document.addEventListener('DOMContentLoaded', loadTasks);
// 2. Event Listeners
addBtn.addEventListener('click', addTask);
input.addEventListener('keypress', (e) => {
if (e.key === 'Enter') addTask();
});
clearBtn.addEventListener('click', () => {
list.innerHTML = '';
saveData();
});
// 3. Add Task Function
function addTask() {
const taskText = input.value.trim();
if(taskText === '') {
alert("Please write something!");
return;
}
createTaskElement(taskText, false); // False = not completed
input.value = ''; // Clear input
saveData(); // Save to local storage
}
// 4. Create HTML Element for Task
function createTaskElement(text, isCompleted) {
const li = document.createElement('li');
li.draggable = true; // Make it draggable
if (isCompleted) li.classList.add('completed');
li.innerHTML = `
<button class="action-btn check-btn"><i class="fas fa-check"></i></button>
<span>${text}</span>
<button class="action-btn delete-btn"><i class="fas fa-trash"></i></button>
`;
// Add Event Listeners for specific buttons
const checkBtn = li.querySelector('.check-btn');
checkBtn.addEventListener('click', () => {
li.classList.toggle('completed');
saveData();
});
const deleteBtn = li.querySelector('.delete-btn');
deleteBtn.addEventListener('click', () => {
li.remove();
saveData();
});
// Add Drag & Drop Event Listeners to the List Item
addDragEvents(li);
list.appendChild(li);
updateStats();
}
// 5. Drag and Drop Logic
function addDragEvents(item) {
item.addEventListener('dragstart', () => {
item.classList.add('dragging');
});
item.addEventListener('dragend', () => {
item.classList.remove('dragging');
saveData(); // Save new order
});
}
// Handle the drag over event on the list container
list.addEventListener('dragover', (e) => {
e.preventDefault(); // Allow dropping
const afterElement = getDragAfterElement(list, e.clientY);
const draggable = document.querySelector('.dragging');
if (afterElement == null) {
list.appendChild(draggable);
} else {
list.insertBefore(draggable, afterElement);
}
});
// Algorithm to determine cursor position relative to list items
function getDragAfterElement(container, y) {
// Query all draggable elements except the one currently dragging
const draggableElements = [...container.querySelectorAll('li:not(.dragging)')];
return draggableElements.reduce((closest, child) => {
const box = child.getBoundingClientRect();
const offset = y - box.top - box.height / 2; // Distance from center of box
// We want the element where offset is negative (cursor above center)
// and closest to 0
if (offset < 0 && offset > closest.offset) {
return { offset: offset, element: child };
} else {
return closest;
}
}, { offset: Number.NEGATIVE_INFINITY }).element;
}
// 6. Local Storage & Stats
function saveData() {
const tasks = [];
const listItems = list.querySelectorAll('li');
listItems.forEach(item => {
tasks.push({
text: item.querySelector('span').innerText,
completed: item.classList.contains('completed')
});
});
localStorage.setItem('todoData', JSON.stringify(tasks));
updateStats();
}
function loadTasks() {
const data = localStorage.getItem('todoData');
if (data) {
const tasks = JSON.parse(data);
tasks.forEach(task => {
createTaskElement(task.text, task.completed);
});
}
updateStats();
}
function updateStats() {
const tasks = list.querySelectorAll('li');
const pending = list.querySelectorAll('li:not(.completed)');
pendingText.innerText = `You have ${pending.length} pending tasks`;
if(tasks.length > 0) {
clearBtn.style.display = 'block';
} else {
clearBtn.style.display = 'none';
}
}
How Drag & Drop works here:
dragstart: When you click and hold an item, we add a CSS class .dragging which lowers the opacity. We know this is the active item.
dragover: This fires constantly as you move the mouse over the container.
getDragAfterElement: This is the math part. It calculates if your mouse cursor is above or below the center of the other items in the list.
- If you are above an item, the JS inserts the dragging item before that item.
- If you are at the bottom, it appends it to the end.
dragend: We remove the CSS class and trigger saveData() to ensure the new order is written to Local Storage.