I have this code that is trying to retrieve data from localstorage. However, nothing happens at all when it is run and there are no console errors.
var score = localStorage.getItem('score') || 0;
function save() {
counter = localStorage.getItem('score', score)
}
<body onl oad="save()">
<p id="score">0</p>
<img src="popcat1.png" alt="Invalid" id="popcat1">
I don't know I'm doing wrong and I want the score not to reset on refresh. Please tell me if there is a better way.
CodePudding user response:
Local storage is not a complicated thing. There are only 4 basic operations.
Set data in localStorage:
localStorage.setItem('name', variable)
Get data from localStorage:
localStorage.getItem('name')
Remove from localStorage
localStorage.removeItem('name')
Remove all from localStorage
localStorage.clear()
In your code, you need to setItem first and than you can get the value.
CodePudding user response:
Just use setItem
on save rather than getItem
:
let score = localStorage.getItem('score') || 0
function save() {
localStorage.setItem('score', score)
// ^^^^^^^
}
For more information check out the MDN docs.