DEV Community

Discussion on: Problem with localStorage

Collapse
 
webdevchallenges profile image
Marc

Check this out: codepen.io/jofrly/pen/oNNdLpL

I think the main Problem with your code was that you defined the window.onload function within the changeAndStoreText function.

Still: You save the text content to the local storage before changing it.
Therefore the first time you click the button, the string Text gets saved to the local storage.
The second time you click the button, the string Another text gets saved to the local storage.
When you reload the page after clicking the button the second time, the paragraph gets populated with Another text.

Collapse
 
andybullet profile image
AndyBullet

Is there a way to make it work on a single click?

Collapse
 
webdevchallenges profile image
Marc

Yes:

function changeAndStoreText() {
  textElement.innerHTML = 'Another text';
  var textContent = textElement.textContent;
  localStorage.setItem('firstScreenText', textContent);
}