Hunter Chen
Hunter Chen

Reputation: 65

How to use localStorage to change value of variable on .js on a HTML file and have the value be retained when on other HTML file?

I have a JavaScript file with some variables on it and multiple HTML files accessing it, but I want it so that when I change a variable in JavaScript, the value is retained in different HTML files and when I reload the page.

say this is my JavaScript file, lets call it variables.js

localStorage.setItem("number", 1);

var number = parseInt(localStorage.number);

console.log(number);

say this is one of my HTML files

<script src="variables.js">
number;
</script>

<script>
/*I've tried all 3 of these separatetly and together, but the value resets back to 10 when accessed on a different HTML file or when I reload the page*/
number = 2;
localStorage.setItem("number", 2);
localStorage.number = 2;
</script>

when I reload the page, the value of the variable resets back to 1 instead of 2

What is the problem here?

Upvotes: 0

Views: 415

Answers (1)

Obsidian Age
Obsidian Age

Reputation: 42314

The problem is in your first two lines of variables.js:

localStorage.setItem("number", 1);
var number = parseInt(localStorage.number);

Every time variables.js gets loaded (it's called at the top of your HTML file with <script src="variables.js">), the localStorage is set to 1, and considering number is set after that, the local variable number is also set to 1 (which is later outputted to the page).

Instead of setting number to parseInt(localStorage.number), you're looking to retrieve the value from localStorage with localStorage.getItem("number"), and you're looking to do this before modifying it.

To output one value at first, and then a new value the second time the user sees the page, you can check the value is set with if (localStorage.number). If it is set, you set the new value. If it is not set, you set the original value. You'll also want to check this when outputting the value to the page.

This can be seen in the following (sandboxed) StackSnippet:

// Output whatever is in the storage, *if* it is set
if (localStorage.number) {
  document.getElementById("output").innerHTML = localStorage.getItem("number");
}

// If the number has already been set to 1, set it to 2
if (localStorage.number) {
  localStorage.setItem("number", 2);
}
// Else set it to 1
else {
  localStorage.setItem("number", 1);
}
<div id="output">Not set yet!</div>

And in this JSFiddle snippet.

Hope this helps! :)

Upvotes: 1

Related Questions