Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Andrew Lundy
13,269 PointsHow to use localStorage after the window was been reloaded?
The following code is for creating a list item for the app.
function createLI(text) { function createElement(elementName, property, value) { const element = document.createElement(elementName); element[property] = value; return element; }
function appendToLI(elementName, property, value) {
const element = createElement(elementName, property, value);
li.appendChild(element);
return element;
}
const li = document.createElement('li');
appendToLI('span', 'textContent', text);
appendToLI('label','textContent', 'Confirm')
.appendChild(createElement('input', 'type', 'checkbox'));
appendToLI('button', 'textContent', 'edit');
appendToLI('button', 'textContent', 'remove');
return li;
}
form.addEventListener('submit', (e) => {
e.preventDefault();
const text = input.value;
input.value = '';
// Checks for empty string in the input area
if (text === '') {
alert("You have not entered a name, please try again.");
return;
}
// Checks for duplicate names
for (i = 0; i < ul.children.length; i++) {
if (text === ul.children[i].children[0].textContent) {
alert("This name has already been entered. Please enter a different name.");
return;
}
}
const li = createLI(text);
ul.appendChild(li);
localStorage.setItem('rsvp', JSON.stringify(ul.outerHTML));
});
As you can see, I have added localStorage.setItem('rsvp', JSON.stringify(ul.outerHTML)); to the event handler, and I am now wondering how to actually get the data to show up when the page reloads?
I have tried using
if (localStorage.rsvp) {
ul.outerHTML = JSON.parse(localStorage.getItem('rsvp'));
}
right after the event handler, but when I reload the page, the buttons on the cards are no longer functional.
1 Answer
Henrik Christensen
Python Web Development Techdegree Student 38,322 Pointsmaybe try something like this
const rsvp = JSON.parse(localStorage.getItem("rsvp"));
if (rsvp != null) {
// do something here
}