Issue
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 !
Solution
Try this:
//Call an invoked function that will run immedietly after the page loads
(function(){
if(localStorage.getItem("storedValue")){
document.getElementById('colorID').value = localStorage.storedValue;
document.querySelector(':root').style.setProperty('--main-color', userColor) = localStorage.storedValue;
})();
// on input, get value and save it as 'storedValue'
function changeColor() {
var userColor = document.getElementById('colorID').value;
localStorage.setItem('storedValue', document.querySelector(':root').style.setProperty('--main-color', userColor));
}
// if there is a value stored, update color picker and background color
if(localStorage.storedValue) {
document.getElementById('colorID').value = localStorage.storedValue;
document.querySelector(':root').style.setProperty('--main-color', userColor) = localStorage.storedValue;
}
Answered By - Aniket Lodh
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.