Skip to content

Instantly share code, notes, and snippets.

@crashmax-dev
Last active September 9, 2021 18:04
Show Gist options
  • Save crashmax-dev/6c22a9d8c65c826b7c30356be0e4838a to your computer and use it in GitHub Desktop.
Save crashmax-dev/6c22a9d8c65c826b7c30356be0e4838a to your computer and use it in GitHub Desktop.
theme.js
<input type="checkbox" id="switchTheme">
<label for="switchTheme"></label>
let switcher = document.querySelector('#switchTheme'),
label = document.querySelector('label[for="switchTheme"]')
if (switcher) {
const getTheme = localStorage.getItem('theme') === null || localStorage.getItem('theme') === 'dark'
if (getTheme) {
switcher.checked = true
}
switchTheme()
switcher.addEventListener('change', () => {
switchTheme()
})
}
function switchTheme() {
if (switcher.checked) {
label.textContent = '🌚'
document.body.setAttribute('data-theme', 'dark')
localStorage.setItem('theme', 'dark')
} else {
label.textContent = '🌞'
document.body.setAttribute('data-theme', 'default')
localStorage.setItem('theme', 'default')
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment