From d369ed6fc9c5da47d96a102b7a5ea8d1e9a363a9 Mon Sep 17 00:00:00 2001 From: Sayyad Aslam Date: Fri, 7 Jun 2024 21:49:42 +0530 Subject: [PATCH] Resolved Dark Mode Toggle --- Theme.js | 34 ++++++++++++++++++++++------------ 1 file changed, 22 insertions(+), 12 deletions(-) diff --git a/Theme.js b/Theme.js index c6c851d6..1332ee21 100644 --- a/Theme.js +++ b/Theme.js @@ -16,18 +16,28 @@ const themeToggle = document.getElementById("themeToggle"); const themeLabel = document.querySelector(".toggle-label"); -themeToggle.addEventListener("change", () => { - document.body.classList.toggle("dark-theme"); - - if (document.body.classList.contains("dark-theme")) { - themeLabel.style.background = "#fff"; // Adjust color for the checked state as needed - console.log("Dark theme"); - document.body.classList.remove("dark-theme"); - document.body.classList.add("light-theme"); - } else { - themeLabel.style.background = "var(--primary-color)"; // Adjust color for the unchecked state as needed - console.log("Light theme"); - document.body.classList.remove("light-theme"); +function applyTheme(theme) { + if (theme === "dark") { document.body.classList.add("dark-theme"); + document.body.classList.remove("light-theme"); + themeLabel.style.background = "var(--primary-color)"; + themeToggle.checked = true; + } else { + document.body.classList.add("light-theme"); + document.body.classList.remove("dark-theme"); + themeLabel.style.background = "#fff"; + themeToggle.checked = false; } +} + +document.addEventListener("DOMContentLoaded", () => { + const savedTheme = localStorage.getItem("theme") || "light"; + applyTheme(savedTheme); }); + +themeToggle.addEventListener("change", () => { + const theme = themeToggle.checked ? "dark" : "light"; + localStorage.setItem("theme", theme); + applyTheme(theme); +}); +