Hi im trying to find a way to use local storage to save a high score, i have a simple script that sets the score each time the user plays.
localStorage.score = $(".score").text();
$(".highscore").text(localStorage.score);
However I now want to expand on it and it only to update the score if its a new high score and also sets the date it was achieved. Thank you
CodePudding user response:
You need to know where you want to have your storage, in a separate storage item, or change it to an object and add values that will hold both the score and date.
Then when using localStorage, to insert a JS object correctly it has to be converted into JSON: JSON.stringify()
, then when retreiving just parse it: JSON.parse()
Here's a working example:
HTML:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >35</div>
<div ></div>
<div ></div>
JS:
$(function() {
let date = new Date();
localStorage.score =
localStorage.score ?
Number($(".score").text()) > JSON.parse(localStorage.score).score ?
JSON.stringify({
"score": $(".score").text(),
"date": `${date.toDateString()} at ${date.toLocaleTimeString()}`
})
: JSON.stringify({
"score": JSON.parse(localStorage.score).score,
"date": JSON.parse(localStorage.score).date
})
: JSON.stringify({
"score": $(".score").text(),
"date": `${date.toDateString()} at ${date.toLocaleTimeString()}`
})
$(".highscore").text(JSON.parse(localStorage.score).score);
$(".highscore-date").text(JSON.parse(localStorage.score).date);
});
This script checks whether the score item has been set in the localStorage first. If it exists, then first cast the score value into a Number
since it's being read as a string, then check wheter it's greater than the current value, and update accordingly
And here an object is used to hold both values for score and date in the same storage item