forked from wesbos/JavaScript30
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
53 lines (41 loc) · 1.24 KB
/
script.js
File metadata and controls
53 lines (41 loc) · 1.24 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
const addItems = document.querySelector('.add-items');
const itemsList = document.querySelector('.plates');
const items = [];
addItems.addEventListener('submit', handleSubmit);
itemsList.addEventListener('click', handleClick)
function handleSubmit(e) {
e.preventDefault();
const text = this.querySelector('[name=item]').value;
items.push({
text,
done: false
});
this.reset();
updateView(items, itemsList);
updateLocalStorage();
}
function handleClick(e) {
if (!e.target.matches('input')) return;
items[e.target.dataset.index].done = !items[e.target.dataset.index].done
updateLocalStorage();
}
function updateView(plates = [], plateList) {
const html = plates.map((item, index) => {
return `
<li>
<input type="checkbox" data-index="${index}" id="item${index}" ${item.done ? 'checked' : ''}/>
<label for="item${index}">${item.text}</label>
</li>
`
}).join('');
plateList.innerHTML = html;
}
function loadFromStorage(items) {
const arrayString = window.localStorage.getItem('menu') || '[]';
items.push(...JSON.parse(arrayString));
}
function updateLocalStorage() {
window.localStorage.setItem('menu', JSON.stringify(items));
}
loadFromStorage(items);
updateView(items, itemsList);