Skip to content

Commit d087398

Browse files
committed
Completed lesson 15
Reminder: add buttons as homework
1 parent 7f55a7b commit d087398

File tree

1 file changed

+39
-2
lines changed

1 file changed

+39
-2
lines changed

15 - LocalStorage/index-START.html

Lines changed: 39 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,11 +28,48 @@ <h2>LOCAL TAPAS</h2>
2828
<script>
2929
const addItems = document.querySelector('.add-items');
3030
const itemsList = document.querySelector('.plates');
31-
const items = [];
31+
const items = JSON.parse(localStorage.getItem('items')) || [];
32+
33+
function addItem(e) {
34+
e.preventDefault();
35+
const text = (this.querySelector('input[name=item]')).value;
36+
const item = {
37+
text,
38+
done: false
39+
};
40+
items.push(item);
41+
populateList(items, itemsList);
42+
localStorage.setItem('items', JSON.stringify(items));
43+
this.reset();
44+
};
45+
46+
function populateList(plates = [], platesList) {
47+
platesList.innerHTML = plates.map((plate, i) => {
48+
return `
49+
<li>
50+
<input type="checkbox" data-index=${i} id="item${i}" ${plate.done ? "checked" : ""} />
51+
<label for="item${i}">${plate.text}</label>
52+
</li>
53+
`;
54+
}).join('');
55+
};
56+
57+
function toggleDone(e) {
58+
if (!e.target.matches('input')) return; // skip unless target is input
59+
const el = e.target;
60+
const index = el.dataset.index;
61+
items[index].done = !items[index].done;
62+
localStorage.setItem('items', JSON.stringify(items));
63+
populateList(items, itemsList);
64+
}
65+
66+
addItems.addEventListener('submit', addItem);
67+
itemsList.addEventListener('click', toggleDone);
68+
69+
populateList(items, itemsList);
3270

3371
</script>
3472

3573

3674
</body>
3775
</html>
38-

0 commit comments

Comments
 (0)