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