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