0

I am currently working on making the to-do list app shown [here][1] work better. I have done things like change the font, but want to use Javascript cookies to make it so that the user's to-dos are properly saved and still there when the page is reopened.

All I need now (which I can't seem to get the idea of how to do) is the part where 1. the browser saves the data and 2. where the browser retrieves the data.

Any help would be greatly appreciated.

<body>
        <!--To-Do Header, where you add tasks-->
        <div id="myDIV" class="header">
            <!--Change one: Make to-do list name different-->
            <h2>To-Do</h2>
            <input type="text" id="myInput" placeholder="Title..." style="padding-bottom: 20px;">
            <span onclick="newElement();" class="addBtn">Add</span>
        </div>
        <!--To-do list-->
        <ul id="myUL">

        </ul>

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 = "close";
  span.appendChild(txt);
  myNodelist[i].appendChild(span);
}
// Click on a close button to hide the current list item
var close = document.getElementsByClassName("close");
var i;
for (i = 0; i < close.length; i++) {
  close[i].onclick = function() {
    var div = this.parentElement;
    div.style.display = "none";
  };
}
// Add a "checked" symbol when clicking on a list item
var list = document.querySelector('ul');
list.addEventListener('click', function(ev) {
  if (ev.target.tagName === 'LI') {
    ev.target.classList.toggle('checked');
  }
}, false);
// Create a new list item when clicking on the "Add" button
function newElement() {
  var li = document.createElement("li");
  var inputValue = document.getElementById("myInput").value;
  var t = document.createTextNode(inputValue);
  li.appendChild(t);
  if (inputValue === '') {
    alert("You must write something to create a task.");
  } else {
    document.getElementById("myUL").appendChild(li);
  }
  document.getElementById("myInput").value = "";
  var span = document.createElement("SPAN");
  var txt = document.createTextNode("\u00D7");
  span.className = "close";
  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";
    };
  }
}

2
  • Please provide all relevant code in an minimal reproducible example in the question itself, not on a third-party site. Jan 17, 2017 at 18:01
  • Ok, @MikeMcCaughan. Will do now.
    – user7070724
    Jan 17, 2017 at 18:02

3 Answers 3

2

Using local storage, as it lasts longer then cookies:

// Store
localStorage.setItem("lastname", "Smith");
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("lastname");

https://developer.mozilla.org/en/docs/Web/API/Window/localStorage

EDIT: @MichaelMior pointed out that local storage may not last longer then cookies, but the cookies are sent with browser requests so it's unnecessary in this case.

9
  • Ok, so I see what it is doing there, but how would I get it to link to the li tags specifically?
    – user7070724
    Jan 17, 2017 at 18:01
  • 1
    @MayorMonty thanks for linking that! I use w3schools a lot because of that too, but I also use websites like CSS-Tricks.
    – user7070724
    Jan 17, 2017 at 18:05
  • 1
    @xC00L Consider using the Mozilla Developer Network documentation isntead developer.mozilla.org/en/docs/Web/API/Window/localStorage Jan 17, 2017 at 18:07
  • 1
    local storage does not necessarily "last longer" than cookies. It's really browser-dependent. I think a better reason to use local storage is that cookies get sent to the server with every request which is unnecessary in this case. Jan 17, 2017 at 18:08
  • 1
    @MichaelMior thanks! i've heard of the mozilla developer network but never actually taken a look.
    – user7070724
    Jan 17, 2017 at 18:12
1

You want to store the text content, so you need to get them first

var values=[...document.getElementsByTagName("li")].map(el=>el.textContent);

Now you can store this array

localStorage.setItem("todos",values);

If the page is loaded, add it back to the page:

localStorage.getItem("todos").forEach(fumction(value){
 //create elem
 elem.textContent=value;
 });

You could also store a HTML collection, but i wouldnt, storing just the text is.much easier...

4
  • Thanks for answering! I just tried your suggestion and it seemed to not want to work with my code. After adding it, I was unable to add to-do's. I will look, because it may have something to do with the variable name, but I just wanted to let you know,
    – user7070724
    Jan 17, 2017 at 18:10
  • After a few seconds of searching, I found a variable called inputValue. Could that affect it? Sorry if that sounds like a foolish question, I am new to javascript.
    – user7070724
    Jan 17, 2017 at 18:23
  • @xC00L its not a full answer. I didnt write copy+ paste code, you need to implement it on your own, i will be glad.to help you ;) Jan 17, 2017 at 18:29
  • Thanks. I will see what I can do to try and implement this if needed, but it looks like another answer is going to work. Thanks for helping though @jonasw
    – user7070724
    Jan 17, 2017 at 18:31
0

Here is a quick example where I store an item and give it a name in localStorage called input. This shows how to setItem() and getItem().

Looks like this example doesn't work in the SO sandbox, so here's a codepen - http://codepen.io/anon/pen/KaNZxX

$('button').on('click',function() {
  localStorage.setItem("input", $('input').val());
  fetch();
});

function fetch() {
  $('#storage').html(localStorage.getItem('input'));
}

fetch(); // fetch on load
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text"> <button>add</button>

<div id="storage"></div>

7
  • Hi! I tried running this code and it didn't seem to work. I want to know, if you look at my current code, I have an area for the actual to-dos to go as an unordered list. Is that where the div id="storage" comes in? Or (just double checked the code) would it be better for me to set the fetch() function to load when the body loads?
    – user7070724
    Jan 17, 2017 at 18:18
  • @xC00L did you check the codepen link? The code won't work in the SO sandbox so I posted a codepen link that works. Yes, the area where you show the to-do's is where the #storage and fetch() code comes in. Using localStorage.getItem() is how you fetch items stored in localStorage. You would loop through those items and display them in the li's where you show stored to-do's. And you would call the function that fetches stored items when someone loads the page (to show already stored to-do's) and you would store an item there as people create a to-do. Jan 17, 2017 at 18:22
  • I figured out the problem. The button to add the to-do's wasn't a real button, it was a span. And since your code used the button press, it wasn't working. I have a few more questions if you don't mind. How would I adjust this to work with my span, since when I added in the "button" to trigger it, I got this mess (i.imgsafe.org/e62099af55.png). And lastly, when the storage comes back, it doesn't seem to want to display in the <li>. It just goes as a text above the rest of the <li>s. How would I go about fixing that? Thanks for all the help so far.
    – user7070724
    Jan 17, 2017 at 18:30
  • @xC00L this was just an example, not necessarily something to copy/paste into your code. Your code example doesn't work or render anything in the browser, do you have a place where I can see what you have so far? Jan 17, 2017 at 18:37
  • I put it on Gist and then remembered Codepen was a thing lol. Here's what I have so far codepen.io/xcool/pen/ggLzWO
    – user7070724
    Jan 17, 2017 at 20:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy