You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
30 lines
841 B
JavaScript
30 lines
841 B
JavaScript
3 years ago
|
const userPref = window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark'
|
||
|
const currentTheme = localStorage.getItem('theme') ?? userPref
|
||
|
|
||
|
if (currentTheme) {
|
||
|
document.documentElement.setAttribute('saved-theme', currentTheme);
|
||
|
}
|
||
|
|
||
|
const switchTheme = (e) => {
|
||
|
if (e.target.checked) {
|
||
|
document.documentElement.setAttribute('saved-theme', 'dark')
|
||
|
localStorage.setItem('theme', 'dark')
|
||
|
}
|
||
|
else {
|
||
|
document.documentElement.setAttribute('saved-theme', 'light')
|
||
|
localStorage.setItem('theme', 'light')
|
||
|
}
|
||
|
}
|
||
|
|
||
3 years ago
|
window.addEventListener('DOMContentLoaded', () => {
|
||
|
// Darkmode toggle
|
||
|
const toggleSwitch = document.querySelector('#darkmode-toggle')
|
||
|
|
||
|
// listen for toggle
|
||
|
toggleSwitch.addEventListener('change', switchTheme, false)
|
||
|
|
||
|
if (currentTheme === 'dark') {
|
||
|
toggleSwitch.checked = true
|
||
|
}
|
||
|
})
|