Skip to content
Advertisement

Local storage to change background colour

I am trying to change the background colour of my website with local storage. I am using onchange() within the HTML for the colours() function, and the rest is the JavaScript below

var bgcolour;

window.onload = function theme(){

    document.body.style.backgroundColor = "red";
    localStorage.setItem("bgcolour", 1);
}


function colours(){
    localStorage.bgcolour = document.getElementById("party").value;

    if (localStorage.bgcolour == '1'){
        document.body.style.backgroundColor = "red";
    }
}

It does nothing. It doesn’t even change, let alone store it as local storage.

I keep missing vital, small parts of code and it feels like I have done it again with this one.

Any help is greatly appreciated!

HTML:

 <select name="pnumber" id="party" onchange="colours()">
     <option value="1">1</option>
     <option value="2">2</option>
     <option value="3">3</option>
     <option value="4">4</option>
     <option value="5">5</option>
     <option value="6">6</option>
     <option value="7">7</option>
     <option value="8">8</option>
     <option value="9">9</option>
     <option value="10">10</option>
     <option value="11">11</option>
     <option value="12">12</option>
     <option value="13">13</option>
     <option value="14">14</option>
     <option value="15">15 (maximum)</option>
 </select>

Advertisement

Answer

the code is wrong, you are improperly setting and checking localStorage values. Also, you need to get the value from the node with id party.

var bgcolour;

window.onload = function theme(){

    document.body.style.backgroundColor = "red";
    localStorage.setItem("bgcolour", 1);
}

var party = document.getElementById('party')
function colours(){
 
    localStorage.setItem('bgcolour', party.value);

    if (localStorage.getItem('bgcolour') === '1'){
        document.body.style.backgroundColor = "red";
    }
  else{
    document.body.style.backgroundColor = "green";
  }
}
<select name="pnumber" id="party" onchange="colours()">
     <option value="1">1</option>
     <option value="2">2</option>
     <option value="3">3</option>
     <option value="4">4</option>
     <option value="5">5</option>
     <option value="6">6</option>
     <option value="7">7</option>
     <option value="8">8</option>
     <option value="9">9</option>
     <option value="10">10</option>
     <option value="11">11</option>
     <option value="12">12</option>
     <option value="13">13</option>
     <option value="14">14</option>
     <option value="15">15 (maximum)</option>
 </select>
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement