-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.js
58 lines (48 loc) · 1.61 KB
/
app.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
const content = document.getElementById('itemTitle');
function addItem() {
if (content.value === "") {
alert("Please add some text!");
return;
}
let existingTodos = JSON.parse(localStorage.getItem("todos"));
const contentObj = {
content: content.value,
_id: (Math.floor(100000 + Math.random() * 900000)).toString(),
}
if (existingTodos !== null) {
existingTodos.push(contentObj);
} else {
existingTodos = [];
existingTodos.push(contentObj);
}
localStorage.setItem("todos", JSON.stringify(existingTodos));
updateTodoList(localStorage.getItem("todos"));
content.value = "";
}
function updateTodoList(todos) {
const myList = document.getElementById("myList");
const parsedTodos = JSON.parse(todos);
myList.innerHTML = "";
for (let i = 0; i < parsedTodos.length; i++) {
myList.innerHTML += `
<li>${parsedTodos[i].content} <i class="fas fa-trash-alt" onclick="deleteTodo(${parsedTodos[i]._id})"></i></li>
`
}
}
function deleteTodo(id) {
const todoId = id.toString();
const parsedTodos = JSON.parse(localStorage.getItem("todos"));
let changedTodos = [];
for (let i = 0; i < parsedTodos.length; i++) {
if (parsedTodos[i]._id !== todoId) {
changedTodos.push(parsedTodos[i]);
}
}
localStorage.setItem("todos", JSON.stringify(changedTodos));
updateTodoList(localStorage.getItem("todos"));
}
window.addEventListener("load", function () {
if (localStorage.getItem("todos") !== null) {
updateTodoList(localStorage.getItem("todos"));
}
})