How do I clear localStorage with a button?

3.9k Views Asked by At

I want to make a button, who clears the localstorage for a user. using localStorage.clear(); but it don't work.

If you look the demo, it don't work.

Demo

JS code:

var money = 0;

//localStorage function

if(localStorage.money) money = localStorage.getItem('money');
document.getElementById("money").innerHTML = money;

//Clicking function

function moneyClick(number){
    money = parseInt(money) + 10;
    document.getElementById ("money").innerHTML = money;
    localStorage.setItem('money', money);
}

//clear data function

function clearClick(number){
    localStorage.clear();
}
1

There are 1 best solutions below

0
On BEST ANSWER

Your code does clearlocalStorage, you need to refresh the page to see that though. In your code you can make it more clear by setting money to 0 and updating the DOM when you clear localStorage:

function clearClick(number){
    localStorage.clear();
    money = 0;
    document.getElementById ("money").innerHTML = money;
}