Skip to content

Instantly share code, notes, and snippets.

@0x30
Created December 24, 2019 10:29
Show Gist options
  • Save 0x30/f3550c4aeb87566ed01048ab56b279a3 to your computer and use it in GitHub Desktop.
Save 0x30/f3550c4aeb87566ed01048ab56b279a3 to your computer and use it in GitHub Desktop.
JavaScript change dark mode
// Query for the toggle that is used to change between themes
const toggle = document.querySelector('#themeToggle');
// Listen for the toggle check/uncheck to toggle the dark class on the <body>
toggle.addEventListener('ionChange', (ev) => {
document.body.classList.toggle('dark', ev.detail.checked);
});
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)');
// Listen for changes to the prefers-color-scheme media query
prefersDark.addListener((e) => checkToggle(e.matches));
// Called when the app loads
function loadApp() {
checkToggle(prefersDark.matches);
}
// Called by the media query to check/uncheck the toggle
function checkToggle(shouldCheck) {
toggle.checked = shouldCheck;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment