Home > Blockchain >  How to use localStorage after using color picker to change --var of :root
How to use localStorage after using color picker to change --var of :root

Time:04-01

I just spent a whole afternoon on my problem, I am new to JavaScript and I want do something :

I want the user to be able to select and change the main-color in the page.

I added a color picker in my HTML with :

<input type="color" id="colorID" oninput="changeColor()">

Then I took this code on Internet :

// on input, get value and save it as 'storedValue'
function changeColor() {
  var userColor = document.getElementById('colorID').value;
  localStorage.setItem('storedValue', document.body.style.backgroundColor = userColor);
}

// if there is a value stored, update color picker and background color
if(localStorage.storedValue) {
  document.getElementById('colorID').value = localStorage.storedValue;
  document.body.style.backgroundColor      = localStorage.storedValue;
}

I want replace "document.body.style.backgroundColor" by my --main-color: #fff; of my :root. I tried a lot of things, replacing document.body by document.documentElement... Nothing wants to work !

CodePudding user response:

Yes, because read/writing in the local/session storage, need to be done with stringify/parse methods:

// on input, get value and save it as 'storedValue'
function changeColor() {
  var userColor = document.getElementById('colorID').value;
  localStorage.setItem('storedValue', JSON.stringify(userColor));
}

// if there is a value stored, update color picker and background color
if(localStorage.getItem('storedValue')) {
  const savedColor = JSON.parse(localStorage.getItem('storedValue'));
  document.getElementById('colorID').value = savedColor;
  document.body.style.backgroundColor      = savedColor;
}

CodePudding user response:

This is not the correct way to get the value from the local Storage:

function changeColor() {
      var userColor = document.getElementById('colorID').value;
localStorage.setItem('storedValue', document.body.style.backgroundColor = userColor);
}
    
    if(localStorage.storedValue) {
        document.getElementById('colorID').value = localStorage.storedValue;
        document.body.style.backgroundColor      = localStorage.storedValue;
    }

Correct way to to get the Stored value from the local Storage is:

 function changeColor() {
          var userColor = document.getElementById('colorID').value;
          document.body.style.backgroundColor=userColor;
          localStorage.setItem('storedValue', userColor);
        }
    
        if(localStorage.getItem("storedValue")) {
             let storedValue=localStorage.getItem("storedValue");
             document.getElementById('colorID').value = storedValue;
             document.body.style.backgroundColor      = storedValue;
            }
  • Related