I am trying to improve the code of my first project, to do list
and what I want to do is save the items in the localStorage
, so that when I refresh the browser, they are not deleted or restarted, but above all, the items checked or that when deleting the items they do not appear again when refreshing the page. In each item I have three buttons:
- the button to complete or check the item:
checkButton
- the button to edit the tasks:
editButton
- the button to delete the tasks:
trashButton
I store the data in a list of objects that contain a único id
, nombre del item
(where I store the value of the input) and the value of the button that checks the items that is stored in completed
(what would it be checkButton.value
, value that helps me know if the item is completed or checked ).
The problem, as I mentioned before, is that if the item is saved in localStorage
it but not the changes that I make in it. For example, let's say that I put an item on the page, it is saved in localStorage but imagine that later I edit its task, delete it or mark it as finished but when I refresh the page those changes that I made are not saved.
I tried to remove the data from localStorage and re-upload it every time I wanted to edit the values but it didn't work.
Please if you explain to me what is happening and I would also appreciate if you tell me if my code is legible at a glance and if it is understood or rather if it is a clean code
"use strict"
//date function
const dateElement= document.getElementById("date");
const options= {
weekday:"long",
month:"short",
day:"numeric"
}
const today= new Date();
dateElement.innerHTML= today.toLocaleDateString("en-US",options);
const list= document.getElementById("list");
const input= document.getElementById("input");
const normalButton= document.getElementById("normal");
const finishedTask= document.getElementById("done");
const unfinishedTask= document.getElementById("not-done");
const refreshBtn = document.getElementById("refresh-btn");
const failBox = document.getElementById("fail");
const closeBtn = document.getElementById("close-btn");
document.addEventListener("keyup",(event)=>{ if(event.keyCode === 13) addToDo() });
let lists = [];
// Obtener desde localStorage al cargar todo el DOM
window.addEventListener('load', function() {
lists = JSON.parse(localStorage.getItem("item.list")) || [];
// Agregar en HTML los elementos encontrados
lists.forEach((item) => addToDo(item));
});
function addToDo(fromList){
refreshBtn.addEventListener("click",() => refreshPage());
event.preventDefault();
let itemValue= (fromList) ? fromList.name : input.value;
function failAlert(){
failBox.style.display = "block";
closeBtn.addEventListener("click", ()=> failBox.style.display = "none")
}
if(itemValue === "" || itemValue === null) return failAlert();
const itemNew= document.createElement("li");
const deleteButton= document.createElement("button");
const para = document.createElement("p");
const editButton= document.createElement("button");
const checkButton= document.createElement("button");
const buttonsContainer= document.createElement("div");
itemNew.appendChild(buttonsContainer);
buttonsContainer.classList.add("buttons");
//creating text
para.classList.add("text");
const text= document.createTextNode(itemValue);
para.appendChild(text);
//item
itemNew.classList.add("item");
itemNew.appendChild(checkButton);
itemNew.appendChild(para);
list.appendChild(itemNew);
//check-buttton
checkButton.classList.add("checkbox");
checkButton.innerHTML = `<i class="far fa-circle fa-lg"></i>`
checkButton.value= "not-checked";
//edit-button
editButton.classList.add("edit");
editButton.innerHTML = `<i class="far fa-edit"></i>`
buttonsContainer.appendChild(editButton);
//delete-button
deleteButton.classList.add("delete");
deleteButton.innerHTML = `<i class="fas fa-trash-alt"></i>`
buttonsContainer.appendChild(deleteButton);
//ACA ES DONDE CHEQUELO LOS ITEMS
checkButton.addEventListener("click",() =>{
//SI EL VALOR DEL CHECKBUTTON NO ESTA CHEQUEADO EJECUTA LA FUNCION COMPLETEDTASK()
checkButton.value ==="not-checked" ? completedTask(): incompletedTask();
function completedTask() {
checkButton.setAttribute("value","checked");
checkButton.innerHTML = `<i class="far fa-check-circle fa-lg"></i>`
}
function incompletedTask() {
checkButton.setAttribute("value","not-checked");
checkButton.innerHTML = `<i class="far fa-circle fa-lg"></i>`
}
para.classList.toggle("completed");
});
//ACA YO ES DONDE EDITO LAS TAREAS
editButton.addEventListener("click",()=>{
para.innerHTML = `<div class=".edit-container" id = "edit-container"></div>`;
let editContainer = document.getElementById("edit-container")
let editInput = document.createElement("input");
let submitEdit = document.createElement("button");
editInput.classList.add("edit-input");
submitEdit.classList.add("submit-edit");
submitEdit.innerHTML = `<i class="fas fa-plus-circle fa-lg"></i>`
editContainer.appendChild(editInput);
editContainer.appendChild(submitEdit);
submitEdit.addEventListener("click",() => para.innerHTML = editInput.value);
}
);
//ACA ELIMINO LA TAREA
deleteButton.addEventListener("click", ()=>{
list.removeChild(itemNew);
} );
//normal button
normalButton.addEventListener("click", ()=> itemNew.setAttribute("style","display:block") );
//finished-task button
finishedTask.addEventListener("click",()=>{
checkButton.value==="checked" ? itemNew.setAttribute("style","display:block")
:itemNew.setAttribute("style","display:none");
});
//unfinished-task button
unfinishedTask.addEventListener("click",()=>{
checkButton.value==="not-checked" ? itemNew.setAttribute("style","display:block")
:itemNew.setAttribute("style","display:none");
});
let data = createDataList(itemValue, checkButton.value);
if(!fromList) {
lists.push(data);
save();
}
function save(){
localStorage.setItem("item.list", JSON.stringify(lists));
}
function createDataList(name, completed){
return {id: Date.now(), name: name, completed: completed};
}
input.value = "";
}
function refreshPage(){
localStorage.clear();
location.reload();
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="css/style.css">
<link href="https://fonts.googleapis.com/css?family=Roboto+Slab&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Roboto+Condensed:300&display=swap" rel="stylesheet">
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<script src="https://kit.fontawesome.com/09faf5376a.js" crossorigin="anonymous"></script>
<title>To Do List</title>
</head>
<body>
<div class="container">
<div class="header">
<i class="fas fa-sync-alt" id="refresh-btn"></i>
<div class="title-container">
<h1 class="title">To Do List App</h1>
<h2 class="ferre">By Fxrree</h2>
</div>
<div class="date" id="date"></div>
<div class="functionalities">
<button id="normal" class="normal">NORMAL</button>
<button id="done" class="done">DONE</button>
<button id="not-done" class="not-done">NOT-DONE</button>
</div>
</div>
<div class="fail" id="fail">
<i class="fas fa-times-circle" style="color: #fff;" id="close-btn"></i>
<p class="failed-text">Please type a valid to do</p>
</div>
<div class="content">
<ul id="list" class="list"></ul>
</div>
<div class="add-item">
<input type="text" class="input" id="input" placeholder="Add something to do">
<i class="fas fa-plus-circle fa-lg" id="button" onclick="addToDo()"></i>
</div>
</div>
<script src="app.js/app.js"></script>
</body>
</html>
You must modify the localStorage data also in each event of the edit and checked button of each corresponding item. For example in this line:
There you are only displaying the new value in the element, but not modifying the localStorage data. What you should do there is detect which item is in localStorage corresponding to the DOM item that you are modifying and then generate a new array with the edited item and then save it in localStorage. However, as your code is, you will have to make several modifications. The fastest would be to add a "data-id" to the "li.item" with the value of the id of the items in your localStorage (which is the "new Date()" you use). So inside the event handler you could do something like this:
This idea itself would work. Remember that you should also do something similar with the checked button.
In addition to this, I would suggest the following:
In this way, much less processes will be used in each edition.
... This mode you can take to the rest of your functionalities. Remember that it is better to maintain order and readability than a super abstract and compact code.
Happy code!