showing results for - "how to prevent todos from vanishing after refreshing page javascript"
Mira
02 Feb 2020
1const addButton = document.querySelector("#addToDo");
2const delBtn = document.querySelector("#delToDo");
3
4addButton.addEventListener("click", addTask, false);
5var tasksID = 0;
6
7function saveTask(taskID, taskInfo) {
8  // Get tasks from local storage
9  let tasks = localStorage.getItem("todo-tasks");
10
11  if (!tasks) {
12    tasks = {};
13  } else {
14    tasks = JSON.parse(tasks);
15    tasks[taskID] = taskInfo;
16  }
17
18  // Save the result back
19  let infobj = JSON.stringify(tasks);
20  localStorage.setItem("todo-tasks", infobj);
21}
22
23function drawSavedTasks() {
24  let tasks = localStorage.getItem("todo-tasks");
25  if (tasks) {
26    tasks = JSON.parse(tasks);
27    Object.keys(tasks).forEach(k => {
28      addTask(null, tasks[k]);
29    });
30  }
31}
32
33drawSavedTasks();
34
35function addTask(e, textToDo = undefined) {
36  if (!textToDo) {
37    textToDo = document.querySelector("#toDo").value;
38  }
39
40  var list = document.querySelector(".list");
41  var divToDo = document.createElement("div");
42  var p = document.createElement("p");
43  var delButton = document.createElement("button");
44
45  divToDo.setAttribute("id", "todo" + tasksID);
46  divToDo.setAttribute("class", "toDo");
47  delButton.classList.add("delToDo");
48
49  delButton.textContent = "Delete";
50  p.textContent = textToDo;
51
52  delButton.onclick = function() {
53    divToDo.parentNode.removeChild(divToDo);
54  }
55
56  divToDo.appendChild(p);
57  divToDo.appendChild(delButton);
58
59  list.appendChild(divToDo);
60  saveTask(tasksID, textToDo);
61  ++tasksID;
62}
similar questions