Thursday, July 23, 2015

javascript - Saving Scores Using Cookies


I've recently created a small galiga like game recently using JavaScript and HTML5. I've run into a bit of trouble saving cookies, the cookie saves, but then resets itself when the page is refreshed, my code:


function saveScore() {
var date = new Date();
date.setMonth(date.getMonth()+5);

var expires = "; expires=" + date.toGMTString();
document.cookie = "score=" + lvl + expires + "; path=/";
}

function loadScore() {

var cookiearray = document.cookie.split(';');
for (var i = 0; i < cookiearray.length; i++) {
var name = cookiearray[i].split('=')[0];
var value = cookiearray[i].split('=')[1];

if (name == "score") {
alert("Prior score found. Loading score...");
lvl = value;
}
}
}

EDIT: It appears as though I made an error outside of the given code, and reset the level to zero, I fixed this, and everything works well, I apologize for any confusion caused.



Answer



ddocument.cookie = "score=" + lvl + expires + "; path=/";


One d too much in document. Is that typo also in your real code?


When I might suggest an alternative solution: Why don't you use HTML5 localStorage? As long as you don't have any server-sided programming which needs persistent data, it's a much superior solution.


When you already require that the users browser supports canvas you don't have to worry about browser support for localStorage. Almost every browser which supports canvas also supports localstorage.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...