Search code examples
javascripthtmlvar

Can I avoid html resetting my javascript variable when I use location.href?


My new project is a small "puzzle" game where you enter a room and solve a puzzle inside, then when you go back to the level select section it opens up the next level.

I have thus far been using a single variable "lock" to count up once every time you beat a level and if the value of "lock" corresponds with the level number it would let you through.

Problem is that it seems when I use location.href it resets the "lock" variable.

Html for level select:

//html, link to js and some text
<h1>
<img src="assets/Nextbutton1.png" onclick="t1()" width="100" //1st level button
height="100"> <br>
<img src="assets/Nextbutton2.png" onclick="t2()" width="100" //2nd level button
height="100">

Win screen html

<body>
<h1 align="center"> Congratulations</h1>
<button align="center" onclick="joo()">Back to level select</button> 

Javascript for pretty much everything

var lock;
var taso2;  // future stuff
var taso3 = 2; //future stuff

function joo(){

location.href='index.html'
if (lock == 0) // if statement so you dont progress by playing 1st level over and over
{
lock += 1;}
}

function t2() {
if (lock > 0) {
location.href='Taso2.html';
}
else { alert("You have to beat the previous levels first") }
}

function t1() {
location.href='Taso1.html';
}

Solution

  • HTML in its nature is 'memoryless'. This means that by default it resets its variables every time the page refreshes. However, there are ways to preserve your variables. From w3schools, the way to achieve this is to either use

    • window.localStorage - stores data with no expiration date
    • window.sessionStorage - stores data for one session (data is lost when the browser tab is closed)

    Again from the same website:

    // Store
    localStorage.setItem("lastname", "Smith");
    
    // Retrieve
    document.getElementById("result").innerHTML = localStorage.getItem("lastname");
    

    Please note that this is all using Vanilla JavaScript, as you haven't indicated any frameworks in your question.