mirror of
https://github.com/jakejarvis/jarv.is.git
synced 2025-04-28 04:50:28 -04:00
74 lines
2.3 KiB
JavaScript
74 lines
2.3 KiB
JavaScript
/* jshint esversion: 6, indent: 2, browser: true, quotmark: single */
|
|
|
|
/*! Dark Mode Switcheroo | MIT License | jrvs.io/bWMz */
|
|
|
|
(function() {
|
|
'use strict';
|
|
|
|
// improve variable mangling
|
|
const win = window;
|
|
const doc = win.document;
|
|
const bod = doc.body;
|
|
const cls = bod.classList;
|
|
const sto = localStorage;
|
|
|
|
// check for preset `dark_mode_pref` in localStorage
|
|
const pref_key = 'dark_mode_pref';
|
|
let pref = sto.getItem(pref_key);
|
|
|
|
// keep track of current state (light by default)
|
|
let dark = false;
|
|
|
|
const activateDarkMode = function() {
|
|
cls.remove('light');
|
|
cls.add('dark');
|
|
dark = true;
|
|
};
|
|
|
|
const activateLightMode = function() {
|
|
cls.remove('dark');
|
|
cls.add('light');
|
|
dark = false;
|
|
};
|
|
|
|
// if user already explicitly toggled in the past, restore their preference.
|
|
if (pref === 'true') activateDarkMode();
|
|
if (pref === 'false') activateLightMode();
|
|
|
|
// user has never clicked the button, so go by their OS preference until/if they do so
|
|
if (!pref) {
|
|
// check for OS dark mode setting and switch accordingly
|
|
// https://gist.github.com/Gioni06/eb5b28343bcf5793a70f6703004cf333#file-darkmode-js-L47
|
|
if (win.matchMedia('(prefers-color-scheme: dark)').matches)
|
|
activateDarkMode();
|
|
else
|
|
activateLightMode();
|
|
|
|
// real-time switching if supported by OS/browser
|
|
// TODO: stop listening when the parent condition becomes false,
|
|
// right now these keep listening even if pref is set.
|
|
win.matchMedia('(prefers-color-scheme: dark)').addListener(function(e) { if (e.matches) activateDarkMode(); });
|
|
win.matchMedia('(prefers-color-scheme: light)').addListener(function(e) { if (e.matches) activateLightMode(); });
|
|
}
|
|
|
|
const toggle = doc.querySelector('.dark-mode-toggle');
|
|
|
|
// don't freak out if page happens not to have a toggle button
|
|
if (toggle) {
|
|
// lightbulb toggle re-appears now that we know user has JS enabled
|
|
toggle.style.visibility = 'visible';
|
|
|
|
// handle lightbulb click
|
|
toggle.addEventListener('click', function() {
|
|
// switch to the opposite theme & save preference in local storage
|
|
if (!dark) {
|
|
activateDarkMode();
|
|
sto.setItem(pref_key, 'true');
|
|
} else {
|
|
activateLightMode();
|
|
sto.setItem(pref_key, 'false');
|
|
}
|
|
}, true);
|
|
}
|
|
})();
|