Incorporating Local Storage into a To-Do List Application

I followed a tutorial from w3schools to create a custom task list, tweaking the code to fit my requirements.

My goal is to ensure that when I click the save button in the toolbar at the top and then refresh the page, the added tasks are preserved.

I've been trying to use JavaScript by assigning a class or ID to the list items (li) and then linking them to local storage, but I haven't achieved success yet.

Attached Code:

var myNodelist = document.getElementsByTagName("LI");
var i;
for (i = 0; i < myNodelist.length; i++) {
  var span = document.createElement("SPAN");
  var txt = document.createTextNode("\u00D7");
  span.className = "taskClose";
  span.appendChild(txt);
  myNodelist[i].appendChild(span);
}

// More JavaScript code here

/*
    Custom CSS styles
*/

html>body {
  height: 100%;
  overflow: hidden;
  margin: 0;
  padding: 0;
  font-family: "Trebuchet MS", sans-serif;
}

/* Additional CSS styles */

<!DOCTYPE HTML>
<!-- HTML code -->

JS for Local Storage:

    JavaScript functions for saving and retrieving user edits from Local Storage

Answer №1

To modify your addTask() function, follow these steps:

function addTask() {
  var li = document.createElement("li");
  li.setAttribute("class", "task_item"); // Updated line (1)
  var inputValue = document.getElementById("input").value;
  var t = document.createTextNode(inputValue);
  li.appendChild(t);
  if (inputValue === '') {} else {
    document.getElementById("taskList").appendChild(li);
  }
  document.getElementById("input").value = "";
  var span = document.createElement("SPAN");
  var txt = document.createTextNode("\u00D7");
  span.className = "taskClose";
  span.appendChild(txt);
  li.appendChild(span);

  for (i = 0; i < close.length; i++) {
    close[i].onclick = function() {
      var div = this.parentElement;
      div.style.display = "none";
    }
  }
}

Make sure to add a class to your list item in step (1) to easily reference all your list items later using

document.getElementsByClassName('task_item');
. Next, your saveEdits() function should be updated as shown below:

function saveEdits() {
  localStorage.clear(); // Modify if needed
  var elements = document.getElementsByClassName('task_item');
  var taskList = []
  for (var i = elements.length - 1; i >= 0; i--) {
    taskList.push(elements[i].innerHTML.split("<span ")[0]);
  };
    var editElems = {
        'edit1': taskList,
    };
    localStorage.setItem('userEdits', JSON.stringify(editElems));
}

You will be referencing all your tasks as an array using

var elements = document.getElementsByClassName('task_item');
. After iterating through the list items and creating the taskList, it will be saved.

Check the web console to view the local storage:

"{"edit1":["task_3","task_2","task_1"]}"

To display your task list on refresh, update your checkEdits() function like this:

function checkEdits() {
    var userEdits = JSON.parse(localStorage.getItem('userEdits'));
    if(userEdits) {
        for(var elementId in userEdits.edit1) {
            var li = document.createElement("li");
            li.setAttribute("class", "task_item");
            li.innerHTML = userEdits.edit1[elementId];
              document.getElementById("taskList").appendChild(li);
            var span = document.createElement("SPAN");
            var txt = document.createTextNode("\u00D7");
            span.className = "taskClose";
            span.appendChild(txt);
            li.appendChild(span);
            for (i = 0; i < close.length; i++) {
              close[i].onclick = function() {
                var div = this.parentElement;
                div.style.display = "none";
              }
            }
        }
    }
}

These updates should meet your requirements.

Note: There may be an issue with how you are deleting a task. Please review.

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

Displaying divs in a reverse order can bring a unique perspective

I have multiple sibling divs that are styled with position: fixed; display: table; top: 0; left: 0; width: 100%; height: 100%;. These divs act as message boxes and are created by a third-party ASP.NET control, preventing me from altering their order in t ...

Error: The name property is not defined and cannot be read in the Constructor.render function

Having trouble building a contact form and encountering an error when trying to access the values. I've checked for bugs in the console multiple times, but it seems like something is missing. Can anyone provide assistance? var fieldValues = { ...

Issue with image preview functionality in dialog modal when loading content via ajax request

<table id="result"> <a href='#' class='pop'><span class='fa fa-eye'><img src='image link here' style='display:none'></a> </table> The hyperlink above is designed to open ...

