-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
72 lines (55 loc) · 1.74 KB
/
main.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
const ITEMS_CONTAINER = document.getElementById("items");
const ITEM_TEMPLATE = document.getElementById("itemTemplate");
const ADD_BUTTON = document.getElementById("add");
let items = getItems();
function getItems(){
const value = localStorage.getItem("todo") || "[]";
return JSON.parse(value);
}
function setItems(items) {
const itemsJson = JSON.stringify(items);
localStorage.setItem("todo", itemsJson);
}
function addItem() {
items.unshift({
description: "",
completed: false
});
setItems(items);
refreshList();
}
function updateItem(item, key, value){
item[key] = value;
setItems(items);
refreshList();
}
function refreshList(){
items.sort((a, b) =>{
if (a.completed){
return 1;
}
if (b.completed){
return -1;
}
return a.description < b.description ? -1 : 1;
});
ITEMS_CONTAINER.innerHTML = "";
for (const item of items) {
const itemElement = ITEM_TEMPLATE.content.cloneNode(true);
const descriptionInput = itemElement.querySelector(".item-description");
const completedInput = itemElement.querySelector(".item-completed");
descriptionInput.value = item.description;
completedInput.checked = item.completed;
descriptionInput.addEventListener("change", () =>{
updateItem(item, "description", descriptionInput.value);
})
completedInput.addEventListener("change", () =>{
updateItem(item, "completed", completedInput.checked);
})
ITEMS_CONTAINER.append(itemElement);
}
}
ADD_BUTTON.addEventListener("click", () =>{
addItem();
});
refreshList();