Deniz Altay Deniz Altay - 5 months ago 15
HTML Question

HTML5 Localstorage help needed

I'm fresh to JS and i was wondering how i could implement this scenario to my code.

Im creating a simple tapping game for android using html, css and js. Whenever my object gets clicked on, 10 points gets added to score. I need this score to saved locally. So when the game restarts the score is there loaded.


Here are the game code:



var score = 0;

$(document).ready(function() {
$("#menu").hide();
$("#bug").autoBounceOff(true);
$("#bug").moveTo(140);
$("#bug").speed(0.8);

//When bug is clicked on
$("#bug").click(function() {
score = score + 10;
$('#score').html('Points: ' + score + '') + 10;
});
})

function showMenu() {
$("#menu").show();
$("#bug").css("visibility", "hidden");
$("#bug").css("animation-play-state", "paused");
return;
}

function resume() {
$("#menu").hide();
$("#bug").css("visibility", "visible");
$("#bug").css("animation-play-state", "running");
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="header">
<div id="score">Points:</div>
<div id="menuheader" onclick="showMenu()">M</div>
</div>
<div id="menu">
<div id="start" onclick="resume()">resume</div>
</div>
<div id="bug"></div>
<div class="bottomwall"></div>
<div class="topwall"></div>
<div class="leftwall"></div>
<div class="rightwall"></div>





JSFiddle

Answer

basic localStorage usage.

When you starting your script, you can test if localStorage.score is already set with:

var score = 0;
if(!localStorage.score){
    localStorage.score = 0;
}
score = parseInt(localStorage.score);

then in your click event:

localStorage.score = score + 10