In this lesson I am saving the state of all of the user inputs into LocalStorage.
First I grab the <form> and <ul> on the page, as well as the 'items' in localStorage formatted as JSON if it exists. Otherwise I initialise an empty array (JSON.parse(loalStorage.getItem('items')) || []).
I listen for the following events:
After the JS is loaded, I run populateList(items, itemsList).
populateList(plates = [], platesList) - Takes in / initialises a new array 'plates[]', as well as take in another list 'platesList'. These parameter names are different than the ones I passed in, to ensure it is a reusable function. Set the 'innerHTML' of 'platesList' to a new .map() from 'plates'. For each item, build up a new <li> element.
In addItem(e) - Prevent the event default to ensure the page doesn't refresh (e.preventDefault()).
Get the [name=item] 'text' value from 'this' element. Create a new 'item' element, pass in 'text' and a default state of 'done: false'. Push the 'item' into the 'items' array.
Next run populateList(), then save the 'items' into 'localStorage' (localStorage.setItem('items', JSON.stringify(items))) and reset the input (this.reset()).
In toggleDone(e) - Check if the target of the event is not an <input> (!e.target.matches('input')), If so, exit the function. Otherwise, get the element and the index of that element (e.target, e.target.dataset.index).
Flip the '.done' polarity for that index in 'items' (items[index].done = !items[index].done). Finally save the items into localStorage as JSON (localStorage.setItem('items', JSON.stringify(items))) and re-populate the list (populateList(items, itemsList).
See the Pen
JavaScript30 - 15 - LocalStorage by Corey Noble (@CoreyNoble)
on CodePen.