From bc49a79d00f19b5c394cf9b5fd6d5a1ab8cc5625 Mon Sep 17 00:00:00 2001 From: Matthew Holt Date: Wed, 31 May 2023 20:57:46 -0600 Subject: [PATCH] Avoid flash during color scheme change --- new/resources/js/common.js | 26 ++++++++++++++++---------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/new/resources/js/common.js b/new/resources/js/common.js index 34763d6..480b877 100644 --- a/new/resources/js/common.js +++ b/new/resources/js/common.js @@ -49,12 +49,12 @@ function cloneTemplate(tplSelector) { // return document.importNode(elem.content, true); } -ready(function() { - // on page load, immediately set the configured theme - setTheme(getTheme()); - -}); + + + + + // when the system theme changes, apply that to our site if system theme is configured window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', ({ matches }) => { @@ -74,11 +74,12 @@ function setTheme(theme) { theme = "system"; } localStorage.setItem("theme", theme); - $('#current-theme').innerText = theme; - if (theme == "system") { - theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? "dark" : "light"; + ready(function() { $('#current-theme').innerText = theme; }); + let lightOrDarkTheme = theme; + if (lightOrDarkTheme == "system") { + lightOrDarkTheme = window.matchMedia('(prefers-color-scheme: dark)').matches ? "dark" : "light"; } - applyTheme(theme); + applyTheme(lightOrDarkTheme); } // applyTheme simply adds or removes the 'dark' class to the HTML. @@ -121,4 +122,9 @@ on('mouseover', '.button', (e) => { setTimeout(function() { elem.remove(); }, 1000); -}); \ No newline at end of file +}); + + + +// immediately set the configured theme to avoid flash +setTheme(getTheme()); \ No newline at end of file