Skip to content

Commit 62c4db1

Browse files
committed
Completed wesbos#15
1 parent 25ea4ff commit 62c4db1

File tree

1 file changed

+50
-2
lines changed

1 file changed

+50
-2
lines changed

15 - LocalStorage/index-START.html

Lines changed: 50 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,11 +28,59 @@ <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')) || [];
3232

33-
</script>
33+
function addItem(e) {
34+
// Prevent Default Behavior
35+
e.preventDefault();
36+
37+
// Get Form Input Contents, Store in "Item" Object
38+
const text = (this.querySelector('[name=item]')).value;
39+
const item = {
40+
text,
41+
done: false
42+
};
43+
44+
// Add Item to Items Array
45+
items.push(item);
46+
47+
// Add Items to Web Page
48+
populateList(items, itemsList);
49+
50+
// Set items to localStorage
51+
localStorage.setItem('items', JSON.stringify(items));
3452

53+
// Clear Form Input
54+
this.reset();
55+
}
3556

57+
function populateList(plates = [], platesList) {
58+
platesList.innerHTML = plates.map((plate, index) => {
59+
return `
60+
<li>
61+
<input type="checkbox" data-index=${index} id="item${index}" ${plate.done ? 'checked' : ''} />
62+
<label for="item${index}">${plate.text}</label>
63+
</li>
64+
`;
65+
}).join('');
66+
}
67+
68+
// Keep Toggle State On Page Refresh
69+
function toggleDone(e) {
70+
if (!e.target.matches('input')) return;
71+
const el = e.target;
72+
const index = el.dataset.index;
73+
items[index].done = !items[index].done;
74+
localStorage.setItem('items', JSON.stringify(items));
75+
populateList(items, itemsList);
76+
}
77+
78+
// Event Handlers
79+
addItems.addEventListener('submit', addItem);
80+
itemsList.addEventListener('click', toggleDone);
81+
82+
populateList(items, itemsList);
83+
</script>
3684
</body>
3785
</html>
3886

0 commit comments

Comments
 (0)