Home > database >  save two opposite functions in local storage to apply selected theme - jQuery
save two opposite functions in local storage to apply selected theme - jQuery

Time:11-21

I have two functions do opposite actions, each one apply a theme when a button is clicked, how to save the theme or the data in this function in local storage? so that when the user reloads the page or change the page the selected theme still the one?

here is my code:

function orangeThemeActivation() {
    $("#orange-theme").removeAttr("disabled", "disabled");
    $(".to-green-blue-theme").attr(
      "style",
      "display: block !important; background: linear-gradient(to right, #14b0af 0%, #14b0af 50%, #004AAB 50%, #004AAB 100%); vertical-align:middle !important;"
    );
    $(this).attr("style", "display: none !important");
    $("body").addClass("orange-mode");
    $("body").removeClass("green-blue-mode");
    $("img[src*='/images/']").prop("src", (_index, oldURL) => {
      const url = new URL(oldURL);
      url.pathname = url.pathname.replace("/assets/images/", "/assets/orange/");
      return url;
    });
  }
  
  function greenBlueThemeActivation() {
    $("#orange-theme").attr("disabled", "disabled");
    $(".to-orange-theme").attr(
      "style",
      "display: block !important; background: orange !important; vertical-align:middle !important;"
    );
    $(this).attr("style", "display: none !important");
    $("body").addClass("green-blue-mode");
    $("body").removeClass("orange-mode");
    $("img[src*='/orange/']").prop("src", (_index, oldURL) => {
      const url = new URL(oldURL);
      url.pathname = url.pathname.replace("/assets/orange/", "/assets/images/");
      return url;
    });
  }
  
  $("#green-blue-color-changer").click(greenBlueThemeActivation);
  $("#orange-color-changer").click(orangeThemeActivation);

CodePudding user response:

  1. Let each function change the localStorage using setItem() when trigerred.

    Add localStorage.setItem('lastThemeApplied', 'orangeTheme') in orangeThemeActivation() function.
    
    Add localStorage.setItem('lastThemeApplied', 'greenBlueTheme') in greenBlueThemeActivation() function.
    
  2. Set the theme by triggering the function corresponding to the value from localStorage using getItem()

window.onLoad = () => {
  if (localStorage.getItem('lastThemeApplied') === 'orangeTheme') {
    orangeThemeActivation();
  } else if (localStorage.getItem('lastThemeApplied') === 'greenBlueTheme') {
    greenBlueThemeActivation();
  }
}
  • Related