-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
79 lines (75 loc) · 2.63 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
const todoForm = document.querySelector('form')
const todoInput = document.getElementById('todo-input')
const todoListUL = document.getElementById('todo-list')
let allTodos = getTodos()
updateTodoList()
todoForm.addEventListener('submit', function(e){
e.preventDefault()
addTodo()
})
function addTodo(){
const todoText = todoInput.value.trim()
if(todoText.length > 0){
const todoObject = {
text: todoText,
completed: false
}
allTodos.push(todoObject)
updateTodoList()
saveTodos()
todoInput.value = ""
}
}
function updateTodoList(){
todoListUL.innerHTML = ""
allTodos.forEach((todo, todoIndex)=>{
todoItem = createTodoItem(todo, todoIndex)
todoListUL.append(todoItem)
})
}
function createTodoItem(todo, todoIndex){
const todoId = "todo-"+todoIndex
const todoLI = document.createElement("li")
const todoText = todo.text
todoLI.className = "todo"
todoLI.innerHTML = `
<input type="checkbox" id="${todoId}">
<label class="custom-checkbox" for="${todoId}">
<svg fill="transparent" xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px" fill="#e8eaed">
<path d="M382-240 154-468l57-57 171 171 367-367 57 57-424 424Z"/>
</svg>
</label>
<label for="${todoId}" class="todo-text">
${todoText}
</label>
<button class="delete-button">
<svg fill="var(--secondary-color)" xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px" fill="#e8eaed">
<path d="M280-120q-33 0-56.5-23.5T200-200v-520h-40v-80h200v-40h240v40h200v80h-40v520q0 33-23.5 56.5T680-120H280Zm80-160h80v-360h-80v360Zm160 0h80v-360h-80v360Z"/>
</svg>
</button>
`
const deleteButton = todoLI.querySelector(".delete-button")
deleteButton.addEventListener("click", ()=>{
deleteTodoItem(todoIndex)
})
const checkbox = todoLI.querySelector("input")
checkbox.addEventListener("change", ()=>{
allTodos[todoIndex].completed = checkbox.checked
saveTodos()
})
checkbox.checked = todo.completed
return todoLI
}
function deleteTodoItem(todoIndex){
allTodos = allTodos.filter((_, i)=> i !== todoIndex)
saveTodos()
updateTodoList()
}
function saveTodos(){
const todosJson = JSON.stringify(allTodos)
localStorage.setItem("todos", todosJson)
}
function getTodos(){
const todos = localStorage.getItem("todos") || "[]"
return JSON.parse(todos)
}