1

so recently i've been having a problem with localStorage in JS. Every time i would press the button instead of adding 1 to var wood; the output would add 1 to the left side of the output each time i pressed the button, so if i pressed the button 3 times instead of wood = 3 it would equal 111 instead. please help.

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p id="output"></p>
<button onclick="collectWood()">collect wood</button>
<script>
var wood = +localStorage.getItem("woodSave");

document.getElementById('output').innerHTML = parseInt(wood);
localStorage.setItem("woodSave", wood);
if(wood >= 1000){
 replace = (wood / 1000).toFixed(2) + "k";
 wood = replace;
 document.getElementById('output').innerHTML = wood;
}
function collectWood() {
 wood = wood + 1;
 document.getElementById('output').innerHTML = wood;
}
</script>
</body>
</html>
Liam Sperry
  • 318
  • 2
  • 9

1 Answers1

0

Your issue is right here:

replace = (wood / 1000).toFixed(2) + "k";
wood = replace;

What's happening here is that when wood (a number) is greater than or equal to 1000, you do some math on the number and return a string and then take that string and reassign that back to your wood variable, so going forward, that's what gets stored and used. You should just take the result of that replace variable and inject it into the DOM, so the user sees the formatted output, but the internal value stays a number.

Also, the first time you run the code, there will be no value being stored, so you need to be prepared to initialize it.

Lastly, you need to move your output code into your button click.

Please see this Fiddle for a working version with comments.

Scott Marcus
  • 64,069
  • 6
  • 49
  • 71