Reputation: 421
I want to bind (attach, maybe?) a variable stored in localStorage to an element (e.g. <p>
, <span>
, or maybe <div>
) on page load and if the variable is not set, display a default value.
How do I go about this?
Upvotes: 2
Views: 86
Reputation: 386
You could 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;
});
}());
Upvotes: 1
Reputation: 1769
Assuming you know how to grab the localStorage variable, I'd 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?
}
Upvotes: 0