Home > Enterprise >  Save user selected color to localstorage
Save user selected color to localstorage

Time:01-10

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

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>

color stays there

CodePudding user response:

function change(list)
            {
                var val=list.options[list.selectedIndex].value;
                document.body.style.background=val;
                
            }
Change to:
function change(list) {
   var val=list.options[list.selectedIndex].value;
   var pageFooter = document.getElementById( "pageFooter");
   pageFooter .style.backgroundColor = val;
}

CodePudding user response:

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') ) {
  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);  
}

  •  Tags:  
  • Related