Skip to content

Instantly share code, notes, and snippets.

@alex-streza
Created July 31, 2022 11:48
Show Gist options
  • Save alex-streza/400c6536e4496a7da9253f9a1bfde42d to your computer and use it in GitHub Desktop.
Save alex-streza/400c6536e4496a7da9253f9a1bfde42d to your computer and use it in GitHub Desktop.
Script to add root class in accordance to dark mode preferences or local storage saved value.
const theme = (() => {
let theme = 'light'
if (typeof localStorage !== 'undefined' && localStorage.getItem('theme')) {
theme = localStorage.getItem('theme')
} else if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
theme = 'dark'
}
window.localStorage.setItem('theme', theme)
return theme
})()
if (theme.includes('light')) {
document.documentElement.classList.remove('dark')
} else {
document.documentElement.classList.add('dark')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment