Created
July 26, 2020 11:44
-
-
Save abhishek2x/4c2f946237608300ac86722b49b439da to your computer and use it in GitHub Desktop.
This gist is created with an intention to clear the concepts of Local Storage in JavaScript.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const addItems = document.querySelector(".add-items"); | |
const itemsList = document.querySelector(".plates"); | |
const items = JSON.parse(localStorage.getItem("items")) || []; | |
function addItem(e) { | |
e.preventDefault(); | |
// console.log('Hello'); | |
const text = this.querySelector("[name=item]").value; | |
const item = { | |
text, | |
done: false, | |
}; | |
// console.log(item) | |
items.push(item); | |
populateList(items, itemsList); | |
localStorage.setItem("items", JSON.stringify(items)); | |
this.reset(); | |
} | |
// This function is recreating the entireList each time | |
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) { | |
// console.log(e); | |
// console.log(e.target); | |
if (!e.target.matches("input")) return; | |
// console.log(e.target); | |
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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment