I am trying to save the data on local storage of the browser, the data is saved but after the reload of the webpage its CSS and JS interactivity are all lost. I have tried to recreate the HTML elements along with their associated event listeners in showTask() function, but it still didnt worked so i deleted that again.
Below is my code
const inputBox = document.getElementById("input-box");
const listContainer = document.getElementById("list-container");
function addTask() {
if(inputBox.value === '') {
alert("Write something!");
}
else {
let li = document.createElement("li"); //creates element li
li.textContent = inputBox.value; //stores the value from inputbox in in the new created li
listContainer.appendChild(li); // displays the li in list container (variable created at the start of the page)
let remove = document.createElement("span");
remove.textContent = "u00d7"; //this code is for the cross icon
li.appendChild(remove); // appending the span which includes the remove icon in each li
}
inputBox.value = ""; //empties the input field after the text entered
saveData();
}
//this event listener on clicking on li makes its class name checked or unchecked
//if clicked on the delete icon which is a span tag it removes it
listContainer.addEventListener("click", function (e) {
if (e.target.tagName === "LI") {
e.target.classList.toggle("checked");
saveData();
}
else if (e.target.tagName === "SPAN") {
e.target.parentElement.remove();
saveData();
}
}, false);
//saveData function stores the data in local storage of the browser
function saveData() {
localStorage.setItem("data", listContainer.textContent);
}
function showTask() {
listContainer.textContent = localStorage.getItem("data");
}
showTask();
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>To-Do List</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<main>
<section class="to-do-section">
<h2>To-Do List <img src="images/icon.png" alt="icon"></h2>
<section class="input-section">
<input type="text" id="input-box" placeholder="Write your To-do's here!">
<button onclick="addTask()">Add</button>
</section>
<ul id="list-container">
<!-- <li class="checked">Task 1</li>
<li>Task 2</li>
<li>Task 3</li> -->
</ul>
</section>
</main>
<script src="script.js"></script>
</body>
</html>