Skip to content

Instantly share code, notes, and snippets.

@onurkerimov
Created January 4, 2021 19:27
Show Gist options
  • Save onurkerimov/526a55bf5915f23e143089cf4d76cbdb to your computer and use it in GitHub Desktop.
Save onurkerimov/526a55bf5915f23e143089cf4d76cbdb to your computer and use it in GitHub Desktop.
Dark mode detection with MutationObserver API
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