Maintain the dynamic CSS on switching tabs on page and on reload

Viewed 181

In my application, there is an option for the user to change the CSS of the page on click of a button. I want that the selected style should remain if the user visits another link on the page or if the page is reloaded, i.e. the user should not have to select the style/theme of choice again and again.

How can I achieve this ?

function switch_style (style){
 
    if(theme == "blue"){
        document.getElementById("test").setAttribute('style','color:blue');
    }
    else if(theme == "black"){
        document.getElementById("test").setAttribute('style','color:black');
    }
    
    }
     
<button type="button" class="btn btn-dark" onclick="switch_style('blue') id="blue">Blue</button>
     <button type="button" class="btn btn-dark" onclick="switch_style('black')id="black">Black</button>
     <p id="test">SAMPLE TEXT</p>


     

2 Answers

For storing value you need to add localStorage from browser. Here is details about it : https://www.w3schools.com/jsref/prop_win_localstorage.asp

Sample code you can use this :

function switch_style (style)
{

if(theme == "blue"){
    document.getElementById("test").setAttribute('style','color:blue');
}
else if(theme == "black"){
    document.getElementById("test").setAttribute('style','color:black');
}
localStorage.setItem("style_theme", theme);

}

and onload check for localstorage

var style_theme = localStorage.getItem("style_theme");
if(!style_theme){
style_theme = "blue" // set default theme which want to.
}
switch_style(style_theme);

Based on this you can call function.

Using Local Storage:

// tweaking switch_style to use local storage

function switch_style (theme) {
  // making switch_style update local staorage any time page theme is changed

  localStorage.setItem('currentThemeColor', theme);

  if(theme == "blue"){
  document.getElementById("test").setAttribute('style','color:blue');
  
  
  } else if (theme == "black") {
      document.getElementById("test").setAttribute('style','color:black');
 
  }

}

// for every page add an eventLister that runs after the page load to get the currentThemeColor from localStorage and apply it ont the current page...
// Example:

window.addEventListener("DOMContentLoaded", function () {
  // getting currentThemeColor from localStorage;
  const currentThemeColor = localStorage.getItem('currentThemeColor') || "blue"; // setting blue as fallball color if localStorage has no currentThemeColor
  
  // updating page theme
  switch_style(currentThemeColor);
})
Related