dark mode switch body class, automaticly switch dark mode

this first checks if the user has dark mdoe enabled add body tag class=dark

and it works with switch too. if “.dark-mode-switch” button or element whatever you want clicked it changes the dark mdoe states too.

browser localstorage saves the user data so it remembers the users preference as well..


// 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() {
  localStorage.darkMode = (localStorage.darkMode === "true") ? "false" : "true";

// Using DOMContentLoaded event to run the function after the DOM is fully parsed
document.addEventListener('DOMContentLoaded', function() {

  // Attach the click event listener for the theme toggle switch
  document.querySelector(".dark-mode-switch").addEventListener('click', toggleTheme);