Tips for preserving the contents of a list with HTML and Javascript

My latest project involves creating a website with a To-Do list feature. Users should be able to add and delete items from the list, which I achieved using JavaScript. Now, my next goal is to ensure that the current items on the list are saved when the page is refreshed.

I'm looking for a way to persistently store the items added by users so that even after a page reload, the To-Do list retains all the entries. As I continue to learn HTML, CSS, and JavaScript, any guidance on how to achieve this would be greatly appreciated.

Answer №1

One practical suggestion is to store the list contents as a string in localStorage. Update this string whenever the list changes, and upon page load, check localStorage to see if there's a saved list.

Additionally, there are some outdated coding practices in your code:

  • Avoid using .getElementsByClassName() or .getElementsByTagName() in favor of .querySelectorAll(), which is more modern.
  • Separate HTML from JavaScript for event handling rather than using inline event attributes.
  • Instead of creating a text node with createTextNode, directly set the textContent property of an element.

Note: The provided example won't work on Stack Overflow due to sandboxing but runs fine on a live page like in this Fiddle demo. Modify the list on the Fiddle, close the browser, reopen it, and see your changes restored.

Check the capitalized comments below for improvements:

// CHECK FOR A SAVED LIST IN LOCALSTORAGE ON PAGE LOAD
const theList = document.querySelector("#myUL");
let ls = localStorage.getItem("list");
if(ls){
  myUL.innerHTML = ls; // Restore list from localStorage
}

// USE JAVASCRIPT FOR EVENT HANDLING, NOT INLINE HTML ATTRIBUTES LIKE 'onclick'
document.querySelector("span.addBtn").addEventListener("click", newElement);

// UPDATE: AVOID GETELEMENTSBYTAGNAME AND USE QUERYSELECTORALL FOR CONSISTENCY
document.querySelectorAll("LI").forEach(function(element){
  const span = document.createElement("SPAN");
  span.classList.add("close");
  span.textContent = "\u00D7";
  element.appendChild(span);
});

// Clicking 'close' should remove the element, not just hide it
const close = document.querySelectorAll(".close");
close.forEach(function(element){
  element.addEventListener("click", function(){
    this.parentElement.remove();
    // UPDATE LOCAL STORAGE 
    localStorage.setItem("list", myUL.innerHTML);
  });
});

// Add a "checked" symbol when clicking on a list item
document.querySelector('ul').addEventListener('click', function(ev) {
  if (ev.target.tagName === 'LI') {
    ev.target.classList.toggle('checked');
  }
});  // ADDITIONAL ARGUMENTS(RIGHT) CAN BE PASSED

const theInput = document.getElementById("myInput");

// Create a new list item on 'Add' button click
function newElement() {
  var li = document.createElement("li");
  // AVOID CREATING TEXT NODE AND APPEND, SET TEXTCONTENT DIRECTLY
  if (theInput.value === '') {
    alert("You must write something!");
  } else {
    li.textContent = theInput.value;
    theList.appendChild(li);
    // UPDATE LOCAL STORAGE 
    localStorage.setItem("list", myUL.innerHTML);
  }
  theInput.value = "";

  const span = document.createElement("SPAN");
  span.classList.add("close");
  span.textContent = "\u00D7";
  li.appendChild(span);
}
/* Use classes instead of inline styles for showing/hiding elements */
.hidden { display:none; }

/* CSS styling for the to-do list */
<div id="myDIV" class="to-do-header">
  <h2 class="table-title">To Do</h2>
  <input id="myInput" placeholder="What do you want to do?">
  <span class="addBtn">Add</span>
</div>
  
<ul id="myUL">
  <li>Wake up</li>
  <li>Meeting with the team</li>
  <li>Have an amazing lunch</li>
  <li>Finish the project</li>
  <li>Get some pizza</li>
  <li>Go to sleep</li>
</ul>

Answer №2

If you prefer not to utilize your backend, a viable option is to make use of the localStorage.

Credit: Mozilla docs

Here is a basic example:

const tasks = [{id:1,title:'save the world', description:'today'},...]

localStorage.setItem('tasks', JSON.stringify(tasks)); // save the tasks

const savedTasks = JSON.parse(localStorage.getItem('tasks')) || []; // load the tasks

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Obtain the initial Firebase child element without a specific key

Trying to access the first child of a firebase object is my current challenge. The reference is structured as follows: var sitesToVisitRef = firebase.database().ref('sitesToVisit') The reference is confirmed functional as I am able to write to ...

Transforming Text On Hover Using CSS, as well as Customizing the Style

I've been struggling with this issue for quite some time now. Despite scouring the first page of Google search results for "css change text on hover," I have not been able to find a solution. Inside a div, I have text that is styled and positioned us ...

Is it possible to generate HTML form fields with fixed positions when using Orbeon forms?

