Skip to content Skip to sidebar Skip to footer

Adding A High Score To Local Storage

I want to add a high score to my game. Right now I have this: var score = 0; var highscore = 0; The score variable works but whenever I get like points so total of 60 points it sa

Solution 1:

Try this:

var score = 0;
var highscore = localStorage.getItem("highscore");

if(highscore !== null){
    if (score > highscore) {
        localStorage.setItem("highscore", score);      
    }
}
else{
    localStorage.setItem("highscore", score);
}

Solution 2:

In addition to the parseInt, you need to set the init value on the localStorage first because localStorage.getItem("highscore",10) doesn't returns 10 as default value if is not setted

var score = 0;
var highscore = 0;
localStorage.setItem("highscore",0);

Because when you check

if (score > parseInt(localStorage.getItem("highscore"))) {
  localStorage.setItem("highscore", score);
}

The localStorage.getItem("highscore") will return null if the item is not setted yet. Or you can also do:

var storagedHighScore = localStorage.getItem("highscore");
if (storagedHighScore  || score > parseInt(storagedHighScore)) {
  localStorage.setItem("highscore", score);
}

Solution 3:

You need to retrieve the value from localStorage with

highscore = +localStorage.getItem("highscore")

or some equivalent code. Items in localStorage don't track the global variables with the same names.

Solution 4:

if (score > parseInt(localStorage.getItem('highscore'), 10)) {
  localStorage.setItem('highscore', score);
}

convert into int before comparing. its string

Solution 5:

I just reviewed your code in http://jsfiddle.net/unb8yLj3/ and i couldn't find in what part you increase the score so when this part of code run score is 0 and localStorage.getItem("highscore") is 10 therefore it doesn't set highscore.

if (score > localStorage.getItem("highscore")) {
                localStorage.setItem("highscore", score);

            }

  }

Is there another js file that does increase the score?

Post a Comment for "Adding A High Score To Local Storage"