Add dark mode toggle

This commit is contained in:
Harrison Sand 2021-09-24 19:38:28 +02:00
parent 5321e4817f
commit 8e4cb8c738
3 changed files with 29 additions and 2 deletions

View File

@ -6,5 +6,9 @@
{{ range .Site.Menus.main }} {{ range .Site.Menus.main }}
<a href="{{ .URL }}">{{ .Name }}</a> <a href="{{ .URL }}">{{ .Name }}</a>
{{ end }} {{ end }}
{{ if eq .Site.Params.mode "toggle" -}}
| <a id="dark-mode-toggle" onclick="toggleTheme()" href=""></a>
<script src="{{ .Site.BaseURL }}js/themetoggle.js"></script>
{{ end }}
</nav> </nav>
</header> </header>

View File

@ -39,9 +39,9 @@
{{ $style := resources.Get "css/main.css" | fingerprint }} {{ $style := resources.Get "css/main.css" | fingerprint }}
<link rel="stylesheet" type="text/css" media="screen" href="{{ $style.Permalink }}" /> <link rel="stylesheet" type="text/css" media="screen" href="{{ $style.Permalink }}" />
{{- if or (eq .Site.Params.mode "auto") (eq .Site.Params.mode "dark") -}} {{- if or (eq .Site.Params.mode "auto") (eq .Site.Params.mode "dark") (eq .Site.Params.mode "toggle") -}}
{{ $darkstyle := resources.Get "css/dark.css" | fingerprint }} {{ $darkstyle := resources.Get "css/dark.css" | fingerprint }}
<link rel="stylesheet" type="text/css" href="{{ $darkstyle.Permalink }}" {{ if eq .Site.Params.mode "auto" }}media="(prefers-color-scheme: dark)"{{ end }} /> <link id="darkModeStyle" rel="stylesheet" type="text/css" href="{{ $darkstyle.Permalink }}" {{ if eq .Site.Params.mode "auto" }}media="(prefers-color-scheme: dark)"{{ end }} {{ if eq .Site.Params.mode "toggle" }}disabled{{ end }} />
{{ end }} {{ end }}
<!-- Custom CSS style get applied last --> <!-- Custom CSS style get applied last -->

23
static/js/themetoggle.js Normal file
View File

@ -0,0 +1,23 @@
function setTheme(mode) {
localStorage.setItem("theme-storage", mode);
if (mode === "dark") {
document.getElementById("darkModeStyle").disabled=false;
document.getElementById("dark-mode-toggle").innerHTML = "<i data-feather=\"sun\"></i>";
feather.replace()
} else if (mode === "light") {
document.getElementById("darkModeStyle").disabled=true;
document.getElementById("dark-mode-toggle").innerHTML = "<i data-feather=\"moon\"></i>";
feather.replace()
}
}
function toggleTheme() {
if (localStorage.getItem("theme-storage") === "light") {
setTheme("dark");
} else if (localStorage.getItem("theme-storage") === "dark") {
setTheme("light");
}
}
var savedTheme = localStorage.getItem("theme-storage") || "light";
setTheme(savedTheme);