theme.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. (function(){
  2. // Select the button
  3. const btnTheme = document.getElementById('theme');
  4. // Check for dark mode preference at the OS level
  5. const prefersDarkScheme = window.matchMedia('(prefers-color-scheme: dark)');
  6. // Get the user's theme preference from local storage, if it's available
  7. const currentTheme = localStorage.getItem('theme');
  8. // If the user's preference in localStorage is dark...
  9. if (currentTheme == 'dark') {
  10. // ...let's toggle the .dark-theme class on the body
  11. document.body.classList.toggle('dark-theme');
  12. // Otherwise, if the user's preference in localStorage is light...
  13. } else if (currentTheme == 'light') {
  14. // ...let's toggle the .light-theme class on the body
  15. document.body.classList.toggle('light-theme');
  16. }
  17. // Listen for a click on the button
  18. btnTheme.addEventListener('click', function() {
  19. // If the user's OS setting is dark and matches our .dark-theme class...
  20. if (prefersDarkScheme.matches) {
  21. // ...then toggle the light mode class
  22. document.body.classList.toggle('light-theme');
  23. // ...but use .dark-theme if the .light-theme class is already on the body,
  24. var theme = document.body.classList.contains('light-theme') ? 'light' : 'dark';
  25. } else {
  26. // Otherwise, let's do the same thing, but for .dark-theme
  27. document.body.classList.toggle('dark-theme');
  28. var theme = document.body.classList.contains('dark-theme') ? 'dark' : 'light';
  29. }
  30. // Finally, let's save the current preference to localStorage to keep using it
  31. localStorage.setItem('theme', theme);
  32. });
  33. })();