I implemented a theme toggle (light/dark mode) on my Astro.js project, and it works perfectly in production. However, in my local development environment, the toggle isn’t functioning. I’ve cleared the cache and checked for JavaScript errors, but the issue persists.
-
What could cause such behavior differences between production and development environments?
-
Could it be related to build settings, environment variables, or something else?
-
Project: Portfolio-cv
-
Production: camilooviedo.com/
ThemeToggle.js
document.addEventListener("DOMContentLoaded", () => {
// Get elements for both large and small screen theme toggle buttons
const themeToggleButton = document.getElementById("theme-toggle-btn");
const themeToggleButtonSm = document.getElementById("theme-toggle-btn-sm");
// Get elements for light and dark mode icons for both screen sizes
const lightModeIcon = document.getElementById("light-icon");
const darkModeIcon = document.getElementById("dark-icon");
const lightModeIconSm = document.getElementById("light-icon-sm");
const darkModeIconSm = document.getElementById("dark-icon-sm");
const applyTheme = (theme) => {
if (theme === "dark") {
document.documentElement.classList.add("dark");
localStorage.setItem("theme", "dark");
// Update icons for large screens
lightModeIcon.classList.add("hidden");
darkModeIcon.classList.remove("hidden");
// Update icons for small screens
lightModeIconSm.classList.add("hidden");
darkModeIconSm.classList.remove("hidden");
} else {
document.documentElement.classList.remove("dark");
localStorage.setItem("theme", "light");
// Update icons for large screens
darkModeIcon.classList.add("hidden");
lightModeIcon.classList.remove("hidden");
// Update icons for small screens
darkModeIconSm.classList.add("hidden");
lightModeIconSm.classList.remove("hidden");
}
};
const storedTheme = localStorage.getItem("theme");
const systemPrefersDark = window.matchMedia(
"(prefers-color-scheme: dark)"
).matches;
const themeToApply = storedTheme || (systemPrefersDark ? "dark" : "light");
// Apply the determined theme on page load
applyTheme(themeToApply);
// Add event listeners to toggle buttons to switch themes
themeToggleButton.addEventListener("click", () => {
const isCurrentlyDark = document.documentElement.classList.contains("dark");
const newTheme = isCurrentlyDark ? "light" : "dark";
applyTheme(newTheme);
});
themeToggleButtonSm.addEventListener("click", () => {
const isCurrentlyDark = document.documentElement.classList.contains("dark");
const newTheme = isCurrentlyDark ? "light" : "dark";
applyTheme(newTheme);
});
});
I expected to work in both environments: development & production