this first checks if the user has dark mode enabled if yes adds body class=dark
it works with switch too.
create your button if “.dark-mode-switch” button or element clicked it changes the dark mode state.
browser localstorage saves the user data so it remembers the users preference as well.
<script> // Function to detect if the user's system prefers dark mode function systemPrefersDark() { return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches; } // Function to set the theme based on local storage or user's system preference function setThemeFromLocalStorageOrSystemPreference() { // If darkMode exists in localStorage, use that. Otherwise, use system preference. const darkModeFromLocalStorage = localStorage.getItem('darkMode'); let isDarkMode; if (darkModeFromLocalStorage !== null) { isDarkMode = darkModeFromLocalStorage === "true"; } else { isDarkMode = systemPrefersDark(); localStorage.setItem('darkMode', isDarkMode ? "true" : "false"); } document.body.classList.add(isDarkMode ? 'dark' : 'light'); } // Function to toggle between dark and light mode function toggleTheme() { document.body.classList.toggle('dark'); document.body.classList.toggle('light'); localStorage.darkMode = (localStorage.darkMode === "true") ? "false" : "true"; } // Using DOMContentLoaded event to run the function after the DOM is fully parsed document.addEventListener('DOMContentLoaded', function() { setThemeFromLocalStorageOrSystemPreference(); // Attach the click event listener for the theme toggle switch document.querySelector(".dark-mode-switch").addEventListener('click', toggleTheme); }); </script>