Bind localStorage variable to element in pageload

I want to bind (attach maybe?) A variable stored in localStorage to an element (like <p>

, <span>

or maybe <div>

)) on page load, and if the variable is not set, display the default.

How should I do it?

+3


source to share


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


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







All Articles