Created
January 4, 2021 19:27
-
-
Save onurkerimov/526a55bf5915f23e143089cf4d76cbdb to your computer and use it in GitHub Desktop.
Dark mode detection with MutationObserver API
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
const htmlTag = document.querySelector('html') | |
const checkDarkMode = () => htmlTag.hasAttribute('dark') | |
const watchDarkMode = (onChange) => { | |
let isDark, isDarkBefore | |
isDark = checkDarkMode() | |
onChange(isDark) | |
const observer = new MutationObserver(mutations => { | |
mutations.forEach(mutation => { | |
if (mutation.attributeName === 'dark') { | |
isDark = checkDarkMode() | |
if (isDarkBefore !== isDark) { | |
onChange(isDark) | |
isDarkBefore = isDark | |
} | |
} | |
}) | |
}) | |
const config = { | |
attributes: true, | |
childList: false, | |
subtree: false, | |
} | |
observer.observe(htmlTag, config) | |
} | |
watchDarkMode((isDark) => { | |
// respond to changes here | |
console.log(isDark) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment