Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Update 15 with logic from tutorial
  • Loading branch information
LHJE committed Jul 7, 2021
commit c507777d35acf910207b4ed1fb6ba491f7fb97c0
46 changes: 44 additions & 2 deletions 15 - LocalStorage/index-START.html
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,53 @@ <h2>LOCAL TAPAS</h2>
<script>
const addItems = document.querySelector('.add-items');
const itemsList = document.querySelector('.plates');
const items = [];
const items = JSON.parse(localStorage.getItem('items')) || [];

function addItem(e) {

e.preventDefault()

const text = (this.querySelector('[name=item]')).value;
const item = {
text,
done: false
};

items.push(item);
populateList(items, itemsList);
localStorage.setItem('items', JSON.stringify(items));
this.reset();
}

function populateList(plates = [], platesList) {
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('');
}

function toggleDone(e) {
if (!e.target.matches('input')) return; // skip this unless it's an input
const el = e.target;
const index = el.dataset.index;
items[index].done = !items[index].done;
localStorage.setItem('items', JSON.stringify(items));
populateList(items, itemsList);
}

addItems.addEventListener('submit', addItem);

itemsList.addEventListener('click', toggleDone);

populateList(items, itemsList);


</script>


</body>
</html>