2

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.

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

2 Comments

Yes it's all in a document.ready, and I am using jQuery. With this method I can still see a split-second delay between the original white background and the black background form the night class.
@Zach That will be your browser background rather than the stylesheet background though. You'll get the same on any site.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.