1

I am working on a project that involves a global 'bank' of points.

I've been trying to use snippits of this code for it, but I can't get the variable to save after refresh.

    <!DOCTYPE HTML>
<html>
<head>
    <title>Javascript variable testing</title>
</head>

<body>
    <script type="text/javascript">
    var clicks = 500000;

    function onClick() {
        clicks += 1;
        document.getElementById("clicks").innerHTML = clicks;

    };

    </script>
    <button type="button" onClick="onClick()">Click this bit</button>
    <p>Clicks: <a id="clicks">500000</a></p>

</body>
</html>

1 Answers1

1

Set you data to localStorage. Here is documentation https://developer.mozilla.org/en/docs/Web/API/Window/localStorage

That can get values after page refresh.

Set you value using: localStorage.setItem('key', 'value');

Get you value from local storage after page refreshed : localStorage.getItem('key');

Otherwise you can use sessionStorage, Web SQL & cookies.

Example :

var clicks = 500000;

localStorage.setItem('clicks', clicks); // set you value to localStorage

function onClick() {
  clicks += 1;
  localStorage.setItem('clicks', clicks); // update you value
  document.getElementById("clicks").innerHTML = clicks;

}

window.onload = function() {
  clicks = localStorage.getItem('clicks'); // get your value from localStorage
};
<!DOCTYPE HTML>
<html>

<head>
  <title>Javascript variable testing</title>
</head>

<body>
  <button type="button" onclick="onClick()">Click this bit</button>
  <p>Clicks: <a id="clicks">500000</a>
  </p>

</body>

</html>
0xdw
  • 3,755
  • 2
  • 25
  • 40