-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtodo.js
81 lines (72 loc) · 2.03 KB
/
todo.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
const todoList = document.querySelector(".todo");
const todoBtn = todoList.querySelector(".todo-setting");
let todos = JSON.parse(localStorage.getItem("todos")) || [];
function showTodos() {
const container = todoList.querySelector("ul");
const content = todos
.map(
(todo) => `
<li data-id=${todo.id} class="${todo.isDone ? "todo-checked" : ""}">
<span class="todo-text">${todo.value}</span>
<span class="todo-button clear"><i class="fa-solid fa-eraser todo-erase"></i></span>
</li>
`
)
.join("");
container.innerHTML = content;
}
function addTodo(value) {
let id = new Date().getTime();
if (!value) return;
const newTodo = {
id,
value,
isDone: false,
};
todos.push(newTodo);
localStorage.setItem("todos", JSON.stringify(todos));
}
function toggleIsDone(id) {
todos = todos.map((todo) => {
if (todo.id == id) {
const newTodo = {
id: todo.id,
value: todo.value,
isDone: !todo.isDone,
};
return newTodo;
} else {
return todo;
}
});
localStorage.setItem("todos", JSON.stringify(todos));
}
function eraseTodo(id) {
todos = todos.filter((todo) => parseInt(todo.id) !== parseInt(id));
localStorage.setItem("todos", JSON.stringify(todos));
}
document.addEventListener("DOMContentLoaded", () => {
showTodos();
});
todoList.addEventListener("submit", (e) => {
e.preventDefault();
const input = todoList.querySelector("input");
addTodo(input.value);
showTodos();
todoList.reset();
});
todoList.addEventListener("click", (e) => {
if (e.target.matches("span") && e.target.classList.contains("todo-text")) {
const parent = e.target.parentNode;
parent.classList.toggle("todo-checked");
toggleIsDone(parent.dataset.id);
} else if (e.target.classList.contains("todo-erase")) {
const parent = e.target.parentNode.parentNode;
console.log(parent);
eraseTodo(parent.dataset.id);
parent.remove();
}
});
todoBtn.addEventListener("click", () => {
todoList.classList.toggle("todo-del-state");
});