dark-theme.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. const DARK_THEME_CLASS = 'dark-theme';
  2. const LIGHT_THEME_CLASS = 'light-theme';
  3. const THEME_KEY = 'theme';
  4. function setDarkTheme() {
  5. document.body.classList.remove(LIGHT_THEME_CLASS);
  6. document.body.classList.add(DARK_THEME_CLASS);
  7. }
  8. function setLightTheme() {
  9. document.body.classList.remove(DARK_THEME_CLASS);
  10. document.body.classList.add(LIGHT_THEME_CLASS);
  11. }
  12. function toggleDarkTheme() {
  13. if (document.body.classList.contains(DARK_THEME_CLASS)) {
  14. setLightTheme();
  15. localStorage.setItem(THEME_KEY, 'light')
  16. } else {
  17. setDarkTheme();
  18. localStorage.setItem(THEME_KEY, 'dark')
  19. }
  20. }
  21. // enable dark theme as soon as possible so first paint is already dark mode
  22. (function () {
  23. window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', event => {
  24. if (localStorage.getItem(THEME_KEY) === null) {
  25. if (event.matches) {
  26. setDarkTheme();
  27. } else {
  28. setLightTheme();
  29. }
  30. }
  31. });
  32. if (localStorage.getItem(THEME_KEY) === 'dark') {
  33. setDarkTheme();
  34. } else if (localStorage.getItem(THEME_KEY) === 'light') {
  35. setLightTheme();
  36. } else if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
  37. setDarkTheme();
  38. } else {
  39. setLightTheme();
  40. }
  41. })();
  42. // handle theme button label and listener once DOM fully loaded
  43. window.addEventListener('DOMContentLoaded', function () {
  44. const isDarkTheme = document.body.classList.contains(DARK_THEME_CLASS)
  45. document.getElementById('dark-theme-button').addEventListener('click', toggleDarkTheme)
  46. })