-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Fix and simplify logic for theme switching (#7)
- Loading branch information
rpmcfong
authored
Feb 3, 2022
1 parent
c761eab
commit 44c6f45
Showing
1 changed file
with
9 additions
and
22 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,31 +1,18 @@ | ||
/* global localStorage */ | ||
;(function () { | ||
'use strict' | ||
const systemInitiatedDark = window.matchMedia('(prefers-color-scheme: dark)') | ||
if (systemInitiatedDark.matches) { | ||
document.documentElement.setAttribute('data-theme', 'dark') | ||
let theme = localStorage.getItem('theme') | ||
if (theme === null) { | ||
const systemDark = window.matchMedia('(prefers-color-scheme: dark)').matches | ||
theme = systemDark ? 'dark' : 'light' | ||
} | ||
document.addEventListener('DOMContentLoaded', function () { | ||
if (systemInitiatedDark.matches) { | ||
document.documentElement.setAttribute('data-theme', 'dark') | ||
} | ||
}) | ||
document.documentElement.setAttribute('data-theme', theme) | ||
|
||
const switchButton = document.getElementById('themeSwitch') | ||
switchButton.addEventListener('click', function (e) { | ||
e.preventDefault() | ||
const theme = localStorage.getItem('theme') | ||
if (theme === 'dark') { | ||
document.documentElement.removeAttribute('data-theme') | ||
localStorage.setItem('theme', 'light') | ||
} else if (theme === 'light') { | ||
document.documentElement.setAttribute('data-theme', 'dark') | ||
localStorage.setItem('theme', 'dark') | ||
} else if (systemInitiatedDark.matches) { | ||
document.documentElement.removeAttribute('data-theme') | ||
localStorage.setItem('theme', 'light') | ||
} else { | ||
document.documentElement.setAttribute('data-theme', 'dark') | ||
localStorage.setItem('theme', 'dark') | ||
} | ||
theme = theme === 'dark' ? 'light' : 'dark' | ||
document.documentElement.setAttribute('data-theme', theme) | ||
localStorage.setItem('theme', theme) | ||
}) | ||
})() |