Skip to content

Commit

Permalink
Detect system setting darkmode
Browse files Browse the repository at this point in the history
  • Loading branch information
shinyichen committed May 12, 2021
1 parent 997fa44 commit cd438b9
Showing 1 changed file with 15 additions and 9 deletions.
24 changes: 15 additions & 9 deletions src/js/dark-mode-switch.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,36 +5,42 @@
document.body.setAttribute('data-theme', 'dark');
darkSwitch.classList.add('darkModeOn');
darkSwitch.setAttribute('title', 'Turn off dark mode');
if (save) localStorage.setItem('darkSwitch', 'dark');
if (save) localStorage.setItem('darkSwitch', 'on');
};

const turnOffDarkMode = (save) => {
document.body.removeAttribute('data-theme');
darkSwitch.classList.remove('darkModeOn');
darkSwitch.setAttribute('title', 'Turn on dark mode');
if (save) localStorage.removeItem('darkSwitch');
if (save) localStorage.setItem('darkSwitch', 'off');
};

const init = () => {
const darkThemeSelected =
// 1. check app setting
if (
localStorage.getItem('darkSwitch') !== null &&
localStorage.getItem('darkSwitch') === 'dark';
if (darkThemeSelected) {
localStorage.getItem('darkSwitch') === 'on'
) {
turnOnDarkMode(false);
}
// 2. check system setting
else if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
turnOnDarkMode(false);
} else {
turnOffDarkMode(false);
}
};

const reset = () => {
darkSwitch.classList.contains('darkModeOn') ? turnOffDarkMode(true) : turnOnDarkMode(true);
};
const toggle = () =>
darkSwitch.classList.contains('darkModeOn')
? turnOffDarkMode(true)
: turnOnDarkMode(true);

window.addEventListener('load', function() {
if (darkSwitch) {
init();
darkSwitch.addEventListener('click', function() {
reset();
toggle();
});
}
});
Expand Down

0 comments on commit cd438b9

Please sign in to comment.