I am currently working on this website https://idle-chicken.glitch.me/chicken.html and I am trying to save the user's progress(the items they purchased, their eggs, cost, etc.) Right now the number of eggs as a cookie, but I was wondering if there is a way for me to save all of the changes both to the JavaScript and the HTML. I am sorry if this is a dumb question I am fine using jQuery Javascript or AJAX (I think that is how you do it)?
This is what I am doing right now
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+ d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.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) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function checkCookie() {
var cookie = getCookie("eggs");
if (cookie != "") {
eggs = cookie;
} else {
setCookie("eggs", eggs, 365);
}
}
$(window).bind("beforeunload", function() {
setCookie("eggs", eggs, 365);
if (notThis) {
return "Do you want to exit this page?";
}
});
and then I do this for the HTML
<body onload="checkCookie()">
Read more here: https://stackoverflow.com/questions/66324847/what-is-the-best-way-to-save-a-users-changes-to-a-html-app
Content Attribution
This content was originally published by qman101 at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.