From 538db8ec575b0d61514e9eb57496c9034c79fbd3 Mon Sep 17 00:00:00 2001 From: Francis Lavoie Date: Sat, 4 Apr 2020 19:19:25 -0400 Subject: [PATCH] Add JS to reset the toggle if the system theme changes when page closed --- src/resources/js/common.js | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/src/resources/js/common.js b/src/resources/js/common.js index 995d20a..511c444 100644 --- a/src/resources/js/common.js +++ b/src/resources/js/common.js @@ -1,3 +1,21 @@ +// We want to run this as early as possible +(function() { + // Grab the cached preferred color scheme + let cachedPref = localStorage.getItem('prefers-color-scheme'); + + // Grab the current preferred color scheme + let currentPref = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'; + + // If the preferred color scheme has changed since last page load + if (cachedPref !== currentPref) { + // We clear the toggle's value so it doesn't override the system choice + localStorage.removeItem('dark-mode-toggle'); + } + + // Set the preferred color scheme so it can be checked on a future page load + localStorage.setItem('prefers-color-scheme', currentPref); +})(); + document.addEventListener('DOMContentLoaded', function() { // Algolia search docsearch({