Day 15 Mini Project: Todo App
Abhi tak seekha hua sab use karte hain — DOM manipulation, events, arrays — aur ek working Todo App banate hain. Yeh tumhara pehla real JavaScript project hoga!
HTML Structure
Pehle HTML banao — input, button, aur list.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Todo App</title>
<style>
body { font-family: Arial; max-width: 500px; margin: 50px auto; padding: 20px; }
input { padding: 10px; width: 70%; font-size: 16px; }
button { padding: 10px 16px; background: var(--primary); border: none; cursor: pointer; font-weight: bold; }
li { display: flex; align-items: center; justify-content: space-between; padding: 10px; margin: 5px 0; background: #f0f0f0; border-radius: 6px; }
li.done span { text-decoration: line-through; opacity: 0.5; }
.del { background: #ff4444; color: white; border: none; cursor: pointer; padding: 4px 10px; border-radius: 4px; }
</style>
</head>
<body>
<h1>📝 Todo App</h1>
<div>
<input type="text" id="todoInput" placeholder="Add a task..." />
<button id="addBtn">Add</button>
</div>
<ul id="todoList"></ul>
<script src="script.js"></script>
</body>
</html>
JavaScript Logic
Ab functionality add karo.
let todos = [];
let nextId = 1;
const input = document.getElementById("todoInput");
const addBtn = document.getElementById("addBtn");
const todoList = document.getElementById("todoList");
function renderTodos() {
todoList.innerHTML = "";
todos.forEach(todo => {
let li = document.createElement("li");
li.className = todo.done ? "done" : "";
li.innerHTML = `
<span onclick="toggleTodo(${todo.id})" style="cursor:pointer">${todo.text}</span>
<button class="del" onclick="deleteTodo(${todo.id})">✕</button>
`;
todoList.appendChild(li);
});
}
function addTodo() {
let text = input.value.trim();
if (!text) return;
todos.push({ id: nextId++, text, done: false });
input.value = "";
renderTodos();
}
function toggleTodo(id) {
todos = todos.map(t => t.id === id ? { ...t, done: !t.done } : t);
renderTodos();
}
function deleteTodo(id) {
todos = todos.filter(t => t.id !== id);
renderTodos();
}
addBtn.addEventListener("click", addTodo);
input.addEventListener("keydown", e => e.key === "Enter" && addTodo());
🎯 Practice Challenge
Todo app mein localStorage add karo taake page refresh hone par todos gayab na hon.