Search code examples
javascripthtmlcssweb-storage

Using webStorage to apply CSS by Toggling Class


I have a site with 2 button I'm using to toggle between [default] Dark and Light theme. I'm doing this using the :root directive, and CSS variables, like so:

HTML:

<body>
  <div>
    Here is some text
  </div>

  <br/>

  <button type="button" onclick="lightToggle()">Light Theme</button>
  <button type="button" onclick="darkToggle()">Dark Theme</button>

</body>

CSS:

:root {
    --bg-color-1: #011627;
}

.light {
    --bg-color-1: #fbfbfb;
}

body {
    background-color: var(--bg-color-1);
}

JS:

function lightToggle() {
    var element = document.body;
    element.classList.add("light");
}

function darkToggle() {
    var element = document.body;
    element.classList.remove("light");
}

This works well for single pages. Now, I would like to have the theme persist when navigating to another webpage within the same domain. I don't want to use cookies, and I don't want to store persistent data on the client side, so I figured sessionStorage is most appropriate for this. I've added setItem in my HTML and JS, but am having difficulty toggling the light class using this sessionStorage value (and I'm not even sure this is best practice when using webStorage?). Here is where I'm starting from:

HTML:

<script>
  sessionStorage.setItem("theme", "dark");

</script>

<body>
  <div>
    Here is some text
  </div>
  <br />
  <button type="button" onclick="lightToggle()">Light Theme</button>

  <button type="button" onclick="darkToggle()">Dark Theme</button>

</body>

CSS (unchaged):

:root {
    --bg-color-1: #011627;
}

.light {
    --bg-color-1: #fbfbfb;
}

body {
    background-color: var(--bg-color-1);
}

JS:

function lightToggle() {
    var element = document.body;
    element.classList.add("light");

    sessionStorage.setItem("theme", "light");
}

function darkToggle() {
    var element = document.body;
    element.classList.remove("light");

    sessionStorage.setItem("theme", "dark");
}

What's the best practice for using webStorage to apply a class to the HTML body?


Solution

  • Everything is fine except for the script that is embedded in html. It will always override your selected theme with 'dark' value. So just change this script to read the current value in session storage and apply the appropriate class.

        <script>
          var theme = sessionStorage.getItem("theme");
          var element = document.body;
          
          if(theme && theme === 'light'){
            element.classList.add("light");
          }
          else{
            element.classList.remove("light");
          }
        </script>