Bind localStorage variable to element in pageload
2 answers
You can try this:
(function () {
var MY_VALUE_DEFAULT = 'MY_VALUE_DEFAULT',
myValue = localStorage.getItem('myValue') || MY_VALUE_DEFAULT;
document.addEventListener('DOMContentLoaded', function (e) {
var myDisplayElement = document.getElementById('displayElement');
myDisplayElement.innerText = myValue;
});
}());
+1
source to share
Assuming you know how to grab the localStorage variable, I would do the following:
window.addEventListener('load', function () {
var lsVar = /*do your magic here (i.e. check for localstorage and grab the data or null*/;
var myDiv = document.getElementByWhatever(); // Id?
// if lsVar is undefined, null, 0, false or empty string, set your default value
lsVar = lsVar || "My default value";
myDiv.innerHTML = lsVar; // or text?
}
0
source to share