Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a html page with two CSS files - one for a light theme and one for a dark theme. When I click the respective button, the theme changes to either light.css or dark.css.

However, whenever I refresh the page, reload the page, go back etc. It changes back to the default css (being the light.css file).

Is there any way I can get it to stay on the dark.css theme when I click the button and refresh the page?

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
772 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can use a cookie, localStorage or sessionStorage where you keep the default theme and the choosen one. So when your page loads you have to read that info from cookie/localStorage/sessionStorage and to apply the chosen theme.

e.g when page is loading

let theme = localStorage.getElement('theme');
if(!theme){
theme = 'light';
localStorage.setElement('theme', 'light');
}
// and you use theme variable to load the light theme

e.g when the user changes the theme

localStorage.setElement('theme', 'dark');
theme = 'dark';

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...