Skip to content

Commit 61e599d

Browse files
committed
WIP: Add a dark/light mode toggle
This button is pretty ugly at the moment. Could use some TLC by someone who actually knows what they're doing. Signed-off-by: Johannes Schindelin <[email protected]>
1 parent 599fe49 commit 61e599d

File tree

3 files changed

+46
-0
lines changed

3 files changed

+46
-0
lines changed

assets/js/application.js

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ const baseURLPrefix = (() => {
2929

3030
$(document).ready(function() {
3131
BrowserFallbacks.init();
32+
DarkMode.init();
3233
Search.init();
3334
Dropdowns.init();
3435
Forms.init();
@@ -541,6 +542,44 @@ var Downloads = {
541542
},
542543
}
543544

545+
var DarkMode = {
546+
init: function() {
547+
const button = $('#dark-mode-button');
548+
if (!button.length) return;
549+
550+
// Check for dark mode preference at the OS level
551+
const prefersDarkScheme = window.matchMedia("(prefers-color-scheme: dark)").matches;
552+
553+
// Get the user's theme preference from local storage, if it's available
554+
const currentTheme = localStorage.getItem("theme");
555+
556+
const body = $("body");
557+
if (prefersDarkScheme) {
558+
if (currentTheme === "light") {
559+
body.addClass("light-mode");
560+
} else {
561+
button.text("🌞");
562+
}
563+
} else if (currentTheme === "dark") {
564+
body.addClass("dark-mode");
565+
button.text("🌞");
566+
}
567+
568+
button.click(() => {
569+
let theme
570+
if (prefersDarkScheme) {
571+
body.toggleClass("light-mode");
572+
theme = body.hasClass("light-mode") ? "light" : "dark";
573+
} else {
574+
body.toggleClass("dark-mode");
575+
theme = body.hasClass("dark-mode") ? "dark" : "light";
576+
}
577+
localStorage.setItem("theme", theme);
578+
button.text(theme === "dark" ? "🌞" : "🌙");
579+
});
580+
},
581+
}
582+
544583
// Scroll to Top
545584
$('#scrollToTop').removeClass('no-js');
546585
$(window).scroll(function() {

assets/sass/dark-mode.css

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,4 +98,10 @@
9898
@media screen and (prefers-color-scheme: dark) {
9999
@include mode($mode: dark)
100100
@include mode($mode: light, $class: ".light-mode")
101+
}
102+
103+
#dark-mode-button {
104+
position: absolute;
105+
top: 10px;
106+
right: 305px;
101107
}

layouts/partials/header.html

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
document.getElementById('tagline').innerHTML = '--' + tagline;
1515
</script>
1616

17+
<a href="#" id="dark-mode-button" class="subtle-button" data-os="">🌙</a>
1718
{{ if ne (.Scratch.Get "section") "search" }}
1819
<form id="search" action="{{ relURL "search/results" }}">
1920
<input id="search-text" name="search" placeholder="Type / to search entire site…" autocomplete="off" type="text" />

0 commit comments

Comments
 (0)