-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
98 lines (80 loc) · 2.59 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
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
97
98
let listState = [];
const STATE_KEY = "todo-list";
function loadState(){
const listState = localStorage.getItem(STATE_KEY);
if(listState !== null){
return JSON.parse(listState);
}
return [];
}
function saveState(list){
localStorage.setItem(STATE_KEY, JSON.stringify(list));
}
function iniList(){
// load state
listState = loadState();
// render list
const ul = document.getElementById("list");
for(const item of listState){
// Put item into li
const li = document.createElement("li");
li.classList.add("item");
li.innerText = item.text;
li.onclick = checkItem;
if(item.checked) li.classList.add("checked");
const deleteButton = document.createElement("span");
deleteButton.classList.add("delete");
deleteButton.onclick = deleteItem;
li.appendChild(deleteButton);
ul.appendChild(li);
}
}
function addItem(){
const ul = document.getElementById("list");
const input = document.getElementById("input");
const text = input.value; /* get the input string from input */
if(text === ""){
alert("Please input the item");
return;
}
const newItem = document.createElement("li");
newItem.classList.add("item");
newItem.innerText = text;
newItem.onclick = checkItem;
const deleteButton = document.createElement("span");
deleteButton.classList.add("delete");
deleteButton.onclick = deleteItem;
newItem.appendChild(deleteButton);
ul.appendChild(newItem);
listState.push({
text,
checked: false
});
saveState(listState);
input.value = "";
}
function checkItem(){
const item = this;
const parent = item.parentNode;
// Use Array.from let parent(iterable) become an array, and get item's index
const index = Array.from(parent.childNodes).indexOf(item);
// false -> true or true -> false
listState[index].checked = !listState[index].checked;
item.classList.toggle("checked");
saveState(listState);
}
function deleteItem(){
const item = this.parentNode;
const parent = item.parentNode;
const index = Array.from(parent.childNodes).indexOf(item);
parent.removeChild(item);
listState.splice(index, 1); // delete item in listState by 'splice' function
saveState(listState);
}
iniList();
const addButton = document.getElementById("add-button");
addButton.addEventListener('click', addItem);
const form = document.getElementById("input-wrapper");
form.addEventListener('submit', (e) => {
e.preventDefault(); /* Prevent to refresh webpage */
});