Stacker-flow
Stacker-flow

Reputation: 1319

store variables to user session Javascript

I have a 'roulette heatmap' application that I have been working with [URL REMOVED] just for a bit of fun.

It has a bunch of tiles (divs) with a value that gets incremented each time you select on a tile to track the spins on a roulette table. Is there a way to store the incremented numbers to a session so that if the page gets reloaded the variable values are not lost?

Much like the '2048 game' where you can move the tiles, leave the page and come back and it remembers your positions without being registered.

Upvotes: 0

Views: 75

Answers (1)

Tiago Duarte
Tiago Duarte

Reputation: 3376

One way of storing persistent data is using cookies.

Storing a cookie value

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+d.toGMTString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
} 

getting a previously stored cookie value

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1);
        if (c.indexOf(name) != -1) return c.substring(name.length,c.length);
    }
    return "";
} 

http://www.w3schools.com/js/js_cookies.asp

If you do decide to choose this method, I would suggest a cookie viewer to help out.

Upvotes: 2

Related Questions