Skip to content

Commit

Permalink
Detect if user has prefers-dark-mode setting on
Browse files Browse the repository at this point in the history
Attempt to fulfill issue coliff#2
  • Loading branch information
popoway committed Dec 2, 2019
1 parent 24a432f commit c11cd31
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 3 deletions.
14 changes: 12 additions & 2 deletions dark-mode-switch.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,22 @@ window.addEventListener('load', () => {
* @return {void}
*/
function initTheme() {
const systemPrefersDarkMode = window.matchMedia("(prefers-color-scheme: dark)").matches;
const darkThemeSelected =
localStorage.getItem('darkSwitch') !== null &&
localStorage.getItem('darkSwitch') === 'dark';
darkSwitch.checked = darkThemeSelected;
darkThemeSelected ? document.body.setAttribute('data-theme', 'dark') :
if (darkThemeSelected) {
darkSwitch.checked = true;
document.body.setAttribute('data-theme', 'dark');
}
else if (systemPrefersDarkMode) {
darkSwitch.checked = true;
document.body.setAttribute('data-theme', 'dark');
}
else {
darkSwitch.checked = false;
document.body.removeAttribute('data-theme');
}
}


Expand Down
2 changes: 1 addition & 1 deletion index.html
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ <h3 class="float-left">Dark Mode Switch</h3>
<label class="custom-control-label" for="darkSwitch">Dark Mode</label>
</div>

<script src="dark-mode-switch.min.js"></script>
<script src="dark-mode-switch.js"></script>

</div>
</nav>
Expand Down

1 comment on commit c11cd31

@rugk
Copy link

@rugk rugk commented on c11cd31 Jan 18, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So why did not you contribute this change upstream? I.e. your linked coliff#2?

Please sign in to comment.