dark-theme.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. const DARK_THEME_CLASS = 'dark-theme';
  2. const LIGHT_THEME_CLASS = 'light-theme';
  3. const DARK_THEME_KEY = 'startInDarkTheme';
  4. function setDarkTheme() {
  5. document.body.classList.remove(LIGHT_THEME_CLASS);
  6. document.body.classList.add(DARK_THEME_CLASS);
  7. setThemeButtonText("Light Theme");
  8. }
  9. function setLightTheme() {
  10. document.body.classList.remove(DARK_THEME_CLASS);
  11. document.body.classList.add(LIGHT_THEME_CLASS);
  12. setThemeButtonText("Dark Theme");
  13. }
  14. function toggleDarkTheme() {
  15. if (document.body.classList.contains(DARK_THEME_CLASS)) {
  16. setLightTheme();
  17. localStorage.setItem(DARK_THEME_KEY, 'false')
  18. } else {
  19. setDarkTheme();
  20. localStorage.setItem(DARK_THEME_KEY, 'true')
  21. }
  22. }
  23. /**
  24. * Safely modify theme button text only if it exists
  25. * @param {string} text label for button
  26. */
  27. function setThemeButtonText(text) {
  28. const button = document.getElementById('dark-theme-button')
  29. if (button) {
  30. button.innerHTML = text
  31. }
  32. }
  33. // enable dark theme as soon as possible so first paint is already dark mode
  34. (function () {
  35. window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', event => {
  36. if (localStorage.getItem(DARK_THEME_KEY) === null) {
  37. if (event.matches) {
  38. setDarkTheme();
  39. } else {
  40. setLightTheme();
  41. }
  42. }
  43. });
  44. if (localStorage.getItem(DARK_THEME_KEY) === 'true' || window.matchMedia('(prefers-color-scheme: dark)').matches) {
  45. setDarkTheme();
  46. }
  47. })();
  48. // handle theme button label and listener once DOM fully loaded
  49. window.addEventListener('DOMContentLoaded', function () {
  50. const isDarkTheme = document.body.classList.contains(DARK_THEME_CLASS)
  51. setThemeButtonText(isDarkTheme ? "Light Theme" : "Dark Theme")
  52. document.getElementById('dark-theme-button').addEventListener('click', toggleDarkTheme)
  53. })