Hi I want to store a number when its value is 0
var count = 3;
var count2 = "0";
var count3;
var btn = document.getElementById("btn");
btn.onclick = function() {
count--;
btn.style.transform = "scale(2)";
setTimeout(function() {
btn.style.transform = "scale(1)";
}, 0005);
if(count === 0) {
/* I want to store the result here in manner that even when the page reload the number remains the same ( 0 in that case ) */
var zero = localStorage.getItem(count);
count3 = parseInt(count2);
localStorage.setItem( count , count3 );
}
}
#btn {
width : 300px;
height : 300px;
border : solid 2px red;
border-radius : 50%;
transition : .1s;
}
<button id="btn">Click me</button>
But I don't need to affect count3 to count since count is already set at 0 :( but I can't affect numbers ? I think there's only string in the 'key' for localStorage.
How I can do that ?
localStorage.setItem( count , count3 )
This is wrong. You should write
localStorage.setItem( "where" , value );
So instead of setting the item in the key equal to the variable count, you should set the value in key "count", which is a string. Otherwise, every time you change the integer count, you store the new value (count3) in a new place.
When you then reload the page, the integer count is then trying to fetch the stored information in key 3.
Also, count === 0 could as well be written as count == 0 so it doesn't check if count is an integer first, and instead accepts strings (and boolean, undefined and null).
EDIT: added snippet as example. I refactored the code so it's more readable, commented out localStorage so you can run the snippet on Stack Overflow, and I assumed that count can't get lower than 0.
As a bonus, I removed count2 and count3 while changing the setTimeout from 0.005 (5ms is minimum anyway) to 50ms (half of 0.1s that is in the transition).
var storedCount = getStoredCount();
const GOT_PREVIOUS_VALUE = storedCount != null;
var count = (GOT_PREVIOUS_VALUE) ? storedCount : 3;
var btn = document.getElementById("btn");
btn.onclick = changeCount;
function changeCount() {
if (count > 0) {
count--;
scaleButton();
storeCount();
console.log({count})
}
}
function scaleButton() {
btn.style.transform = "scale(2)";
setTimeout(function() {
btn.style.transform = "scale(1)";
}, 50);
}
function getStoredCount() {
return localStorage.getItem('count') ;
}
function storeCount() {
localStorage.setItem('count', count);
}
#btn {
width: 300px;
height: 300px;
border: solid 2px red;
border-radius: 50%;
transition: .1s;
}
<button id="btn">Click me</button>
The key for localstorage is to only use String. You can define a function to parse the key to any.... When the page reload, loacalStorage can't be cleared. So you can do it like var key = parse(localStorage.getitem(count)) in your defined function.