Animated theme transitions powered by view transitions

Switching from dark to light modes can be dull and jittery , but a great way to make it look smoother can be adding animations

October 21, 2024
Gist
transition: all 0.3s ease;

but we can take this further by using the newly added view transitions

/* Angled */
[data-style="angled"]::view-transition-old(root) {
  animation: none;
  z-index: -1;
}

[data-style="angled"]::view-transition-new(root) {
  animation: unclip 1s;
  clip-path: polygon(-100vmax 100%, 100% 100%, 100% -100vmax);
}

@keyframes unclip {
  0% {
    clip-path: polygon(100% 100%, 100% 100%, 100% 100%);
  }
}

and trigger the animations using the view transitions

  function transitionColors() {
    if (typeof window !== "undefined") {
      try {
        document.startViewTransition(() => {
          const newTheme = theme === "light" ? "dark" : "light";
          document.documentElement.dataset.theme = newTheme;
          updateTheme(newTheme);
        });
      } catch (error) {
        const newTheme = theme === "light" ? "dark" : "light";
        document.documentElement.dataset.theme = newTheme;
        updateTheme(newTheme);
      }
    }
  }

📝 Note
Remember to add the data-theme and data-style attribute in the html element to make the changes visible