Java Reference
In-Depth Information
Quiz Ninja Project
We're going to use the Web Storage API to store the high score of the game. This will be
stored locally even after the browser has been closed, so players can keep a record of their
best attempt and try to beat it. To do this, we first add an extra paragraph to the header to
show the high score. Add the following line between the score and timer paragraphs in
the <header> element in index.htm:
<p id="hiScore"></p>
Now we need to write a method of the Game.prototype object to update the high score.
Add the following to the end of the Game constructor function::
Game.prototype.hiScore = function() {
if(window.localStorage) {
// the value held in localStorage is initally null so
make it 0
var hi = localStorage.getItem("hiScore") || 0;
// check if the hi-score has been beaten and display a
if it has
if(this.score > hi || hi === 0) {
localStorage.setItem("hiScore", this.score);
return localStorage.getItem("hiScore");
This function checks to see if window.localStorage is supported first. If it is, it sets
a local variable called hiScore to the value that's stored inside the object under the key
hiScore . If a high score is yet to be set already, it will be null , so we'll initialize it to 0
in this case. Next, we check to see if the score that's provided as an argument to the func-
tion is bigger than the current high score that we just retrieved. If it is, we show a message
to congratulate the player, and also update the value stored in localStorage using the
setItem() method.
Search WWH ::

Custom Search