-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
110 lines (89 loc) · 2.56 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
99
100
101
102
103
104
105
106
107
108
109
110
let button = document.getElementById("enter");
let input = document.getElementById("userinput");
let ul = document.querySelector("ul");
let item = document.querySelectorAll("li");
let deleteButton = document.getElementsByClassName("delete")
let items = []
// Read existing data from localStorage
const loadItems = () => {
const itemsJSON = localStorage.getItem('items')
try {
return itemsJSON ? JSON.parse(itemsJSON) : []
} catch (e) {
return []
}
}
items = loadItems();
items.forEach((item) => {
let li = document.createElement("li");
let delButton = document.createElement("button");
delButton.textContent = "x";
delButton.setAttribute("class", "delete");
li.appendChild(document.createTextNode(item));
li.appendChild(delButton);
ul.appendChild(li);
li.addEventListener("click", function() {
if (li.classList) {
li.classList.toggle("done");
}
});
})
// Save recipes to localStorage
const saveItems = () => {
localStorage.setItem('items', JSON.stringify(items))
}
// Expose recipes from module
const getItems = () => items
function inputLength() {
return input.value.length;
}
function createListElement() {
let li = document.createElement("li");
let delButton = document.createElement("button");
delButton.textContent = "x";
delButton.setAttribute("class", "delete");
li.appendChild(document.createTextNode(input.value));
items.push(input.value);
saveItems();
li.appendChild(delButton);
ul.appendChild(li);
input.value = "";
li.addEventListener("click", function() {
if (li.classList) {
li.classList.toggle("done");
}
});
delButton.addEventListener("click", function() {
const index = items.findIndex(item => item ===(this.parentNode.textContent).slice(0,-1))
items.splice(index,1);
saveItems();
li.parentNode.removeChild(li);
});
}
function addListAfterClick() {
if (inputLength() > 0) {
createListElement();
}
}
function addListAfterKeypress(event) {
if (inputLength() > 0 && event.keyCode === 13) {
createListElement();
}
}
for (let i=0; i<item.length;i++) {
item[i].addEventListener("click", toggleListItem);
}
function toggleListItem() {
this.classList.toggle("done");
}
for (let i=0; i<deleteButton.length;i++) {
deleteButton[i].addEventListener("click", deleteItem);
}
function deleteItem() {
const index = items.findIndex(item => item ===(this.parentNode.textContent).slice(0,-1))
items.splice(index,1);
saveItems();
this.parentNode.parentNode.removeChild(this.parentNode);
}
button.addEventListener("click", addListAfterClick);
input.addEventListener("keypress", addListAfterKeypress);