portails/assets/js/darkmode.js

39 lines
865 B
JavaScript
Raw Normal View History

2021-09-07 12:08:46 +02:00
const mode = document.getElementById('mode');
2021-09-07 12:08:46 +02:00
if (mode !== null) {
2021-09-07 12:08:46 +02:00
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', event => {
2021-09-07 12:08:46 +02:00
if (event.matches) {
2021-09-07 12:08:46 +02:00
localStorage.setItem('theme', 'dark');
document.documentElement.setAttribute('data-dark-mode', '');
} else {
localStorage.setItem('theme', 'light');
document.documentElement.removeAttribute('data-dark-mode');
}
})
mode.addEventListener('click', () => {
document.documentElement.toggleAttribute('data-dark-mode');
localStorage.setItem('theme', document.documentElement.hasAttribute('data-dark-mode') ? 'dark' : 'light');
});
if (localStorage.getItem('theme') === 'dark') {
document.documentElement.setAttribute('data-dark-mode', '');
} else {
document.documentElement.removeAttribute('data-dark-mode');
}
}