saadeghi / theme-change

Change CSS theme with toggle, buttons or select using CSS custom properties and localStorage
https://codepen.io/saadeghi/pen/OJypbNM
MIT License
1.42k stars 46 forks source link

Theme Bug fix, Resets while using View Transitions and Cant change the theme! Astro (View Transitions) #47

Closed sahillangoo closed 9 months ago

sahillangoo commented 9 months ago

Im using Tailwind with dasiyUI and im using this script to change themes, but when i added View Transitions theme automatically changes to white theme and im not able to change the theme as well. Any Fixed or Workaround? Live Link:https://sahillangoo-github-io.vercel.app/blog TIA

<script is:inline>
    if (localStorage.getItem('theme') === null) {
        document.documentElement.setAttribute('data-theme', 'InfinityDark')
    } else document.documentElement.setAttribute('data-theme', localStorage.getItem('theme'))
</script>
<script>
    import { themeChange } from 'theme-change'
    themeChange()
</script>
saadeghi commented 9 months ago

Is this script in a hydrated component?

sahillangoo commented 9 months ago

The theme changer was working fine before but when i added View Transitions theme automatically changes to white; and Im not able to change the theme as well.

Tried this script now but now im not able to change theme

<script is:inline>
  function initTheme() {
    let theme = localStorage.getItem('theme');
    if (!theme) {
      document.documentElement.setAttribute('data-theme', 'InfinityDark');
      localStorage.setItem('theme', 'InfinityDark');
    } else {
      if (theme === 'InfinityDark') {
        document.documentElement.setAttribute('data-theme', 'InfinityDark');
      } else if (theme === 'InfinityLight') {
        document.documentElement.setAttribute('data-theme', 'InfinityLight');
      } else if (theme === 'InfinityReading') {
        document.documentElement.setAttribute('data-theme', 'InfinityReading');
      }
    }
  }

  initTheme();

  document.addEventListener('astro:after-swap', initTheme);
</script>
<script>
  import { themeChange } from 'theme-change'
  themeChange()
</script>
sahillangoo commented 9 months ago

Update Finally Found the Fix ✅ ! How to fix: update your scripts as per this! https://docs.astro.build/en/tutorials/add-view-transitions/#update-scripts For Fixing theme change buttons use:

<nav transition:persist ...

Thanks to Jeff from fireship.io 🔥, https://www.youtube.com/watch?v=lsXqparnx24