Is there a way in Orbeon forms to position input fields at specific coordinates, relative to a background image? I currently have a paper form that fills an entire page. My goal is to use the scanned image of this form as a background and then overlay inp ...

What causes Chrome Extension Images to appear broken when they are inserted into the DOM?

Currently working on a Chrome extension, I am attempting to insert a div with a background image into the DOM using a content script. The CSS is loading correctly, and upon inspecting the Developer Tools, the image URL appears to be correct. $('.clos ...

React is still unable to display images when looping, despite the use of the "require"

I am facing an issue with extracting image paths from an array using the map function. The problem is that the image path is being printed as a string instead of rendering as an image. I tried using the require keyword, but I encountered an error stating " ...

Converting an array of object keys into integers only can be done using JavaScript

Here is an array of objects with various nutrients and their values: [ {nutrient: "Energy", per100: "449kcal", per35: "157kcal", id: 6} {nutrient: "Fat", per100: "24.4g", per35: "8.6g", id: 1} {nutrient: "Saturated fat", per100: "4.5g", per35: "1.6g ...

Tips for integrating a unique font into your PhoneGap project

I've been attempting to incorporate a custom font into my PhoneGap application, trying out two different methods I came across online. Unfortunately, neither of them seem to be effective when using PhoneGap 3 and Xcode 5. First method involves using ...

Numerous anchor links are present

Is it possible to eliminate the red lines between "google links" while keeping the border color as red? How can I achieve this? Here is the code snippet provided: <!doctype html> <html> <head> <title>Website</title> </he ...

`Proliferating values through constantly changing addition`

I am facing an issue with my code that involves 3 input fields: <div class="row"> <input onblur="calc_basic_amount();" id="rate_basic"></input> <input onblur="calc_basic_amount();" id="qty_b ...

Is TypeScript's nullish coalescing operator (??) supported by more browsers compared to JavaScript's equivalent?

When it comes to the nullish coalescing operator (??) in JavaScript, browser support is limited to newer browsers such as Chrome 80, Edge 80, and Firefox 72. Since TypeScript gets converted to JavaScript, do nullish coalescing operators also undergo some ...

Can you show me a way to use jQuery to delete several href links using their IDs at once?

Currently facing a challenge with removing multiple href links that share the same ID. Here is a snippet of my code: $('.delblk').click(function(e) { e.preventDefault(); var id = $(this).attr('id').substr(7); ...

Using routerLink for linking to multiple components

Below is the anchor tag provided: <a class="uppercase" routerLink="settings/pressure" routerLinkActive="text-success" (click)="closeModal()" > <div class="pad-btm"> PRESSURE </div> </a> I need to include another route ...

Troubleshooting: AngularJS Http Post Method Failing to Execute

I am attempting to make an HTTP POST request to update my database using AngularJS. Although my code is not displaying any errors, the database is not being updated and I'm having trouble pinpointing the issue. Below is the code snippet: //topic-serv ...

Having trouble with Vue image source file paths?

Having an issue with loading an image via file_path on Vue. When using a hardcoded path, it works fine. Refer to the sample code below: JavaScript function getRestaurantsbyId(id) { var restaurants = { "1" : { "name": "xxxx", ...

Using CSS Zoom / Transform with the iframe Tag in HTML

I'm currently working on embedding a child web page (a plain HTML/PHP file) into a parent web page built on WordPress. The challenge I'm facing is that the parent web page has a width of only 800px, whereas the child web page has a width of appro ...

Placing an image on a three.js cube using overlay does not function properly

I attempted to superimpose an image onto a cube by utilizing code from GPT chat and Blackbox AI, but in both cases, I encountered a black screen. I saved the code in a file named test.html and tested it on Google Chrome and Opera GX browsers, only to be me ...

Loading CSS files conditionally in Angular2's index.html

Currently, my index.html page features a dark theme: <base href="/"> <html> <head> <title>XXX</title> </head> <body> <link rel="stylesheet" type="text/css" href="assets/dark_room.css"> <my-app ...

Perform an Ajax call just one time

$('#addToCart').click(function () { let csrf = $("input[name=csrfmiddlewaretoken]").val(); let trTable = $(this).parents('div')[1]; let customPrice = $($(trTable).children('div') ...

Using React, retrieving the value of a checked radio button from the state

My issue involves a list of radio buttons generated from a map loop containing numbers like 1, 2, and 3. When I select a radio button, it should set a state: <ul className="flex gap-6 justify-center"> {maxPaxArr.map((keypax) => ...

What is the best way to display changing session variables in PHP?

Purchase Page: This page allows customers to select business card orders in various foreign languages and customize their options. Whenever a user decides to add an extra card by clicking a button, javaScript dynamically includes new form fields. To ensur ...