Created
December 24, 2019 10:29
-
-
Save 0x30/f3550c4aeb87566ed01048ab56b279a3 to your computer and use it in GitHub Desktop.
JavaScript change dark mode
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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