Setting a variable in local storage

A game is currently being developed, and the idea is to score high, so when the current score is greater than the local memory, it is replaced:

localStorage.setItem('highScore', highScore);
var HighScore = localStorage.getItem('highScore');
if (HighScore == null || HighScore == "null") {
  HighScore = 0;
}

if (user.points > HighScore) {
  highScore = parseInt(HighScore);
}
return highScore 

Thanks guys,

+4
source share
3 answers

This should indicate the right direction.

// Get Item from LocalStorage or highScore === 0
var highScore = localStorage.getItem('highScore') || 0;

// If the user has more points than the currently stored high score then
if (user.points > highScore) {
  // Set the high score to the users' current points
  highScore = parseInt(user.points);
  // Store the high score
  localStorage.setItem('highScore', highScore);
}

// Return the high score
return highScore;
+11
source

Here is an example of what I think you are trying to achieve. Of course, this is just an example, not code written for you.

<button id="save10">Save 10</button>
<button id="save12">Save 12</button>

var highscore = 11,
    button10 = document.getElementById("save10"),
    button12 = document.getElementById("save12"),
    savedHighscore;

function saveData(x) {
    localStorage.setItem('highscore', x);
}

button10.addEventListener("click", function () {
    saveData(10);
}, false);

button12.addEventListener("click", function () {
    saveData(12);
}, false);

savedHighscore = parseInt(localStorage.getItem('highscore'), 10);
if (typeof savedHighscore === "number" && highscore <  savedHighscore) {
    highscore = savedHighscore;
}

alert("Highscore: " + highscore);

On jsfiddle

, , 10, 12. , ( ). 11, 11 12 .

+2

How can I permanently store a variable in local data. I make a game and I want it to store information (Potatoes and buildings). Here is a link to my game. applesnake.somee.com/clicker.html

0
source

All Articles