js.html 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <!-- js from https://codepen.io/MrGrigri/pen/XQmWBv -->
  2. <script>
  3. // @license magnet:?xt=urn:btih:d3d9a9a6595521f9666a5e94cc830dab83b65699&dn=expat.txt Expat
  4. const themePreference = () => {
  5. const hasLocalStorage = localStorage.getItem('theme');
  6. let supports = false;
  7. let theme = undefined;
  8. if (hasLocalStorage === 'light') {
  9. theme = 'light';
  10. }
  11. if (hasLocalStorage === 'dark') {
  12. theme = 'dark';
  13. }
  14. if (window.matchMedia(`(prefers_color: dark)`).matches) {
  15. theme = hasLocalStorage ? hasLocalStorage : 'dark';
  16. supports = true;
  17. };
  18. if (window.matchMedia(`(prefers_color: light)`).matches) {
  19. theme = hasLocalStorage ? hasLocalStorage : 'light';
  20. supports = true;
  21. };
  22. if (window.matchMedia(`(prefers_color: no-preference)`).matches) {
  23. theme = hasLocalStorage ? hasLocalStorage : 'none';
  24. supports = true;
  25. };
  26. return {
  27. supports,
  28. theme
  29. };
  30. }
  31. document.addEventListener('DOMContentLoaded', e => {
  32. console.clear();
  33. const userThemePreference = themePreference();
  34. const toggle = document.querySelector('[theme_toggle]');
  35. const html = document.documentElement;
  36. const setTheme = () => {
  37. switch (userThemePreference.theme) {
  38. case 'dark':
  39. toggle.checked = true;
  40. html.classList.add('dark');
  41. html.classList.remove('light');
  42. break;
  43. case 'light':
  44. toggle.checked = false;
  45. html.classList.remove('dark');
  46. html.classList.add('light');
  47. break;
  48. }
  49. }
  50. setTheme();
  51. toggle.addEventListener('click', e => {
  52. if (toggle.checked) {
  53. html.classList.add('dark');
  54. html.classList.remove('light');
  55. localStorage.setItem('theme', 'dark');
  56. } else {
  57. html.classList.remove('dark');
  58. html.classList.add('light');
  59. localStorage.setItem('theme', 'light');
  60. }
  61. }, false);
  62. }, false);
  63. // @license-end
  64. </script>