DEV Community

AndyBullet
AndyBullet

Posted on

Problem with localStorage

Hi guys! I have a problem.
https://pastebin.com/pPCpxT9N
By this code I would like to change the text written in the paragraph from "Text" to "Another text", and I want to save the changement by localStorage, but it doesn't work. Can you tell me why?

Top comments (5)

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);
}
Collapse
 
neradev profile image
Moritz Schramm

My current guess: You need to prevent the default behavior of the button. Normally the page just reloads which is the reason why you cannot see your changes.

Collapse
 
pfacklam profile image
Paul Facklam

Agree. He saves the text before changing it.