I have a button which change background color and title color
button id="change" onclick="change()">Change background!</button>
var state = true;
function change(){
if (state){
document.body.style.backgroundColor = "red";
document.getElementById('title').style.color='blue';
} else {
document.body.style.backgroundColor = "#005fff";
document.getElementById('title').style.color='lightgreen';
}
state = !state;
}
I use state to choose between one and second option, if you have better solutions pls tell me.
I want to save the setting in localstorage(after refresh and quit i want to stay the background which was chosen).
U have to update the localStorage with ur own defined key, ichose bgcolor for that in the example.
Also when the script is loaded u should apply the bgcolor on the document body, asigning the value u get from the localStorage.
If no value was found, i set the background on white. this is optional of course :)
var state = true;
document.body.style.backgroundColor = localStorage.getItem('bgcolor') || 'white';
function change(){
if (state){
document.body.style.backgroundColor = "red";
document.getElementById('title').style.color='blue';
localStorage.setItem('bgcolor', 'red');
} else {
document.body.style.backgroundColor = "#005fff";
document.getElementById('title').style.color='lightgreen';
localStorage.setItem('bgcolor', '#005fff');
}
state = !state;
}
<h1 id="title">Title</h1>
<button id="change" onclick="change()">Change background!</button>
You could store the current color in local storage like this:
function change(){
const colorOption = localStorage.getItem('colorOption');
if (colorOption === "2"){
document.body.style.backgroundColor = "red";
document.getElementById('title').style.color='blue';
localStorage.setItem('colorOption', '1');
} else {
document.body.style.backgroundColor = "#005fff";
document.getElementById('title').style.color='lightgreen';
localStorage.setItem('colorOption', '2');
}
}