mirror of
https://github.com/lukin/keywind.git
synced 2025-01-26 01:06:25 +00:00
feat(darkmode): add function to switch darkmode by user preference
This commit is contained in:
parent
817ba75423
commit
9c804c93ef
1 changed files with 32 additions and 1 deletions
33
src/index.ts
33
src/index.ts
|
@ -2,6 +2,37 @@ import './index.css';
|
||||||
|
|
||||||
import Alpine from 'alpinejs';
|
import Alpine from 'alpinejs';
|
||||||
|
|
||||||
|
function setColorScheme(scheme: string) {
|
||||||
|
const htmlElement = document.querySelector(':root') as HTMLHtmlElement
|
||||||
|
if (scheme == 'dark') {
|
||||||
|
htmlElement.classList.add('dark');
|
||||||
|
} else {
|
||||||
|
htmlElement.classList.remove('dark')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function getPreferredColorScheme() {
|
||||||
|
if (window.matchMedia) {
|
||||||
|
if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
|
||||||
|
return 'dark';
|
||||||
|
} else {
|
||||||
|
return 'light';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return 'light';
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateColorScheme() {
|
||||||
|
setColorScheme(getPreferredColorScheme());
|
||||||
|
}
|
||||||
|
|
||||||
|
if (window.matchMedia) {
|
||||||
|
var colorSchemeQuery = window.matchMedia('(prefers-color-scheme: dark)');
|
||||||
|
colorSchemeQuery.addEventListener('change', updateColorScheme);
|
||||||
|
}
|
||||||
|
|
||||||
|
updateColorScheme();
|
||||||
|
|
||||||
window.Alpine = Alpine;
|
window.Alpine = Alpine;
|
||||||
|
|
||||||
Alpine.start();
|
Alpine.start();
|
Loading…
Reference in a new issue