I'm new at coding and today for a few days I've tried to code a simple clicker game that has a counter in it, basically all you had to do was to click the image to increase your xp number and after 25 xp number you get 1 kill count from it, I've tried the localstorage setitem and get item, they're working flawlessly however after I refreshed the page and then clicked on the image again the counter reset from 1 I've tried a few thin
<html>
<head>
<title> Menggokil Adventure </title>
</head>
<body>
<p>XP: <span id="XP">0</span></p>
<p>KillCount <span id="KillCount">0</span></p>
<img src="gokil.jpg" height="256px" width="256px" onclick="addToXP (1)">
<br>
<button onclick="SAVE()">Save Game Gokil ini</button> <button onclick="LOAD()">Load Game Gokil ini</button>
</body>
</html>
<script>
var XP= 0 , checkXP;
var KillCount=0;
function addToXP(amount) {
XP = XP + (amount)
document.getElementById("XP").innerHTML = XP;
killCount();
}
function SAVE() {
localStorage.setItem("XP", XP); console.log('XP', XP);
localStorage.setItem("killcount", KillCount); console.log("killcount" , KillCount)
}
function LOAD() {
var XP = localStorage.getItem("XP");
var KillCount = localStorage.getItem("killcount");
document.getElementById("XP").innerHTML = XP;
document.getElementById("KillCount").innerHTML = KillCount;
console.log("killcount", KillCount)
}
function killCount() {
if(XP % 25 === 0) {
KillCount++
document.getElementById("KillCount").innerHTML = KillCount;
}
function checkXP() {
var XP = checkXP("XP"); }
if (XP == "checkXP") {
XP = "checkXP"
setCookie("CheckXP", XP);
}
return parseInt(XP);
}
</script>
gs however I'm still at a loss since I'm new, can anyone give me some leads for this problem?
As stated in the comments I will formulate an answer.
If you want to use the globally defined counters (like the XP or killCount) even after you LOAD() then you have to overwrite the variables. This is possible if you access them from the LOAD() function. What you are doing is defining new local variables within the LOAD() context. For overriding the values within the globally defined variables, omit the var keyword from the variables XP and killCount and make sure, that the variable read out of the localContext gets parsed correctly as a number.
function LOAD() {
XP = parseInt(localStorage.getItem("XP"));
KillCount = localStorage.getItem("killcount");
document.getElementById("XP").innerHTML = XP;
document.getElementById("KillCount").innerHTML = KillCount;
console.log("killcount", KillCount)
}
This should bring you up to speed.