Reputation: 55
Would I be able to create a function that automatically runs when something is put into localstorage?
I tried to come up with something myself but it doesn't seem to work.
function () {
if (localStorage.value == ""){
//do nothing
}
else {
document.getElementById("test").innerHTML = "" + (localStorage.getItem("server")) + "" ;
}
}
Edit: This bit of code works, but it doesn't update itself, so if I enter a new value into localstorage, this code won't pick it up and will display the old value still.
if (localStorage.length == 0){
document.getElementById("test").innerHTML = "Please go back and enter your name.";
}
else {
document.getElementById("test").innerHTML = "" + (localStorage.getItem("server")) + "" ;
}
Upvotes: 0
Views: 865
Reputation: 55
I managed to use setInterval
to refresh itself.
if (localStorage.length == 0){
document.getElementById("test").innerHTML = "Please go back and enter your name.";
}
else {
var myVar = setInterval(function(){myTimer()}, 1000);
function myTimer() {
var nameprint = document.getElementById("test").innerHTML ="" + (localStorage.getItem("server")) + "";
}
}
Upvotes: 0
Reputation: 36511
If you wrote a wrapper around localStorage and used that instead set you could run a callback when a value is set
var storage = {
get: function(key){
return localStorage.getItem(key);
},
set: function(key, value, callback){
localStorage.setItem(key, value);
if(typeof(callback) === 'function'){
callback.call(null, value);
}
}
}
storage.set('user', "John Smith", function(value){
console.log("You set your username to %s", value);
});
Upvotes: 1
Reputation: 19915
This is the way to find out if localstorage is empty.
if (localStorage.length == 0){ ...
Upvotes: 0