1
mirror of https://github.com/jakejarvis/dark-mode.git synced 2025-04-26 05:15:23 -04:00

a bit more cleanup

This commit is contained in:
Jake Jarvis 2021-08-04 15:34:22 -04:00
parent e4d7e4f61b
commit a91d67cfeb
Signed by: jake
GPG Key ID: 2B0C9CF251E69A39

View File

@ -9,9 +9,8 @@ const initializeDarkMode = function (options) {
// check for preset `dark_mode_pref` preference in local storage // check for preset `dark_mode_pref` preference in local storage
const storageKey = options.storageKey || "dark_mode_pref"; const storageKey = options.storageKey || "dark_mode_pref";
const storageEnabled = storageAvailable("localStorage"); const storageAvailable = isStorageAvailable();
// eslint-disable-next-line prettier/prettier const pref = storageAvailable ? localStorage.getItem(storageKey) : null;
const pref = storageEnabled ? localStorage.getItem(storageKey) : null;
// change CSS via these <body> classes: // change CSS via these <body> classes:
const dark = options.classes ? options.classes.dark : "dark"; const dark = options.classes ? options.classes.dark : "dark";
@ -24,12 +23,12 @@ const initializeDarkMode = function (options) {
let active = defaultTheme === dark; let active = defaultTheme === dark;
// receives a class name and switches <body> to it // receives a class name and switches <body> to it
const activateTheme = function (theme, remember = false) { const activateTheme = function (theme, remember) {
document.body.classList.remove(dark, light); document.body.classList.remove(dark, light);
document.body.classList.add(theme); document.body.classList.add(theme);
active = theme === dark; active = theme === dark;
if (storageEnabled && remember) { if (storageAvailable && !!remember) {
localStorage.setItem(storageKey, theme); localStorage.setItem(storageKey, theme);
} }
}; };
@ -90,9 +89,9 @@ const initializeDarkMode = function (options) {
// recommended method (by MDN) to detect localStorage availability: // recommended method (by MDN) to detect localStorage availability:
// https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API#feature-detecting_localstorage // https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API#feature-detecting_localstorage
const storageAvailable = function (type) { const isStorageAvailable = function () {
try { try {
var storage = window[type]; var storage = window["localStorage"];
var x = "__storage_test__"; var x = "__storage_test__";
storage.setItem(x, x); storage.setItem(x, x);
storage.removeItem(x); storage.removeItem(x);