-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththeme-switcher.js.download
69 lines (56 loc) · 1.94 KB
/
theme-switcher.js.download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/**
* Switch between light and dark themes (color modes)
* Copyright 2023 Createx Studio
*/
(() => {
'use strict'
const getStoredTheme = () => localStorage.getItem('theme')
const setStoredTheme = theme => localStorage.setItem('theme', theme)
const getPreferredTheme = () => {
const storedTheme = getStoredTheme()
if (storedTheme) {
return storedTheme
}
// Set default theme to 'light'.
// Possible options: 'dark' or system color mode (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light')
return 'light'
}
const setTheme = theme => {
if (theme === 'auto' && window.matchMedia('(prefers-color-scheme: dark)').matches) {
document.documentElement.setAttribute('data-bs-theme', 'dark')
} else {
document.documentElement.setAttribute('data-bs-theme', theme)
}
}
setTheme(getPreferredTheme())
const showActiveTheme = (theme) => {
const themeSwitcher = document.querySelector('[data-bs-toggle="mode"]')
if (!themeSwitcher) {
return
}
const themeSwitcherCheck = themeSwitcher.querySelector('input[type="checkbox"]')
if (theme === 'dark') {
themeSwitcherCheck.checked = 'checked'
} else {
themeSwitcherCheck.checked = false
}
}
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => {
const storedTheme = getStoredTheme()
if (storedTheme !== 'light' && storedTheme !== 'dark') {
setTheme(getPreferredTheme())
}
})
window.addEventListener('DOMContentLoaded', () => {
showActiveTheme(getPreferredTheme())
document.querySelectorAll('[data-bs-toggle="mode"]')
.forEach(toggle => {
toggle.addEventListener('click', () => {
const theme = toggle.querySelector('input[type="checkbox"]').checked === true ? 'dark' : 'light'
setStoredTheme(theme)
setTheme(theme)
showActiveTheme(theme, true)
})
})
})
})()