Reputation: 5073
I found some nifty JavaScript that inverts the colors on my website and I found a way to persist the state using localStorage
.
Here is what the persisting logic looks like:
var isNight = localStorage['night'] || false;
if (isNight) {
// $html is shorthand for my jQuery selected <html> tag
$html.addClass('night');
else {
$html.removeClass('night');
}
// further down I have code that adjusts `localStorage` everytime my button is clicked, inverting the colors
This works, however it looks very clunky as you can clearly see the CSS change every time you refresh the page.
Is there a way to make the CSS stay how it was last changed? What I'm thinking I have to do is manually edit the CSS file through JavaScript so that when the page loads it is already in there, but I'm not sure how to approach this.
Upvotes: 2
Views: 33
Reputation: 78525
I assume this is all within a document.ready
if you're using jQuery. To get this to render before the user sees anything, conditionally add the class inside the head
element:
<html>
<head>
<!-- Make sure the CSS class is added first -->
<script>
var isNight = localStorage["night"] || false;
if(isNight) document.querySelector("html").className = "night";
</script>
<!-- Now load your stylesheet, jQuery & other scripts -->
<link rel="stylesheet" type="text/css" href="yourstyles.css">
</head>
<body>
</body>
</html>
Upvotes: 1