Is it possible to run a JavaScript script from any location?

Currently, I am diving into a Javascript script and in order to run it seamlessly from any webpage I am browsing, I am thinking of adding a button to my bookmarks or using an extension. To be honest, I am clueless about the process and despite doing some ...

Adaptable HTML design with alignment features

Here is the structure I am working with: <style> #main { max-width: 500px; margin: 0 auto; overflow: hidden; border: 1px solid red; } #container{ margin-right: -50px; } .block{ display: inline-block; width: 100px; height: 100px; border: 1px solid gr ...

Laravel's blade allows you to easily convert an HTML element to an array using the same name

I have two separate divs with similar content but different values <div id="tracks-1"> <div> <label>Song Title</label> <input type="text" name="tracks[song_title]" value=""> <input type="text ...

Utilize separate production environments for each client on the NodeJS server to ensure seamless operation and

After conducting extensive research, I have been unable to find a solution to my current problem. I am operating a Node server with multiple environments (dev, test, demo, prod). The server is deployed on a Linux server in the production environment via a ...

Is there a decrease in performance when interacting with variables in the method below?

Alright, I have a reference to a div stored in a variable, which I'll refer to as div_var. Now, when I want to apply some action to it, I have two options for referencing it: div_var.animate()...... $(div_var).animate()..... The first method is mor ...

Learn the best way to handle special characters like <, >, ", ', and & in Javascript, and successfully transfer escaped data from one text box to another

I am seeking a way to use JavaScript to escape special characters. I came across a code snippet on this URL: http://jsperf.com/encode-html-entities. It successfully handles <>&, but I have encountered an issue with double quotes ("). The JavaScri ...

Is the callback for a request always invoked?

When using the npm module request, I often encounter situations where some requests are not called back, leading to various issues. This has raised a question in my mind - is it expected for the request function to always callback? For instance, if my req ...

What is the method for tallying CSS page breaks in printed HTML documents?

Currently, for my report generation process using HTML and CSS to manage page breaks dynamically. I've enabled the option for users to print multiple reports at once by combining them into different sections within a single HTML document. This helps p ...

Express.js: Request body with an undefined base64 encoding

I'm currently working on transforming a table in .xls format to individual rows in .csv format. I came across a helpful library for this task called XLSX My initial step involves encoding the .xls table into base64 format. Next, I'm attempting ...

Is XMLHttpRequest just sitting idle...?

As a newcomer to the world of javascript and AJAX, I've been stuck on a single problem for the past 8 hours. Despite my best efforts, I just can't seem to figure out what's going wrong. On my website, I have an image with an onclick event ca ...

Need help in setting the default TIME for the p-calendar component in Angular Primeng version 5.2.7?

In my project, I have implemented p-calendar for selecting dates and times. I have set [minDate]="dateTime" so that it considers the current date and time if I click on Today button. However, I would like the default time to be 00:00 when I click ...

Tips for capturing an error generated by a child component's setter?

I've created an App component that contains a value passed to a Child component using the @Input decorator. app.component.html <app-child [myVariable]="myVariable"></app-child> app.component.ts @Component(...) export class AppC ...

JavaScript quiz featuring randomized questions with selectable radio buttons

I need assistance in creating a feature on my webpage where users can select the number of questions they want to answer (ranging from 1 to 10). The selected number of questions should then be displayed randomly, without any duplicates. I am not very famil ...

Having trouble locating the componentwillunmountafterInteraction in the React Native deck swiper

I've been utilizing react native deckSwiper in my project, but I'm having trouble unmounting it from the screen due to an error that says "ReferenceError: Can't find variable componentWillUnmountAfterInteractions". The error stack trace is s ...

javascript mobile nav event

My website utilizes a bootstrap feature for mobile devices where a left sidebar pops up when clicking a button. I am not very familiar with bootstrap, but I would like to link a javascript event to determine if the left sidebar is visible. How can I achiev ...

What strategies can I employ to prevent my div tags from shifting positions relative to each other?

I spent time formatting a div tag for my main content and then placed that div inside another wrapper div. However, when I tried to add my logo to the site, everything shifted. It appeared as though the div containing the logo had pushed the wrapper down. ...

Updating form in react requires a double click

I'm facing an issue with the popup form in my note-taking project. The popup form displays when a user wants to edit a note, and it should already contain the contents of the selected note. While the form shows the correct contents, I've noticed ...