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
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);
}
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);
}
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?
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.
if (score > parseInt(localStorage.getItem('highscore'), 10)) {
localStorage.setItem('highscore', score);
}
convert into int before comparing. its string