keeping changed color after refresh

409 views Asked by At

i'm trying to change my head and button color using this code

   <div class="ann-right">
    <button id="red" onclick="color1('#D91E18'), color2('#96281B')" class="tooltip color" title="Red"></button>
    <button id="green" onclick="color1('#3FC380'), color2('#00B16A')" class="tooltip color"title="Green" ></button>
    <button id="blue" onclick="color1('#5BBBFF'), color2('#22A7F0')" class="tooltip color" title="Blue"></button>
   </div>

  <script>
  function color1(col){
  document.getElementById("head").style.backgroundColor=col;
  }

  function color2(col){
  document.getElementById("submit-search").style.backgroundColor=col;
  document.getElementById("submit-post").style.backgroundColor=col;
  }
  </script>

How to keep the color after the page refreshed ?

1

There are 1 answers

3
Tha'er AlAjlouni ثائر العجلوني On BEST ANSWER

There are multiple options to implement the required behavior, one of which is to use sessionStorage. Save the selected color in sessionStorgae and read it on page load. Refer to the following for more info:

// Save data to sessionStorage
sessionStorage.setItem('key', 'value');

// Get saved data from sessionStorage
var data = sessionStorage.getItem('key');

// Remove saved data from sessionStorage
sessionStorage.removeItem('key');

// Remove all saved data from sessionStorage
sessionStorage.clear();

Update: For your case:

<div class="ann-right">
  <button id="red" onclick="color1('#D91E18'), color2('#96281B')" class="tooltip color" title="Red"></button>
  <button id="green" onclick="color1('#3FC380'), color2('#00B16A')" class="tooltip color" title="Green"></button>
  <button id="blue" onclick="color1('#5BBBFF'), color2('#22A7F0')" class="tooltip color" title="Blue"></button>
</div>

<script>
  function color1(col) {
    document.getElementById("head").style.backgroundColor = col;
    sessionStorage.setItem('col1', col);
  }

  function color2(col) {
    document.getElementById("submit-search").style.backgroundColor = col;
    document.getElementById("submit-post").style.backgroundColor = col;
    sessionStorage.setItem('col2', col);
  }

  color1(sessionStorage.getItem('col1'));
  color2(sessionStorage.getItem('col2'));
</script>