Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
This gist is created with an intention to clear the concepts of Local Storage in JavaScript.
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