Adyy Pop
Adyy Pop

Reputation: 115

Saving a variable after closing browser

Ok so I got a simple script, that increase a number when a button is pressed:

<script>
var count = 0;
    var button = document.getElementById("countButton");
    var display = document.getElementById("displayCount");

    button.onclick = function(){
        count++;
        display.innerHTML = count;
        } </script>

This is the button: <input type="button" value="Count" id="countButton" />

And this is the number: <span id="displayCount">0</span>

My problem is, that the number is starting again from 0 when I refresh the page. What I want, for example, if I press the button twice and then restart the browser, the page will display number "2", not 0.

Some help?

Upvotes: 2

Views: 4331

Answers (4)

Megan
Megan

Reputation: 41

An alternative to local storage is using cookies. Save the value in a cookie before the browser closes using window.onbeforeunload then access it when the page loads. http://www.w3schools.com/js/js_cookies.asp

Upvotes: 0

Robin-Hoodie
Robin-Hoodie

Reputation: 4974

That is because the script is reloaded every time you refresh the page.

The most modern/simple solution to solve this is using webstorage (local/session storage in the browser) which was introduced with HTML5.

With this you could do:

localStorage.setItem('count', '0');
var incrementedCount = localStorage.getItem('count') + 1;
localStorage.setItem('count', incrementedCount);

localStorage (and sessionStorage) is a property on the window object and can be used to save data inbetween browser sessions, sessionStorage will only keep the data in one session and is less useful for your use case.

It's a very simple API to use and at the moment it can only store strings, so to store objects you need to use JSON.stringify and JSON.parse

Upvotes: 0

mr-wildcard
mr-wildcard

Reputation: 550

You need to use localStorage API.

http://www.w3schools.com/html/html5_webstorage.asp

Not tested.

<script>
    var count = localStorage.getItem("count") || 0;
    var button = document.getElementById("countButton");
    var display = document.getElementById("displayCount");

    button.onclick = function() {
        count++;
        display.innerHTML = count;

        localStorage.setItem("count", count);
    }
</script>

Upvotes: 1

nicael
nicael

Reputation: 18995

Local storage seems to be the thing you want.

var count = 0;
if(localStorage.btncount){count=localStorage.btncount;} //check if you have already stored it; set count to it if yes
    var button = document.getElementById("countButton");
    var display = document.getElementById("displayCount");
    display.innerHTML = count;
    button.onclick = function(){
        count++;
        localStorage.btncount=count; // store the count
        display.innerHTML = count;
    }

Upvotes: 5

Related Questions