-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtodo.js
More file actions
79 lines (62 loc) · 1.84 KB
/
todo.js
File metadata and controls
79 lines (62 loc) · 1.84 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
// save to local store
// load from local store
const toDoForm = document.querySelector('.js-toDoForm');
const toDoInput = toDoForm.querySelector('input');
const toDoList = document.querySelector('.js-toDoList');
const TODOS_LS = 'toDos';
let toDos = []; // save to do list
function saveToDo(){
localStorage.setItem(TODOS_LS, JSON.stringify(toDos));
}
function writeToDo(text){
const newId = toDos.length + 1;
// save to html
const li = document.createElement('li');
const span = document.createElement('span');
span.innerText = text;
li.id = newId;
const delBtn = document.createElement('button');
delBtn.innerText = 'X';
delBtn.addEventListener("click", deleteToDo);
li.appendChild(span);
li.appendChild(delBtn);
toDoList.appendChild(li);
const toDoObj = {
text: text,
id: newId
};
// save to local store
toDos.push(toDoObj);
saveToDo();
}
function loadToDos(){
const loadedToDos = localStorage.getItem(TODOS_LS);
if(loadedToDos !== null){
// const parsedToDos = JSON.parse(loadedToDos);
JSON.parse(loadedToDos).forEach(function(toDo){
writeToDo(toDo.text);
});
}
}
function deleteToDo(event){
// search parent node
const selectedBtn = event.target;
const parentLi = selectedBtn.parentNode;
toDoList.removeChild(parentLi);
const cleanToDo = toDos.filter(function(toDo){
return toDo.id !== parseInt(parentLi.id);
})
toDos = cleanToDo;
saveToDo();
}
function handleSubmit(event){
event.preventDefault();
const currentValue = toDoInput.value;
writeToDo(currentValue);
toDoInput.value = "";
}
function init(){
loadToDos();
toDoForm.addEventListener("submit", handleSubmit);
}
init();