Skip to content

Commit

Permalink
Allow theme toggle based on user browser preference even when cookies…
Browse files Browse the repository at this point in the history
… are not allowed
  • Loading branch information
nathan-contino committed Dec 12, 2024
1 parent 7090b96 commit 933935d
Showing 1 changed file with 11 additions and 14 deletions.
25 changes: 11 additions & 14 deletions jekyll-assets/scripts/theme.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@ function toggleTheme() {
var theme = localStorage.getItem('theme');
// if the theme has never been set, or is light, set the theme to the dark symbol in local storage to change it
if (localStorage.getItem('theme') !== null && theme == '🌝' ) {
if (document.cookie.indexOf("cookiebanner_accepted") != -1) {
if (cookiePermission != -1) {
localStorage.setItem('theme', '🌚');
}
} else {
if (document.cookie.indexOf("cookiebanner_accepted") != -1) {
if (cookiePermission != -1) {
// otherwise, the theme is currently set to dark, so set the theme to the light symbol in local storage to change it
localStorage.setItem('theme', '🌝');
}
Expand All @@ -25,17 +25,14 @@ function toggleTheme() {
// from the site's perspective, we default to a dark theme, but toggle it to a light theme on load if the user doesn't ask for dark.
// why do this? To prevent an annoying light 'flash' for dark theme users. light theme users don't really notice or care if there's a dark anti-flash.
function initTheme() {
var cookiePermission = document.cookie.indexOf("cookiebanner_accepted");
if (document.cookie.indexOf("cookiebanner_accepted") != -1) {
// fetch the theme from local storage (if it exists)
var theme = localStorage.getItem('theme');
// if the theme has been set to light (null check to short circuit if not set)
if(theme !== null && theme === '🌝'
// if we can use matchMedia and the browser supports the dark color scheme
|| (window.matchMedia && !window.matchMedia('(prefers-color-scheme: dark)').matches)
&& theme !== '🌚') {
// toggles the theme from the default dark mode to the light version (which actually _shows_ by default to many users)
document.body.classList.toggle('light');
}
// fetch the theme from local storage (if it exists)
var theme = localStorage.getItem('theme');
// if the theme has been set to light (null check to short circuit if not set)
if(theme !== null && theme === '🌝'
// if we can use matchMedia and the browser supports the dark color scheme
|| (window.matchMedia && !window.matchMedia('(prefers-color-scheme: dark)').matches)
&& theme !== '🌚') {
// toggles the theme from the default dark mode to the light version (which actually _shows_ by default to many users)
document.body.classList.toggle('light');
}
}

0 comments on commit 933935d

Please sign in to comment.