-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
49 lines (45 loc) · 1.32 KB
/
script.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
const form = document.getElementById("form");
const input = document.getElementById("input");
const todosList = document.getElementById("todos");
const todos = JSON.parse(localStorage.getItem("todos"));
const updateLocalStorage = () => {
const todosElements = document.querySelectorAll("li");
const todos = [];
todosElements.forEach((todoElement) => {
todos.push({
text: todoElement.innerText,
completed: todoElement.classList.contains("completed"),
});
});
localStorage.setItem("todos", JSON.stringify(todos));
};
const addTodo = (todo) => {
let todoText = input.value;
if (todo) todoText = todo.text;
if (todoText) {
const todoElement = document.createElement("li");
if (todo && todo.completed) {
todoElement.classList.add("completed");
}
todoElement.innerText = todoText;
todoElement.addEventListener("click", () => {
todoElement.classList.toggle("completed");
updateLocalStorage();
});
todoElement.addEventListener("contextmenu", (e) => {
e.preventDefault();
todoElement.remove();
updateLocalStorage();
});
todosList.appendChild(todoElement);
input.value = "";
updateLocalStorage();
}
};
if (todos) {
todos.forEach((todo) => addTodo(todo));
}
form.addEventListener("submit", (e) => {
e.preventDefault();
addTodo();
});