I have been trying to save user selection to localstorage but the code is not working. I want it to save the color the user selects to localstorage so that if the user changes or refreshes the page the background color stays there.
function change(list) {
var val=list.options[list.selectedIndex].value;
document.body.style.background=val;
}
$(function () {
$('#changer').change(function () {
localStorage.setItem('todoData', this.value);
});
if (localStorage.getItem('todoData')) {
$('#changer')
.val(localStorage.getItem('todoData'))
.trigger('change');
}
});
#pageFooter{
background-color: #F49080;
color: white;
text-align: right;
position: relative;
margin-top: -50px;
clear: both;
}
label{
font-size: 14px;
font-family: sans-serif;
color: white;
}
<footer id="pageFooter">
<label>Select Color</label>
<select id="changer" onchange="change(this)">
<option value="" selected disabled hidden> - - Select Color - -</option>
<option value="Black">Black</option>
<option value="#D48166">Orange</option>
<option value="DarkGreen">Dark Green</option>
<option value="#D6A3FB">Pink</option>
<option value="#003b49">Original</option>
</select>
</footer>
I change it. The ordery would be. On page load you have to check if soem value is already setted in the localStorage. If yes it will set the color for the body.
Then if the change Event Listener fired it will change the color and store the value in the localStorage.
Without jQuery working example:
if( localStorage.getItem('todoData') ) {
alert(localStorage.getItem('todoData'))
document.body.style.background = localStorage.getItem('todoData');
}
function change(list)
{
var val = list.options[list.selectedIndex].value;
document.body.style.background = val;
localStorage.setItem('todoData', this.value);
}
Update your code shown below:
function change(list){
var val=list.options[list.selectedIndex].value;
document.body.style.background=val;
}
And change it to:
function change(list) {
var val=list.options[list.selectedIndex].value;
var pageFooter = document.getElementById( "pageFooter");
pageFooter .style.backgroundColor = val;
}