Set default theme on initial load JS

Viewed 220

I'm trying to set the theme of my site to 'theme-dark-purple' if there's no previously set theme in localStorage (for new visitors). However, the code that I have now doesn't work, and I can't figure out why.

There are corresponding buttons with onclick functions to set each each theme, but I didn't include it here because the buttons work just fine and I don't want to add in code here that already works.

<script>
  // function to set a given theme/color-scheme
  function setTheme(themeName) {
    localStorage.setItem('theme', themeName);
    document.documentElement.className = themeName;
  }

  // Immediately invoked function to set the default theme as 'theme-dark-purple' if there's no set theme
  (function () {
    if (localStorage.getItem('theme') != 'theme-dark-purple', 'theme-light-purple', 'theme-dark-blue', 'theme-light-blue') {
      setTheme('theme-dark-purple');
    }
  })();
</script>
1 Answers

Actually your way of writing the condition is wrong. You can try this.

  (function () {
    const themes = ['theme-dark-purple', 'theme-light-purple', 'theme-dark-blue', 'theme-light-blue'];
    if (!themes.includes(localStorage.getItem('theme'))) {
      setTheme('theme-dark-purple');
    }
  })();
Related