-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscripts.js
71 lines (65 loc) · 2.07 KB
/
scripts.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
const addItems = document.querySelector('.add-items');
const itemsList = document.querySelector('.plates');
const selectAllButton = document.querySelector('#select-all-button');
const deSelectAllButton = document.querySelector('#deselect-all-button');
let items = JSON.parse(localStorage.getItem('items')) || [];
function addItem(event) {
event.preventDefault();
const item = {
text: (this.querySelector('[name=item]')).value,
done: false
};
items.push(item);
populateList(items, itemsList);
localStorage.setItem('items', JSON.stringify(items));
this.reset();
}
function populateList(plates = [], platesList) {
if (plates.length > 0) {
platesList.innerHTML = plates.map((plate, i) => {
return `
<li>
<input type="checkbox" data-index=${i} id="item${i}" ${plate.done ? 'checked' : ''} />
<label for="item${i}">${plate.text}</label>
</li>
`;
}).join('');
} else {
return `<li>Loading Tapas...</li>`;
}
}
function toggleDone(e) {
if (!e.target.matches('input')) return;
const element = e.target;
const index = element.dataset.index;
items[index].done = !items[index].done;
localStorage.setItem('items', JSON.stringify(items));
populateList(items, itemsList);
}
function selectAll(e) {
e.preventDefault();
items = items.map(item => {
return {
...item,
done: true
};
});
localStorage.setItem('items', JSON.stringify(items));
populateList(items, itemsList);
}
function deSelectAll(e) {
e.preventDefault();
items = items.map(item => {
return {
...item,
done: false
};
});
localStorage.setItem('items', JSON.stringify(items));
populateList(items, itemsList);
}
addItems.addEventListener('submit', addItem);
itemsList.addEventListener('click', toggleDone);
selectAllButton.addEventListener('click', selectAll);
deSelectAllButton.addEventListener('click', deSelectAll);
populateList(items, itemsList);