-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
61 lines (52 loc) · 1.57 KB
/
app.js
File metadata and controls
61 lines (52 loc) · 1.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
const taskInput = document.getElementById("taskInput");
const addTaskBtn = document.getElementById("addTaskBtn");
const taskList = document.getElementById("taskList");
const errorMessage = document.getElementById("errorMessage");
let tasks = [];
async function fetchTasks() {
try {
const response = await fetch('/api/tasks');
if (!response.ok) throw new Error('API error');
tasks = await response.json();
renderTasks();
} catch (error) {
errorMessage.classList.remove('hidden');
}
}
function renderTasks() {
taskList.innerHTML = '';
tasks.forEach((task) => {
const li = document.createElement("li");
li.className = "task-item";
li.innerHTML = `
<input type="checkbox" ${task.completed ? "checked" : ""}>
<span>${task.name}</span>
<button class="delete-btn">Delete</button>
`;
li.querySelector("input").addEventListener("change", () => toggleComplete(task.id));
li.querySelector(".delete-btn").addEventListener("click", () => deleteTask(task.id));
taskList.appendChild(li);
});
}
function addTask(taskName) {
const newTask = { id: Date.now(), name: taskName, completed: false };
tasks.push(newTask);
renderTasks();
}
function toggleComplete(id) {
const task = tasks.find((t) => t.id === id);
task.completed = !task.completed;
renderTasks();
}
function deleteTask(id) {
tasks = tasks.filter((t) => t.id !== id);
renderTasks();
}
addTaskBtn.addEventListener("click", () => {
const taskName = taskInput.value.trim();
if (taskName) {
addTask(taskName);
taskInput.value = '';
}
});
fetchTasks();