-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathtodo.js
More file actions
96 lines (78 loc) · 2.64 KB
/
todo.js
File metadata and controls
96 lines (78 loc) · 2.64 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
let todos = [];
//
const fetchAllTodos = async () => {
const response = await fetch("http://localhost:3000/todos");
const todos = await response.json();
todos.forEach((todo) => {
createTodoElement(todo);
});
};
fetchAllTodos();
const todosContainer = document.getElementById("todos-container");
const createTodoElement = (todo) => {
const todoItem = document.createElement("div");
todoItem.classList.add("todo-item");
const todoTextElement = document.createElement("p");
todoTextElement.innerHTML = todo.item;
if (todo.completed === true) {
todoTextElement.style.textDecoration = "line-through";
todoTextElement.style.color = "blue";
}
todoItem.appendChild(todoTextElement);
const todoItemButtons = document.createElement("div");
todoItemButtons.classList.add("todo-item-buttons");
const completedBtn = document.createElement("button");
completedBtn.classList.add("completed-btn");
completedBtn.innerHTML = "✓";
completedBtn.style.cursor = "pointer";
completedBtn.addEventListener("click", async () => {
const response = await fetch(`http://localhost:3000/todos/${todo._id}`, {
method: "PATCH",
});
const data = await response.json();
if (data.data.completed) {
todoTextElement.style.textDecoration = "line-through";
todoTextElement.style.color = "blue";
} else {
todoTextElement.style.textDecoration = "none";
todoTextElement.style.color = "#232323";
}
});
todoItemButtons.appendChild(completedBtn);
const deleteBtn = document.createElement("button");
deleteBtn.classList.add("delete-btn");
deleteBtn.innerHTML = "x";
deleteBtn.style.cursor = "pointer";
deleteBtn.addEventListener("click", async () => {
const response = await fetch(`http://localhost:3000/todos/${todo._id}`, {
method: "DELETE",
});
await response.json();
todoItem.remove();
});
todoItemButtons.appendChild(deleteBtn);
todoItem.append(todoItemButtons);
todosContainer.appendChild(todoItem);
};
const newTodoInput = document.getElementById("new-todo-input");
const saveButton = document.getElementById("save-btn");
saveButton.addEventListener("click", async () => {
let newTodoInputValue = newTodoInput.value;
if (newTodoInputValue === "") {
alert("A todo is required.");
} else {
const todoPayload = {
item: newTodoInputValue,
};
const response = await fetch("http://localhost:3000/todos", {
method: "POST",
body: JSON.stringify(todoPayload),
headers: {
"Content-Type": "application/json",
},
});
const todo = await response.json();
createTodoElement(todo);
newTodoInput.value = "";
}
});