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:
Let each function change the
localStorage
usingsetItem()
when trigerred.Add localStorage.setItem('lastThemeApplied', 'orangeTheme') in orangeThemeActivation() function. Add localStorage.setItem('lastThemeApplied', 'greenBlueTheme') in greenBlueThemeActivation() function.
Set the theme by triggering the function corresponding to the value from
localStorage
usinggetItem()
window.onLoad = () => {
if (localStorage.getItem('lastThemeApplied') === 'orangeTheme') {
orangeThemeActivation();
} else if (localStorage.getItem('lastThemeApplied') === 'greenBlueTheme') {
greenBlueThemeActivation();
}
}