-
Notifications
You must be signed in to change notification settings - Fork 0
/
scripts.js
57 lines (46 loc) · 1.66 KB
/
scripts.js
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
document.addEventListener("DOMContentLoaded", () => {
const todoInput = document.getElementById("input");
const todoList = document.getElementById("todo-list");
const addTaskButton = document.getElementById("add-task-button");
let tasks = JSON.parse(localStorage.getItem('tasks')) || [];
tasks.forEach((task) => renderTask(task));
addTaskButton.addEventListener("click", () => {
const tasktext = todoInput.value.trim();
if (tasktext === "") return;
const newTask = {
id: Date.now(),
text: tasktext,
completed: false,
};
tasks.push(newTask);
saveTask();
renderTask(newTask);
todoInput.value = "";
console.log(tasks);
});
function renderTask(task) {
console.log(task);
const li = document.createElement("li");
li.setAttribute("data-id", task.id);
if (task.completed) li.classList.add("completed");
li.innerHTML = `
<span>${task.text}</span>
<button>delete</button>
`;
li.addEventListener("click", (e) => {
if (e.target.tagName === "BUTTON") return;
task.completed = !task.completed;
li.classList.toggle("completed");
});
li.querySelector('button').addEventListener('click', (e) => {
e.stopPropagation();
tasks = tasks.filter(t => t.id !== task.id);
li.remove();
saveTask();
});
todoList.appendChild(li);
}
function saveTask() {
localStorage.setItem("tasks", JSON.stringify(tasks));
}
});