Skip to content

Instantly share code, notes, and snippets.

@abhishek2x
Created July 26, 2020 11:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abhishek2x/4c2f946237608300ac86722b49b439da to your computer and use it in GitHub Desktop.
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.
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