Show changed localStorage without refreshing page?

Viewed 827

I am working on something. But everytime I take away from the value, I have to refresh the page to show the new value.

localStorage.setItem("money", money - 20);

How do I make the value "money" refresh on the page without actually refreshing the page itself? Can it be done with pure JavaScript?

2 Answers

First things first, storing money in localStorage is not desirable. Users can easily change its value using developer tools. If you're using that value for caching, never trust that value in Backend.

Second, you have to update the value with custom function whenever you change the money and store it to localStorage. Like the following:

localStorage.setItem("money", money - 20);
document.getElementById("balance").innerText = localStorage.getItem("money") || 0;

localStorage is not supported in SO code snippet, so I'm going to post a full html here. You can just cut&paste and try to understand its logic.

Example:

<!DOCTYPE html>
<html>
<head>
   <title>Balance Example</title>
</head>
<body>
<div>Balance: $<span id="balance">0</span></div>
<button id="btnWithdraw" onClick="withdraw(20)">Withdraw 20$</button>
<button id="btnDeposit" onClick="deposit(100)">Deposit 100$</button>
</body>
<script>
   function getBalance() {
      let money = parseFloat(localStorage.getItem("money") || 0);
      return isNaN(money) ? 0 : money;
   }

   function setBalance(amount) {
      localStorage.setItem("money", parseFloat(amount));
   }

   function withdraw(amount) {
      let balance = getBalance();
      if(balance < amount) {
         return alert("Not enough balance!");
      } else {
         balance = balance - parseFloat(amount);
      }
      if (isNaN(balance)) balance = 0;
      setBalance(balance);
      renderBalance();
   }

   function deposit(amount) {
      amount = parseFloat(amount);
      if (isNaN(amount) || amount < 0) {
         return alert("Invalid amount!");
      }
      let balance = getBalance();
      balance += amount;
      setBalance(balance);
      renderBalance();
   }

   function renderBalance() {
      document.getElementById("balance").innerText = getBalance().toFixed(2);
   }

   window.onload = function() {
      renderBalance();
   }

</script>
</html>

After updating localStorage, use document.getElementById() to select the element on your page that displays the value of your money variable and update its content with .innerHTML:

localStorage.setItem("money", money - 20);
document.getElementById("money").innerHTML = money - 20;
The following Pen shows a working example of how to implement this. Show changed variable without reloading page on CodePen.

Related