script.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. const toggleButton = document.getElementById('theme-toggle');
  2. const themeIcon = document.getElementById('theme-icon');
  3. const themeSound = document.getElementById('theme-sound');
  4. // Function to update the theme icon based on the current theme
  5. const updateThemeIcon = (isDarkMode) => {
  6. const themeMode = isDarkMode ? 'darkMode' : 'lightMode';
  7. const iconPath = themeIcon.querySelector('use').getAttribute('href').replace(/#.*$/, `#${themeMode}`);
  8. themeIcon.querySelector('use').setAttribute('href', iconPath);
  9. };
  10. // Function to update the theme based on the current mode
  11. const updateTheme = (isDarkMode) => {
  12. const theme = isDarkMode ? 'dark' : 'light';
  13. document.documentElement.setAttribute('data-theme', theme);
  14. updateThemeIcon(isDarkMode);
  15. };
  16. // Function to toggle the theme
  17. const toggleTheme = () => {
  18. const isDarkMode = toggleButton.checked;
  19. updateTheme(isDarkMode);
  20. themeSound.play();
  21. localStorage.setItem('theme', isDarkMode ? 'dark' : 'light');
  22. // Add transition class to body for smooth transition
  23. document.body.classList.add('theme-transition');
  24. setTimeout(() => {
  25. document.body.classList.remove('theme-transition');
  26. }, 300);
  27. };
  28. // Event listener for theme toggle
  29. toggleButton.addEventListener('change', toggleTheme);
  30. // Function to initialize the theme based on the stored preference
  31. const initializeTheme = () => {
  32. const storedTheme = localStorage.getItem('theme');
  33. const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
  34. const isDarkMode = storedTheme === 'dark' || (!storedTheme && prefersDark);
  35. toggleButton.checked = isDarkMode;
  36. updateTheme(isDarkMode);
  37. };
  38. // Initialize the theme
  39. initializeTheme();
  40. // Listen for changes in system preference
  41. window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', initializeTheme);