1

I have this code here:

<script>
            const stored = localStorage[location.href]
            const number = stored || Math.floor(Math.random() * 6) + 2

            document.getElementById("n1").innerHTML = number

            if ( !stored ) localStorage[location.href] = number
</script>
<div>
 The first number is <span id="n1"></span>.
</div>

That displays a random number between 2~6 and that saves that to the user's cache, so if he reloads the page the same number will appear again. But what I am trying to do now is to display a second number, and I am trying this:

<script>
            const stored2 = localStorage[location.href]
            const number2 = stored2 || Math.floor(Math.random() * 8) + 3

            document.getElementById("n2").innerHTML = number2

            if ( !stored2 ) localStorage[location.href] = number2
</script>
<div>
     The second number is <span id="n2"></span>.
 </div>

But the <span id="n2"></span> is display always the same number as in <span id="n1"></span>. I guess it has something to do with the local storage in the user's cache. How make it display 2 different numbers but keep storing those numbers in the user's cache so if he reloads the page the same 2 number would be displayed?

Thanks in advance

1
  • localStorage[location.href] <-- so you use same thing and wonder why is the same? Commented Apr 10, 2019 at 23:54

1 Answer 1

4

You’ve stored both numbers in localStorage under the same key (location.href) so the second one is overwriting the first.

You need to use different keys or store the numbers in a JSON dictionary and store that instead.

Sign up to request clarification or add additional context in comments.

4 Comments

Hey, thanks for the reply! Yea, that's the problem. But I can't change that key because it's mapping it to the current URL. So the generated number by the script can change if the user goes to a different page but will keep the same if he just reloads the page. Is there any way to generate 2 different numbers and store it in localStorage but mapped by the page URL?
You can just append some known string to the end of the url (numberOne and numberTwo or something similar). That way the key stays the same between visits but is different for the numbers.
Thanks a lot! Can you give me some example code based on mine?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.