From 9fad4b93e68d588559cfc898c0411b6665e063aa Mon Sep 17 00:00:00 2001 From: Dian Date: Sat, 24 Jul 2021 16:54:10 +0800 Subject: [PATCH] make dark as default theme When user visit at the first time, it will use dark theme. --- dark-mode-switch.js | 21 ++++++--------------- index.html | 6 +++--- 2 files changed, 9 insertions(+), 18 deletions(-) diff --git a/dark-mode-switch.js b/dark-mode-switch.js index 06edb2b..69a37ab 100644 --- a/dark-mode-switch.js +++ b/dark-mode-switch.js @@ -4,7 +4,7 @@ * Licensed under MIT (https://github.com/coliff/dark-mode-switch/blob/main/LICENSE) */ -var darkSwitch = document.getElementById("darkSwitch"); +const darkSwitch = document.getElementById("darkSwitch"); window.addEventListener("load", function () { if (darkSwitch) { initTheme(); @@ -26,13 +26,9 @@ window.addEventListener("load", function () { * @return {void} */ function initTheme() { - var darkThemeSelected = - localStorage.getItem("darkSwitch") !== null && - localStorage.getItem("darkSwitch") === "dark"; - darkSwitch.checked = darkThemeSelected; - darkThemeSelected - ? document.body.setAttribute("data-theme", "dark") - : document.body.removeAttribute("data-theme"); + const currentTheme = localStorage.getItem("darkSwitch") || document.body.getAttribute('data-theme'); + darkSwitch.checked = currentTheme === 'dark'; + document.body.setAttribute('data-theme', currentTheme); } /** @@ -42,11 +38,6 @@ function initTheme() { * @return {void} */ function resetTheme() { - if (darkSwitch.checked) { - document.body.setAttribute("data-theme", "dark"); - localStorage.setItem("darkSwitch", "dark"); - } else { - document.body.removeAttribute("data-theme"); - localStorage.removeItem("darkSwitch"); - } + document.body.setAttribute("data-theme", darkSwitch.checked ? "dark" : "light"); + localStorage.setItem("darkSwitch", darkSwitch.checked ? "dark" : "light"); } diff --git a/index.html b/index.html index 7b0056a..5e67b38 100644 --- a/index.html +++ b/index.html @@ -10,7 +10,7 @@ - + @@ -31,7 +31,7 @@ - +
@@ -45,7 +45,7 @@
- +